From fc5262f36e50f96626e159c491443f1f81f816bc Mon Sep 17 00:00:00 2001 From: Srinath Narayanan Date: Wed, 8 May 2019 15:48:33 -0700 Subject: [PATCH 01/85] Porting V3 OM changes from VSTS to Github (#98) * inital commit for V3 port from vsts to github * Hash v2 for SDK v3 bumped version to 3.0.0-beta-3 for release * Modified Pom file to copy jar files to required location * updated sdk-version property * removed additions to pom * Removing unused code Changing version to 3.0.0-SNAPSHOT --- benchmark/pom.xml | 2 +- commons-test-utils/pom.xml | 2 +- commons/pom.xml | 2 +- .../cosmosdb/PartitionKeyDefinition.java | 22 +- .../PartitionKeyDefinitionVersion.java | 2 +- .../cosmosdb/internal/HttpConstants.java | 2 +- direct-impl/pom.xml | 4 +- .../cosmosdb/PartitionKeyHashingTests.java | 94 +++ examples/pom.xml | 2 +- .../cosmos/examples/AccountSettings.java | 59 ++ .../azure/cosmos/examples/BasicDemo.java | 220 ++++++++ gateway/pom.xml | 2 +- pom.xml | 17 +- sdk/pom.xml | 31 +- .../microsoft/azure/cosmos/CosmosClient.java | 252 +++++++++ .../azure/cosmos/CosmosConfiguration.java | 159 ++++++ .../azure/cosmos/CosmosContainer.java | 533 ++++++++++++++++++ .../cosmos/CosmosContainerRequestOptions.java | 122 ++++ .../azure/cosmos/CosmosContainerResponse.java | 57 ++ .../azure/cosmos/CosmosContainerSettings.java | 187 ++++++ .../azure/cosmos/CosmosDatabase.java | 301 ++++++++++ .../cosmos/CosmosDatabaseRequestOptions.java | 57 ++ .../azure/cosmos/CosmosDatabaseResponse.java | 75 +++ .../azure/cosmos/CosmosDatabaseSettings.java | 64 +++ .../azure/cosmos/CosmosFeedResponse.java | 52 ++ .../microsoft/azure/cosmos/CosmosItem.java | 209 +++++++ .../cosmos/CosmosItemRequestOptions.java | 174 ++++++ .../azure/cosmos/CosmosItemResponse.java | 48 ++ .../azure/cosmos/CosmosRequestOptions.java | 57 ++ .../azure/cosmos/CosmosResource.java | 70 +++ .../azure/cosmos/CosmosResponse.java | 138 +++++ .../azure/cosmos/CosmosStoredProcedure.java | 127 +++++ .../CosmosStoredProcedureRequestOptions.java | 99 ++++ .../cosmos/CosmosStoredProcedureResponse.java | 132 +++++ .../cosmos/CosmosStoredProcedureSettings.java | 57 ++ .../microsoft/azure/cosmos/CosmosTrigger.java | 110 ++++ .../azure/cosmos/CosmosTriggerResponse.java | 56 ++ .../azure/cosmos/CosmosTriggerSettings.java | 56 ++ .../cosmos/CosmosUserDefinedFunction.java | 109 ++++ .../CosmosUserDefinedFunctionResponse.java | 56 ++ .../CosmosUserDefinedFunctionSettings.java | 56 ++ .../azure/cosmos/CosmosContainerCrudTest.java | 163 ++++++ .../azure/cosmos/CosmosDatabaseCrudTest.java | 141 +++++ .../azure/cosmos/CosmosItemCrudTest.java | 147 +++++ .../azure/cosmos/CosmosResponseValidator.java | 109 ++++ .../azure/cosmos/CosmosTestSuiteBase.java | 176 ++++++ 46 files changed, 4594 insertions(+), 16 deletions(-) create mode 100644 direct-impl/src/test/java/com/microsoft/azure/cosmosdb/PartitionKeyHashingTests.java create mode 100644 examples/src/main/java/com/microsoft/azure/cosmos/examples/AccountSettings.java create mode 100644 examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosConfiguration.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerResponse.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedure.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureResponse.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTrigger.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunction.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java create mode 100644 sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java create mode 100644 sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java create mode 100644 sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java create mode 100644 sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java create mode 100644 sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java diff --git a/benchmark/pom.xml b/benchmark/pom.xml index 675e338ae224d..7e3a747891512 100644 --- a/benchmark/pom.xml +++ b/benchmark/pom.xml @@ -29,7 +29,7 @@ com.microsoft.azure azure-cosmosdb-parent - 2.4.5-SNAPSHOT + 3.0.0-SNAPSHOT azure-cosmosdb-benchmark diff --git a/commons-test-utils/pom.xml b/commons-test-utils/pom.xml index 6acc0c8717c25..977a5a5822a00 100644 --- a/commons-test-utils/pom.xml +++ b/commons-test-utils/pom.xml @@ -28,7 +28,7 @@ SOFTWARE. com.microsoft.azure azure-cosmosdb-parent - 2.4.5-SNAPSHOT + 3.0.0-SNAPSHOT azure-cosmosdb-commons-test-utils Common Test Components for Testing Async SDK for SQL API of Azure Cosmos DB Service diff --git a/commons/pom.xml b/commons/pom.xml index 3e92a416bc1ee..2db549d7278de 100644 --- a/commons/pom.xml +++ b/commons/pom.xml @@ -27,7 +27,7 @@ SOFTWARE. com.microsoft.azure azure-cosmosdb-parent - 2.4.5-SNAPSHOT + 3.0.0-SNAPSHOT azure-cosmosdb-commons Common Components for Async SDK for SQL API of Azure Cosmos DB Service diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java index b1f143cba43f4..e9f71e9928b0a 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java @@ -24,10 +24,14 @@ package com.microsoft.azure.cosmosdb; import com.microsoft.azure.cosmosdb.internal.Constants; +import com.microsoft.azure.cosmosdb.rx.internal.Strings; import java.util.ArrayList; import java.util.List; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.WordUtils; + /** * Represents a partition key definition in the Azure Cosmos DB database service. A partition key definition specifies which * document property is used as the partition key in a collection that has multiple partitions. @@ -76,15 +80,27 @@ public void setKind(PartitionKind kind) { this.kind = kind; } - PartitionKeyDefinitionVersion getVersion() { + public PartitionKeyDefinitionVersion getVersion() { if (this.version == null) { - version = super.getObject(Constants.Properties.PARTITION_KEY_DEFINITION_VERSION, PartitionKeyDefinitionVersion.class); + Object versionObject = super.getObject(Constants.Properties.PARTITION_KEY_DEFINITION_VERSION, Object.class); + if (versionObject == null) { + this.version = null; + } else { + String versionStr = String.valueOf(versionObject); + if (StringUtils.isNumeric(versionStr)) { + this.version = PartitionKeyDefinitionVersion.valueOf(String.format("V%d", Integer.parseInt(versionStr))); + } else { + this.version = !Strings.isNullOrEmpty(versionStr) + ? PartitionKeyDefinitionVersion.valueOf(WordUtils.capitalize(versionStr)) + : null; + } + } } return this.version; } - void setVersion(PartitionKeyDefinitionVersion version) { + public void setVersion(PartitionKeyDefinitionVersion version) { this.version = version; } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinitionVersion.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinitionVersion.java index 27353df603b20..096f2dc054f9f 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinitionVersion.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinitionVersion.java @@ -26,7 +26,7 @@ /** * Partitioning version. */ -enum PartitionKeyDefinitionVersion { +public enum PartitionKeyDefinitionVersion { /** * Original version of hash partitioning. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java index c4860b6a54821..2a90ef59c029c 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java @@ -269,7 +269,7 @@ public static class Versions { // TODO: FIXME we can use maven plugin for generating a version file // @see https://stackoverflow.com/questions/2469922/generate-a-version-java-file-in-maven - public static final String SDK_VERSION = "2.4.5-SNAPSHOT"; + public static final String SDK_VERSION = "3.0.0-SNAPSHOT"; public static final String SDK_NAME = "cosmosdb-java-sdk"; } diff --git a/direct-impl/pom.xml b/direct-impl/pom.xml index 28cdafba89aea..407e05f2cc06c 100644 --- a/direct-impl/pom.xml +++ b/direct-impl/pom.xml @@ -27,14 +27,14 @@ SOFTWARE. com.microsoft.azure azure-cosmosdb-direct Azure Cosmos DB Async SDK Direct Internal Implementation - 2.4.5-SNAPSHOT + 3.0.0-SNAPSHOT Azure Cosmos DB Async SDK Direct Internal Implementation https://docs.microsoft.com/en-us/azure/cosmos-db jar UTF-8 unit - 2.4.5-SNAPSHOT + 3.0.0-SNAPSHOT 27.0.1-jre diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/PartitionKeyHashingTests.java b/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/PartitionKeyHashingTests.java new file mode 100644 index 0000000000000..72b83febf4229 --- /dev/null +++ b/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/PartitionKeyHashingTests.java @@ -0,0 +1,94 @@ +package com.microsoft.azure.cosmosdb; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.fasterxml.jackson.databind.node.NullNode; +import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternalHelper; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +public class PartitionKeyHashingTests { + + @Test(groups = "unit") + public void effectivePartitionKeyHashV1() { + HashMap keyToEffectivePartitionKeyString = new HashMap() {{ + put("", "05C1CF33970FF80800"); + put("partitionKey", "05C1E1B3D9CD2608716273756A756A706F4C667A00"); + put(new String(new char[1024]).replace("\0", "a"), "05C1EB5921F706086262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626200"); + put(null, "05C1ED45D7475601"); + put(NullNode.getInstance(), "05C1ED45D7475601"); + put(Undefined.Value(), "05C1D529E345DC00"); + put(true, "05C1D7C5A903D803"); + put(false, "05C1DB857D857C02"); + put(Byte.MIN_VALUE, "05C1D73349F54C053FA0"); + put(Byte.MAX_VALUE, "05C1DD539DDFCC05C05FE0"); + put(Long.MIN_VALUE, "05C1DB35F33D1C053C20"); + put(Long.MAX_VALUE, "05C1B799AB2DD005C3E0"); + put(Integer.MIN_VALUE, "05C1DFBF252BCC053E20"); + put(Integer.MAX_VALUE, "05C1E1F503DFB205C1DFFFFFFFFC"); + put(Double.MIN_VALUE, "05C1E5C91F4D3005800101010101010102"); + put(Double.MAX_VALUE, "05C1CBE367C53005FFEFFFFFFFFFFFFFFE"); + }}; + + for (Map.Entry entry : keyToEffectivePartitionKeyString.entrySet()) { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + partitionKeyDef.setKind(PartitionKind.Hash); + partitionKeyDef.setPaths(Arrays.asList(new String[]{"\\id"})); + String actualEffectiveKeyString = PartitionKeyInternalHelper.getEffectivePartitionKeyString(new PartitionKey(entry.getKey()).getInternalPartitionKey(),partitionKeyDef, true); + assertThat(entry.getValue()).isEqualTo(actualEffectiveKeyString); + } + } + + @Test(groups = "unit") + public void effectivePartitionKeyHashV2() { + HashMap keyToEffectivePartitionKeyString = new HashMap() {{ + put("", "32E9366E637A71B4E710384B2F4970A0"); + put("partitionKey", "013AEFCF77FA271571CF665A58C933F1"); + put(new String(new char[1024]).replace("\0", "a"), "332BDF5512AE49615F32C7D98C2DB86C"); + put(null, "378867E4430E67857ACE5C908374FE16"); + put(NullNode.getInstance(), "378867E4430E67857ACE5C908374FE16"); + put(Undefined.Value(), "11622DAA78F835834610ABE56EFF5CB5"); + put(true, "0E711127C5B5A8E4726AC6DD306A3E59"); + put(false, "2FE1BE91E90A3439635E0E9E37361EF2"); + put(Byte.MIN_VALUE, "01DAEDABF913540367FE219B2AD06148"); + put(Byte.MAX_VALUE, "0C507ACAC853ECA7977BF4CEFB562A25"); + put(Long.MIN_VALUE, "23D5C6395512BDFEAFADAD15328AD2BB"); + put(Long.MAX_VALUE, "2EDB959178DFCCA18983F89384D1629B"); + put(Integer.MIN_VALUE, "0B1660D5233C3171725B30D4A5F4CC1F"); + put(Integer.MAX_VALUE, "2D9349D64712AEB5EB1406E2F0BE2725"); + put(Double.MIN_VALUE, "0E6CBA63A280927DE485DEF865800139"); + put(Double.MAX_VALUE, "31424D996457102634591FF245DBCC4D"); + }}; + + for (Map.Entry entry : keyToEffectivePartitionKeyString.entrySet()) { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + partitionKeyDef.setKind(PartitionKind.Hash); + partitionKeyDef.setVersion(PartitionKeyDefinitionVersion.V2); + partitionKeyDef.setPaths(Arrays.asList(new String[]{"\\id"})); + String actualEffectiveKeyString = PartitionKeyInternalHelper.getEffectivePartitionKeyString(new PartitionKey(entry.getKey()).getInternalPartitionKey(),partitionKeyDef, true); + assertThat(entry.getValue()).isEqualTo(actualEffectiveKeyString); + } + } + + @Test(groups = "unit") + public void hashV2PartitionKeyDeserialization() { + String partitionKeyDefinitionStr = "{\"paths\":[\"/pk\"],\"kind\":\"Hash\",\"version\":2}"; + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(partitionKeyDefinitionStr); + assertThat(partitionKeyDef.getVersion()).isEqualTo(PartitionKeyDefinitionVersion.V2); + assertThat(partitionKeyDef.getKind()).isEqualTo(PartitionKind.Hash); + assertThat(partitionKeyDef.getPaths().toArray()[0]).isEqualTo("/pk"); + } + + @Test(groups = "unit") + public void hashV1PartitionKeyDeserialization() { + String partitionKeyDefinitionStr = "{\"paths\":[\"/pk\"],\"kind\":\"Hash\"}"; + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(partitionKeyDefinitionStr); + assertThat(partitionKeyDef.getVersion()).isNull(); + assertThat(partitionKeyDef.getKind()).isEqualTo(PartitionKind.Hash); + assertThat(partitionKeyDef.getPaths().toArray()[0]).isEqualTo("/pk"); + } +} diff --git a/examples/pom.xml b/examples/pom.xml index f220146a2f56d..f95c90de11847 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -29,7 +29,7 @@ com.microsoft.azure azure-cosmosdb-parent - 2.4.5-SNAPSHOT + 3.0.0-SNAPSHOT azure-cosmosdb-examples diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/AccountSettings.java b/examples/src/main/java/com/microsoft/azure/cosmos/examples/AccountSettings.java new file mode 100644 index 0000000000000..b3fa7538971d4 --- /dev/null +++ b/examples/src/main/java/com/microsoft/azure/cosmos/examples/AccountSettings.java @@ -0,0 +1,59 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.microsoft.azure.cosmos.examples; + +import org.apache.commons.lang3.StringUtils; + +/** + * Contains the account configurations for Sample. + * + * For running tests, you can pass a customized endpoint configuration in one of the following + * ways: + *
    + *
  • -DACCOUNT_KEY="[your-key]" -ACCOUNT_HOST="[your-endpoint]" as JVM + * command-line option.
  • + *
  • You can set ACCOUNT_KEY and ACCOUNT_HOST as environment variables.
  • + *
+ * + * If none of the above is set, emulator endpoint will be used. + * Emulator http cert is self signed. If you are using emulator, + * make sure emulator https certificate is imported + * to java trusted cert store: + * https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator-export-ssl-certificates + */ +public class AccountSettings { + // Replace MASTER_KEY and HOST with values from your Azure Cosmos DB account. + // The default values are credentials of the local emulator, which are not used in any production environment. + public static String MASTER_KEY = + System.getProperty("ACCOUNT_KEY", + StringUtils.defaultString(StringUtils.trimToNull( + System.getenv().get("COSMOS_ACCOUNT_KEY")), + "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==")); + + public static String HOST = + System.getProperty("ACCOUNT_HOST", + StringUtils.defaultString(StringUtils.trimToNull( + System.getenv().get("COSMOS_ACCOUNT_HOST")), + "https://localhost:8081/")); +} diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java b/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java new file mode 100644 index 0000000000000..1fa342e878e82 --- /dev/null +++ b/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java @@ -0,0 +1,220 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.examples; + +import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemResponse; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +public class BasicDemo { + + private static final String DATABASE_NAME = "test_db"; + private static final String CONTAINER_NAME = "test_container"; + + private CosmosClient client; + private CosmosDatabase database; + private CosmosContainer container; + + public static void main(String[] args) { + BasicDemo demo = new BasicDemo(); + demo.start(); + } + + private void start(){ + // Get client + client = CosmosClient.create(AccountSettings.HOST, AccountSettings.MASTER_KEY); + + //Create a database and a container + createDbAndContainerBlocking(); + + //Get a proxy reference to container + container = client.getDatabase(DATABASE_NAME).getContainer(CONTAINER_NAME); + + CosmosContainer container = client.getDatabase(DATABASE_NAME).getContainer(CONTAINER_NAME); + TestObject testObject = new TestObject("item_new_id_1", "test", "test description", "US"); + TestObject testObject2 = new TestObject("item_new_id_2", "test2", "test description2", "CA"); + + //Create an Item async + Mono itemResponseMono = container.createItem(testObject, testObject.country); + //Create another Item async + Mono itemResponseMono1 = container.createItem(testObject2, testObject2.country); + + //Wait for completion + try { + itemResponseMono.doOnError(throwable -> log("Create item 1", throwable)) + .mergeWith(itemResponseMono1) + .doOnError(throwable -> log("Create item 2 ", throwable)) + .doOnComplete(() -> log("Items created")) + .publishOn(Schedulers.elastic()) + .blockLast(); + }catch (RuntimeException e){ + log("Couldn't create items due to above exceptions"); + } + + createAndReplaceItem(); + + queryItems(); + + queryWithContinuationToken(); + + //Close client + client.close(); + log("Completed"); + } + + private void createAndReplaceItem() { + TestObject replaceObject = new TestObject("item_new_id_3", "test3", "test description3", "JP"); + CosmosItem cosmosItem = null; + //Create item sync + try { + cosmosItem = container.createItem(replaceObject, replaceObject.country) + .doOnError(throwable -> log("Create 3", throwable)) + .publishOn(Schedulers.elastic()) + .block() + .getItem(); + }catch (RuntimeException e){ + log("Couldn't create items due to above exceptions"); + } + if(cosmosItem != null) { + cosmosItem.set("new property", "value"); + + //Replace the item and wait for completion + cosmosItem.replace(cosmosItem, new CosmosItemRequestOptions(cosmosItem.get("country"))).block(); + } + } + + private void createDbAndContainerBlocking() { + client.createDatabaseIfNotExists(DATABASE_NAME) + .doOnSuccess(cosmosDatabaseResponse -> log("Database: " + cosmosDatabaseResponse.getDatabase().getId())) + .flatMap(dbResponse -> dbResponse.getDatabase().createContainerIfNotExists(new CosmosContainerSettings(CONTAINER_NAME, "/country"))) + .doOnSuccess(cosmosContainerResponse -> log("Container: " + cosmosContainerResponse.getContainer().getId())) + .doOnError(throwable -> log(throwable.getMessage())) + .publishOn(Schedulers.elastic()) + .block(); + } + + int count = 0; + private void queryItems(){ + log("+ Querying the collection "); + String query = "SELECT * from root"; + FeedOptions options = new FeedOptions(); + options.setEnableCrossPartitionQuery(true); + options.setMaxDegreeOfParallelism(2); + Flux> queryFlux = container.queryItems(query, options); + + queryFlux.publishOn(Schedulers.elastic()).subscribe(cosmosItemFeedResponse -> {}, + throwable -> {}, + () -> {}); + + queryFlux.publishOn(Schedulers.elastic()) + .toIterable() + .forEach(cosmosItemFeedResponse -> + { + log(cosmosItemFeedResponse.getResults()); + }); + + } + + private void queryWithContinuationToken(){ + log("+ Query with paging using continuation token"); + String query = "SELECT * from root r "; + FeedOptions options = new FeedOptions(); + options.setEnableCrossPartitionQuery(true); + options.setPopulateQueryMetrics(true); + options.setMaxItemCount(1); + String continuation = null; + do{ + options.setRequestContinuation(continuation); + Flux> queryFlux = container.queryItems(query, options); + FeedResponse page = queryFlux.blockFirst(); + assert page != null; + log(page.getResults()); + continuation = page.getResponseContinuation(); + }while(continuation!= null); + + } + + private void log(Object object) { + System.out.println(object); + } + + private void log(String msg, Throwable throwable){ + log(msg + ": " + ((DocumentClientException)throwable).getStatusCode()); + } + + class TestObject { + String id; + String name; + String description; + String country; + + public TestObject(String id, String name, String description, String country) { + this.id = id; + this.name = name; + this.description = description; + this.country = country; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + } +} diff --git a/gateway/pom.xml b/gateway/pom.xml index 0196873e0eda9..ff0f98aef71d2 100644 --- a/gateway/pom.xml +++ b/gateway/pom.xml @@ -27,7 +27,7 @@ SOFTWARE. com.microsoft.azure azure-cosmosdb-parent - 2.4.5-SNAPSHOT + 3.0.0-SNAPSHOT azure-cosmosdb-gateway Common Gateway Components for Async SDK for SQL API of Azure Cosmos DB Service diff --git a/pom.xml b/pom.xml index da7184b4bb577..840ec341e97b2 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ 4.0.0 com.microsoft.azure azure-cosmosdb-parent - 2.4.5-SNAPSHOT + 3.0.0-SNAPSHOT pom Azure Cosmos DB SQL API Java Async SDK (with Reactive Extension RX support) for Azure Cosmos DB SQL API @@ -56,13 +56,17 @@ 1.3.8 0.8.0.17 1.1.1 + 3.2.2.RELEASE 6.14.3 3.11.1 1.10.19 27.0.1-jre + 0.13.3 + 2.2.4 1.6 + Bismuth-RELEASE unit - 2.4.5-SNAPSHOT + 3.0.0-SNAPSHOT @@ -91,7 +95,7 @@ fast - simple + simple,cosmosv3 @@ -334,6 +338,13 @@ azure-cosmosdb-commons-test-utils ${project.parent.version} + + io.projectreactor + reactor-bom + ${reactor-bom.version} + pom + import + diff --git a/sdk/pom.xml b/sdk/pom.xml index e57cdcb5bf302..05b3cdf373792 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -27,7 +27,7 @@ SOFTWARE. com.microsoft.azure azure-cosmosdb-parent - 2.4.5-SNAPSHOT + 3.0.0-SNAPSHOT azure-cosmosdb Async SDK for SQL API of Azure Cosmos DB Service @@ -191,6 +191,10 @@ SOFTWARE. rxjava-string ${rxjava-string.version} + + io.projectreactor + reactor-core + io.reactivex rxnetty @@ -263,5 +267,30 @@ SOFTWARE. ${guava.version} test + + io.projectreactor.addons + reactor-adapter + ${reactor-addons.version} + test + + + io.projectreactor + reactor-test + test + + + com.github.akarnokd + rxjava2-interop + ${rxjava2interop.verison} + + + io.reactivex.rxjava2 + rxjava + ${rxjava2.version} + + + io.projectreactor.addons + reactor-adapter + diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java new file mode 100644 index 0000000000000..3e81053a1d214 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java @@ -0,0 +1,252 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.BridgeInternal; +import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.SqlQuerySpec; +import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Provides a client-side logical representation of the Azure Cosmos database service. + * This asynchronous client is used to configure and execute requests + * against the service. + */ + public class CosmosClient { + + //Document client wrapper + private AsyncDocumentClient asyncDocumentClient; + + /** + * Creates a cosmos client with given cosmosConfiguration + * @param cosmosConfiguration the cosmosConfiguration + * @return cosmos client + */ + public static CosmosClient create(CosmosConfiguration cosmosConfiguration) { + return new CosmosClient(cosmosConfiguration); + } + + /** + * Creates a cosmos client with given endpoint and key + * @param endpoint the service end point + * @param key the key + * @return cosmos clients + */ + public static CosmosClient create(String endpoint, String key) { + CosmosConfiguration cosmosConfiguration = new CosmosConfiguration.Builder() + .withServiceEndpoint(endpoint) + .withKeyOrResourceToken(key).build(); + return create(cosmosConfiguration); + } + + /** + * Creates a cosmos client with given cosmos configuration + * @param cosmosConfiguration the cosmos configuration + */ + private CosmosClient(CosmosConfiguration cosmosConfiguration) { + this.asyncDocumentClient = new AsyncDocumentClient.Builder() + .withServiceEndpoint(cosmosConfiguration.getServiceEndpoint().toString()) + .withMasterKeyOrResourceToken(cosmosConfiguration.getKeyOrResourceToken()) + .withConnectionPolicy(cosmosConfiguration.getConnectionPolicy()) + .withConsistencyLevel(cosmosConfiguration.getDesiredConsistencyLevel()) + .build(); + } + + AsyncDocumentClient getDocClientWrapper(){ + return asyncDocumentClient; + } + + /** + * Create a Database if it does not already exist on the service + * + * The {@link Mono} upon successful completion will contain a single cosmos database response with the + * created or existing database. + * @param databaseSettings CosmosDatabaseSettings + * @return a {@link Mono} containing the cosmos database response with the created or existing database or + * an error. + */ + public Mono createDatabaseIfNotExists(CosmosDatabaseSettings databaseSettings) { + return createDatabaseIfNotExistsInternal(getDatabase(databaseSettings.getId())); + } + + /** + * Create a Database if it does not already exist on the service + * The {@link Mono} upon successful completion will contain a single cosmos database response with the + * created or existing database. + * @param id the id of the database + * @return a {@link Mono} containing the cosmos database response with the created or existing database or + * an error + */ + public Mono createDatabaseIfNotExists(String id) { + return createDatabaseIfNotExistsInternal(getDatabase(id)); + } + + private Mono createDatabaseIfNotExistsInternal(CosmosDatabase database){ + return database.read().onErrorResume(exception -> { + if (exception instanceof DocumentClientException) { + DocumentClientException documentClientException = (DocumentClientException) exception; + if (documentClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { + return createDatabase(new CosmosDatabaseSettings(database.getId()), new CosmosDatabaseRequestOptions()); + } + } + return Mono.error(exception); + }); + } + + /** + * Creates a database. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the + * created database. + * In case of failure the {@link Mono} will error. + * + * @param databaseSettings {@link CosmosDatabaseSettings} + * @param options {@link CosmosDatabaseRequestOptions} + * @return an {@link Mono} containing the single cosmos database response with the created database or an error. + */ + public Mono createDatabase(CosmosDatabaseSettings databaseSettings, + CosmosDatabaseRequestOptions options) { + Database wrappedDatabase = new Database(); + wrappedDatabase.setId(databaseSettings.getId()); + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(asyncDocumentClient.createDatabase(wrappedDatabase, options.toRequestOptions()).map(databaseResourceResponse -> + new CosmosDatabaseResponse(databaseResourceResponse, this)).toSingle())); + } + + /** + * Creates a database. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the + * created database. + * In case of failure the {@link Mono} will error. + * + * @param databaseSettings {@link CosmosDatabaseSettings} + * @return an {@link Mono} containing the single cosmos database response with the created database or an error. + */ + public Mono createDatabase(CosmosDatabaseSettings databaseSettings) { + return createDatabase(databaseSettings, new CosmosDatabaseRequestOptions()); + } + + /** + * Creates a database. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the + * created database. + * In case of failure the {@link Mono} will error. + * + * @param id id of the database + * @return a {@link Mono} containing the single cosmos database response with the created database or an error. + */ + public Mono createDatabase(String id) { + return createDatabase(new CosmosDatabaseSettings(id), new CosmosDatabaseRequestOptions()); + } + + /** + * Reads all databases. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the read databases. + * In case of failure the {@link Flux} will error. + * + * @param options {@link FeedOptions} + * @return a {@link Flux} containing one or several feed response pages of read databases or an error. + */ + public Flux> listDatabases(FeedOptions options) { + return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().readDatabases(options) + .map(response-> BridgeInternal.createFeedResponse(CosmosDatabaseSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + /** + * Reads all databases. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the read databases. + * In case of failure the {@link Flux} will error. + * + * @return a {@link Flux} containing one or several feed response pages of read databases or an error. + */ + public Flux> listDatabases() { + return listDatabases(new FeedOptions()); + } + + + /** + * Query for databases. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the read databases. + * In case of failure the {@link Flux} will error. + * + * @param query the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of read databases or an error. + */ + public Flux> queryDatabases(String query, FeedOptions options){ + return queryDatabases(new SqlQuerySpec(query), options); + } + + /** + * Query for databases. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the read databases. + * In case of failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of read databases or an error. + */ + public Flux> queryDatabases(SqlQuerySpec querySpec, FeedOptions options){ + return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().queryDatabases(querySpec, options) + .map(response-> BridgeInternal.createFeedResponse( + CosmosDatabaseSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + /** + * Gets a database object without making a service call. + * @param id name of the database + * @return + */ + public CosmosDatabase getDatabase(String id) { + return new CosmosDatabase(id, this); + } + + /** + * Close this {@link CosmosClient} instance and cleans up the resources. + */ + public void close() { + asyncDocumentClient.close(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosConfiguration.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosConfiguration.java new file mode 100644 index 0000000000000..3e111f4c692d2 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosConfiguration.java @@ -0,0 +1,159 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ConnectionPolicy; +import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.microsoft.azure.cosmosdb.Permission; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +public class CosmosConfiguration { + private URI serviceEndpoint; + private String keyOrResourceToken; + private ConnectionPolicy connectionPolicy; + private ConsistencyLevel desiredConsistencyLevel; + private List permissions; + + private CosmosConfiguration(Builder builder) { + this.serviceEndpoint = builder.serviceEndpoint; + this.keyOrResourceToken = builder.keyOrResourceToken; + this.connectionPolicy = builder.connectionPolicy; + this.desiredConsistencyLevel = builder.desiredConsistencyLevel; + this.permissions = builder.permissions; + } + + public static class Builder { + + URI serviceEndpoint; + String keyOrResourceToken; + ConnectionPolicy connectionPolicy; //can set a default value here + ConsistencyLevel desiredConsistencyLevel; //can set a default value here + List permissions; //can set a default value here + int eventLoopSize = -1; + + public Builder withServiceEndpoint(String serviceEndpoint) { + try { + this.serviceEndpoint = new URI(serviceEndpoint); + } catch (URISyntaxException e) { + throw new IllegalArgumentException(e.getMessage()); + } + return this; + } + + /** + * This method will take either key or resource token and perform authentication + * for accessing resource. + * + * @param keyOrResourceToken key or resourceToken for authentication . + * @return current Builder. + */ + public Builder withKeyOrResourceToken(String keyOrResourceToken) { + this.keyOrResourceToken = keyOrResourceToken; + return this; + } + + /** + * This method will accept the permission list , which contains the + * resource tokens needed to access resources. + * + * @param permissions Permission list for authentication. + * @return current Builder. + */ + public Builder withPermissions(List permissions) { + this.permissions = permissions; + return this; + } + + /** + * This method accepts the (@link ConsistencyLevel) to be used + * @param desiredConsistencyLevel (@link ConsistencyLevel) + * @return + */ + public Builder withConsistencyLevel(ConsistencyLevel desiredConsistencyLevel) { + this.desiredConsistencyLevel = desiredConsistencyLevel; + return this; + } + + /** + * The (@link ConnectionPolicy) to be used + * @param connectionPolicy + * @return + */ + public Builder withConnectionPolicy(ConnectionPolicy connectionPolicy) { + this.connectionPolicy = connectionPolicy; + return this; + } + + private void ifThrowIllegalArgException(boolean value, String error) { + if (value) { + throw new IllegalArgumentException(error); + } + } + + /** + * Builds a cosmos configuration object with the provided settings + * @return CosmosConfiguration + */ + public CosmosConfiguration build() { + + ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint"); + ifThrowIllegalArgException( + this.keyOrResourceToken == null && (permissions == null || permissions.isEmpty()), + "cannot build client without key or resource token"); + + return new CosmosConfiguration(this); + } + + } + + public URI getServiceEndpoint() { + return serviceEndpoint; + } + + String getKeyOrResourceToken() { + return keyOrResourceToken; + } + + ConnectionPolicy getConnectionPolicy() { + return connectionPolicy; + } + + /** + * Gets the consistency level + * @return the (@link ConsistencyLevel) + */ + public ConsistencyLevel getDesiredConsistencyLevel() { + return desiredConsistencyLevel; + } + + /** + * Gets the permission list + * @return the permission list + */ + public List getPermissions() { + return permissions; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java new file mode 100644 index 0000000000000..3d9a4ce3db4e9 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java @@ -0,0 +1,533 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.BridgeInternal; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.SqlQuerySpec; +import com.microsoft.azure.cosmosdb.StoredProcedure; +import com.microsoft.azure.cosmosdb.Trigger; +import com.microsoft.azure.cosmosdb.UserDefinedFunction; +import com.microsoft.azure.cosmosdb.internal.Paths; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class CosmosContainer extends CosmosResource { + + private CosmosDatabase database; + + CosmosContainer(String id, CosmosDatabase database) { + super(id); + this.database = database; + } + + /** + * Reads the document container + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cossmos container response with the read + * container. + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the single cossmos container response with the read container or an error. + */ + public Mono read() { + return read(new CosmosContainerRequestOptions()); + } + + /** + * Reads the document container by the container link. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cossmos container response with the read container. + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the single cossmos container response with the read container or an error. + */ + public Mono read(CosmosContainerRequestOptions requestOptions) { + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(database.getDocClientWrapper().readCollection(getLink(), + requestOptions.toRequestOptions()) + .map(response -> new CosmosContainerResponse(response, database)).toSingle())); + } + + /** + * Deletes the item container + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cossmos container response for the deleted database. + * In case of failure the {@link Mono} will error. + * + * @param requestOptions the request options. + * @return an {@link Mono} containing the single cossmos container response for the deleted database or an error. + */ + public Mono delete(CosmosContainerRequestOptions requestOptions) { + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(database.getDocClientWrapper() + .deleteCollection(getLink(),requestOptions.toRequestOptions()) + .map(response -> new CosmosContainerResponse(response, database)) + .toSingle())); + } + + /** + * Deletes the item container + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos container response for the deleted container. + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the single cossmos container response for the deleted container or an error. + */ + public Mono delete() { + return delete(new CosmosContainerRequestOptions()); + } + + /** + * Replaces a document container. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cossmos container response with the replaced document container. + * In case of failure the {@link Mono} will error. + * + * @param containerSettings the item container settings + * @param requestOptions the cosmos container request options. + * @return an {@link Mono} containing the single cossmos container response with the replaced document container or an error. + */ + public Mono replace(CosmosContainerSettings containerSettings, + CosmosContainerRequestOptions requestOptions) { + validateResource(containerSettings); + if(requestOptions == null){ + requestOptions = new CosmosContainerRequestOptions(); + } + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(database.getDocClientWrapper() + .replaceCollection(containerSettings.getV2Collection(),requestOptions.toRequestOptions()) + .map(response -> new CosmosContainerResponse(response, database)) + .toSingle())); + } + + /* CosmosItem operations */ + + /** + * Creates a cosmos item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the created cosmos item. + * In case of failure the {@link Mono} will error. + * + * @param item the cosmos item represented as a POJO or cosmos item object. + * @return an {@link Mono} containing the single resource response with the created cosmos item or an error. + */ + public Mono createItem(Object item){ + return createItem(item, null); + } + + /** + * Creates a cosmos item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the created cosmos item. + * In case of failure the {@link Mono} will error. + * + * @param item the cosmos item represented as a POJO or cosmos item object. + * @param partitionKey the partition key + * @return an {@link Mono} containing the single resource response with the created cosmos item or an error. + */ + public Mono createItem(Object item, Object partitionKey){ + return createItem(item, new CosmosItemRequestOptions(partitionKey)); + } + + /** + * Creates a cosmos item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the created cosmos item. + * In case of failure the {@link Mono} will error. + * + * @param item the cosmos item represented as a POJO or cosmos item object. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the created cosmos item or an error. + */ + public Mono createItem(Object item, CosmosItemRequestOptions options) { + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(database.getDocClientWrapper() + .createDocument(getLink(),CosmosItem.fromObject(item),options.toRequestOptions(), true) + .map(response -> new CosmosItemResponse(response, this)) + .toSingle())); + } + + /** + * Upserts a cosmos item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the upserted item. + * In case of failure the {@link Mono} will error. + * + * @param item the item represented as a POJO or Item object to upsert. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the upserted document or an error. + */ + public Mono upsertItem(Object item, CosmosItemRequestOptions options){ + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.getDatabase() + .getDocClientWrapper() + .upsertDocument(this.getLink(), + item, + options.toRequestOptions(), + true) + .map(response -> new CosmosItemResponse(response, this)) + .toSingle())); + } + + /** + * Reads all cosmos items in the container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the read cosmos items. + * In case of failure the {@link Flux} will error. + * + * @return an {@link Flux} containing one or several feed response pages of the read cosmos items or an error. + */ + public Flux> listItems() { + return listItems(new FeedOptions()); + } + + /** + * Reads all cosmos items in a container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the read cosmos items. + * In case of failure the {@link Flux} will error. + * + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the read cosmos items or an error. + */ + public Flux> listItems(FeedOptions options) { + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(getDatabase().getDocClientWrapper() + .readDocuments(getLink(), options) + .map(response-> BridgeInternal.createFeedResponse(CosmosItem.getFromV2Results(response.getResults(),this), + response.getResponseHeaders())))); + } + + /** + * Query for documents in a items in a container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the obtained items. + * In case of failure the {@link Flux} will error. + * + * @param query the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. + */ + public Flux> queryItems(String query, FeedOptions options){ + return queryItems(new SqlQuerySpec(query), options); + } + + /** + * Query for documents in a items in a container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the obtained items. + * In case of failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. + */ + public Flux> queryItems(SqlQuerySpec querySpec, FeedOptions options){ + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(getDatabase() + .getDocClientWrapper() + .queryDocuments(getLink(), querySpec, options) + .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( + CosmosItem.getFromV2Results(response.getResults(), this), + response.getResponseHeaders(), response.getQueryMetrics())))); + } + + /** + * Gets a CosmosItem object without making a service call + * @param id id of the item + * @return a cosmos item + */ + public CosmosItem getItem(String id){ + return new CosmosItem(id, this); + } + + /* CosmosStoredProcedure operations */ + + /** + * Creates a cosmos stored procedure. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos stored procedure response with the + * created cosmos stored procedure. + * In case of failure the {@link Mono} will error. + * + * @param settings the cosmos stored procedure settings. + * @param options the stored procedure request options. + * @return an {@link Mono} containing the single cosmos stored procedure resource response or an error. + */ + public Mono createStoredProcedure(CosmosStoredProcedureSettings settings, + CosmosStoredProcedureRequestOptions options){ + StoredProcedure sProc = new StoredProcedure(); + sProc.setId(settings.getId()); + sProc.setBody(settings.getBody()); + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(database.getDocClientWrapper() + .createStoredProcedure(getLink(), sProc, options.toRequestOptions()) + .map(response -> new CosmosStoredProcedureResponse(response, this)) + .toSingle())); + } + + /** + * Reads all cosmos stored procedures in a container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the read cosmos stored procedure settings. + * In case of failure the {@link Flux} will error. + * + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the read cosmos stored procedures + * settings or an error. + */ + public Flux> listStoredProcedures(FeedOptions options){ + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + .readStoredProcedures(getLink(), options) + .map(response -> BridgeInternal.createFeedResponse(CosmosStoredProcedureSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + /** + * Query for stored procedures in a container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained stored procedures. + * In case of failure the {@link Flux} will error. + * + * @param query the the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained stored procedures or + * an error. + */ + public Flux> queryStoredProcedures(String query, + FeedOptions options){ + return queryStoredProcedures(new SqlQuerySpec(query), options); + } + + /** + * Query for stored procedures in a container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained stored procedures. + * In case of failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained stored procedures or + * an error. + */ + public Flux> queryStoredProcedures(SqlQuerySpec querySpec, + FeedOptions options){ + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + .queryStoredProcedures(getLink(), querySpec,options) + .map(response -> BridgeInternal.createFeedResponse( CosmosStoredProcedureSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + + /* UDF Operations */ + + /** + * Creates a cosmos user defined function. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos user defined function response. + * In case of failure the {@link Mono} will error. + * + * @param settings the cosmos user defined function settings + * @param options the cosmos request options. + * @return an {@link Mono} containing the single resource response with the created user defined function or an error. + */ + public Mono createUserDefinedFunction(CosmosUserDefinedFunctionSettings settings, + CosmosRequestOptions options){ + UserDefinedFunction udf = new UserDefinedFunction(); + udf.setId(settings.getId()); + udf.setBody(settings.getBody()); + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(database.getDocClientWrapper() + .createUserDefinedFunction(getLink(), udf, options.toRequestOptions()) + .map(response -> new CosmosUserDefinedFunctionResponse(response, this)).toSingle())); + } + + /** + * Reads all cosmos user defined functions in the container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the read user defined functions. + * In case of failure the {@link Flux} will error. + * + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the read user defined functions or an error. + */ + public Flux> listUserDefinedFunctions(FeedOptions options){ + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + .readUserDefinedFunctions(getLink(), options) + .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + /** + * Query for user defined functions in the container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained user defined functions. + * In case of failure the {@link Flux} will error. + * + * @param query the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained user defined functions or an error. + */ + public Flux> queryUserDefinedFunctions(String query, + FeedOptions options){ + return queryUserDefinedFunctions(new SqlQuerySpec(query), options); + } + + /** + * Query for user defined functions in the container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained user defined functions. + * In case of failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained user defined functions or an error. + */ + public Flux> queryUserDefinedFunctions(SqlQuerySpec querySpec, + FeedOptions options){ + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + .queryUserDefinedFunctions(getLink(),querySpec, options) + .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + /* Trigger Operations */ + /** + * Creates a Cosmos trigger. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos trigger response + * In case of failure the {@link Mono} will error. + * + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the created trigger or an error. + */ + public Mono createTrigger(CosmosTriggerSettings settings, + CosmosRequestOptions options){ + Trigger trigger = new Trigger(settings.toJson()); + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(database.getDocClientWrapper() + .createTrigger(getLink(), trigger,options.toRequestOptions()) + .map(response -> new CosmosTriggerResponse(response, this)) + .toSingle())); + } + + /** + * Reads all triggers in a container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the read cosmos trigger settings. + * In case of failure the {@link Flux} will error. + * + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the read cosmos rigger settings or an error. + */ + public Flux> listTriggers(FeedOptions options){ + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + .readTriggers(getLink(), options) + .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + /** + * Query for triggers in the container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained triggers. + * In case of failure the {@link Flux} will error. + * + * @param query the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained triggers or an error. + */ + public Flux> queryTriggers(String query, FeedOptions options){ + return queryTriggers(new SqlQuerySpec(query), options); + } + + /** + * Query for triggers in the container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained triggers. + * In case of failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained triggers or an error. + */ + public Flux> queryTriggers(SqlQuerySpec querySpec, + FeedOptions options){ + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + .queryTriggers(getLink(), querySpec, options) + .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + /** + * Gets the parent Database + * @return the (@link CosmosDatabase) + */ + public CosmosDatabase getDatabase() { + return database; + } + + @Override + protected String getURIPathSegment() { + return Paths.COLLECTIONS_PATH_SEGMENT; + } + + @Override + protected String getParentLink() { + return database.getLink(); + } + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java new file mode 100644 index 0000000000000..8dc3c121f6fe3 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java @@ -0,0 +1,122 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.microsoft.azure.cosmosdb.RequestOptions; + +/** + * Encapsulates options that can be specified for a request issued to cosmos container. + */ +public class CosmosContainerRequestOptions extends CosmosRequestOptions { + private Integer offerThroughput; + private boolean populateQuotaInfo; + private ConsistencyLevel consistencyLevel; + private String sessionToken; + + /** + * Gets the throughput in the form of Request Units per second when creating a cosmos container. + * + * @return the throughput value. + */ + public Integer getOfferThroughput() { + return offerThroughput; + } + + /** + * Sets the throughput in the form of Request Units per second when creating a cosmos container. + * + * @param offerThroughput the throughput value. + */ + public void setOfferThroughput(Integer offerThroughput) { + this.offerThroughput = offerThroughput; + } + + /** + * Gets the PopulateQuotaInfo setting for cosmos container read requests in the Azure Cosmos DB database service. + * PopulateQuotaInfo is used to enable/disable getting cosmos container quota related stats for document + * collection read requests. + * + * @return true if PopulateQuotaInfo is enabled + */ + public boolean isPopulateQuotaInfo() { + return populateQuotaInfo; + } + + /** + * Sets the PopulateQuotaInfo setting for cosmos container read requests in the Azure Cosmos DB database service. + * PopulateQuotaInfo is used to enable/disable getting cosmos container quota related stats for document + * collection read requests. + * + * @param populateQuotaInfo a boolean value indicating whether PopulateQuotaInfo is enabled or not + */ + public void setPopulateQuotaInfo(boolean populateQuotaInfo) { + this.populateQuotaInfo = populateQuotaInfo; + } + + /** + * Gets the consistency level required for the request. + * + * @return the consistency level. + */ + public ConsistencyLevel getConsistencyLevel() { + return consistencyLevel; + } + + /** + * Sets the consistency level required for the request. + * + * @param consistencyLevel the consistency level. + */ + public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { + this.consistencyLevel = consistencyLevel; + } + + /** + * Gets the token for use with session consistency. + * + * @return the session token. + */ + public String getSessionToken() { + return sessionToken; + } + + /** + * Sets the token for use with session consistency. + * + * @param sessionToken the session token. + */ + public void setSessionToken(String sessionToken) { + this.sessionToken = sessionToken; + } + + @Override + protected RequestOptions toRequestOptions() { + super.toRequestOptions(); + requestOptions.setOfferThroughput(offerThroughput); + requestOptions.setPopulateQuotaInfo(populateQuotaInfo); + requestOptions.setSessionToken(sessionToken); + requestOptions.setConsistencyLevel(consistencyLevel); + return requestOptions; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerResponse.java new file mode 100644 index 0000000000000..c3fdee76c9421 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerResponse.java @@ -0,0 +1,57 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.ResourceResponse; + +public class CosmosContainerResponse extends CosmosResponse { + + private CosmosContainer container; + + CosmosContainerResponse(ResourceResponse response, CosmosDatabase database) { + super(response); + if(response.getResource() == null){ + super.setResourceSettings(null); + }else{ + super.setResourceSettings(new CosmosContainerSettings(response)); + container = new CosmosContainer(getResourceSettings().getId(), database); + } + } + + /** + * Gets the container settings + * @return the cosmos container settings + */ + public CosmosContainerSettings getCosmosContainerSettings() { + return getResourceSettings(); + } + + /** + * Gets the Container object + * @return the Cosmos container object + */ + public CosmosContainer getContainer() { + return container; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java new file mode 100644 index 0000000000000..a5635b0ec36de --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java @@ -0,0 +1,187 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.IndexingPolicy; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.UniqueKeyPolicy; +import com.microsoft.azure.cosmosdb.internal.Constants; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Represents a item container in the Azure Cosmos DB database service. A cosmos container is a named logical container + * for cosmos items. + *

+ * A database may contain zero or more named containers and each container consists of zero or more JSON items. + * Being schema-free, the items in a container do not need to share the same structure or fields. Since containers + * are application resources, they can be authorized using either the master key or resource keys. + */ +public class CosmosContainerSettings extends Resource { + + private IndexingPolicy indexingPolicy; + private UniqueKeyPolicy uniqueKeyPolicy; + private PartitionKeyDefinition partitionKeyDefinition; + + /** + * Constructor + * @param id id of the Container + * @param partitionKeyPath partition key path + */ + public CosmosContainerSettings(String id, String partitionKeyPath) { + super.setId(id); + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList<>(); + paths.add(partitionKeyPath); + partitionKeyDef.setPaths(paths); + setPartitionKey(partitionKeyDef); + } + + /** + * Constructor + * @param id id of the container + * @param partitionKeyDefinition the (@link PartitionKeyDefinition) + */ + public CosmosContainerSettings(String id, PartitionKeyDefinition partitionKeyDefinition) { + super.setId(id); + setPartitionKey(partitionKeyDefinition); + } + + CosmosContainerSettings(ResourceResponse response) { + super(response.getResource().toJson()); + } + + // Converting document collection to CosmosContainerSettings + CosmosContainerSettings(DocumentCollection collection){ + super(collection.toJson()); + } + + static List getFromV2Results(List results){ + return results.stream().map(CosmosContainerSettings::new).collect(Collectors.toList()); + } + + /** + * Gets the container's indexing policy. + * + * @return the indexing policy. + */ + public IndexingPolicy getIndexingPolicy() { + if (this.indexingPolicy == null) { + if (super.has(Constants.Properties.INDEXING_POLICY)) { + this.indexingPolicy = super.getObject(Constants.Properties.INDEXING_POLICY, IndexingPolicy.class); + } else { + this.indexingPolicy = new IndexingPolicy(); + } + } + + return this.indexingPolicy; + } + + /** + * Sets the container's indexing policy + * @param indexingPolicy + */ + public void setIndexingPolicy(IndexingPolicy indexingPolicy) { + if (indexingPolicy == null) { + throw new IllegalArgumentException("IndexingPolicy cannot be null."); + } + this.indexingPolicy = indexingPolicy; + super.set(Constants.Properties.INDEXING_POLICY, indexingPolicy); + } + + /** + * Gets the containers unique key policy + * + * @return the unique key policy + */ + public UniqueKeyPolicy getUniqueKeyPolicy() { + + // Thread safe lazy initialization for case when collection is cached (and is basically readonly). + if (this.uniqueKeyPolicy == null) { + this.uniqueKeyPolicy = super.getObject(Constants.Properties.UNIQUE_KEY_POLICY, UniqueKeyPolicy.class); + + if (this.uniqueKeyPolicy == null) { + this.uniqueKeyPolicy = new UniqueKeyPolicy(); + } + } + + return this.uniqueKeyPolicy; + } + + /** + * Sets the Containers unique key policy + * + * @param uniqueKeyPolicy the unique key policy + */ + public void setUniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) { + if (uniqueKeyPolicy == null) { + throw new IllegalArgumentException("uniqueKeyPolicy cannot be null."); + } + + this.uniqueKeyPolicy = uniqueKeyPolicy; + super.set(Constants.Properties.UNIQUE_KEY_POLICY, uniqueKeyPolicy); + } + + /** + * Gets the containers's partition key definition. + * + * @return the partition key definition. + */ + public PartitionKeyDefinition getPartitionKey() { + if (this.partitionKeyDefinition == null) { + + if (super.has(Constants.Properties.PARTITION_KEY)) { + this.partitionKeyDefinition = super.getObject(Constants.Properties.PARTITION_KEY, PartitionKeyDefinition.class); + } else { + this.partitionKeyDefinition = new PartitionKeyDefinition(); + } + } + + return this.partitionKeyDefinition; + } + + /** + * Sets the containers's partition key definition. + * + * @param partitionKeyDefinition the partition key definition. + */ + public void setPartitionKey(PartitionKeyDefinition partitionKeyDefinition) { + if (partitionKeyDefinition == null) { + throw new IllegalArgumentException("partitionKey cannot be null."); + } + + this.partitionKeyDefinition = partitionKeyDefinition; + } + + DocumentCollection getV2Collection(){ + DocumentCollection collection = new DocumentCollection(this.toJson()); + collection.setPartitionKey(this.getPartitionKey()); + collection.setIndexingPolicy(this.getIndexingPolicy()); + return collection; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java new file mode 100644 index 0000000000000..6327e174dd442 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java @@ -0,0 +1,301 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.BridgeInternal; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.SqlQuerySpec; +import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.microsoft.azure.cosmosdb.internal.Paths; +import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; + +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import org.apache.commons.lang3.StringUtils; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Cosmos Database + */ +public class CosmosDatabase extends CosmosResource { + private CosmosClient client; + + CosmosDatabase(String id, CosmosClient client) { + super(id); + this.client = client; + } + + /** + * Reads a database. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos database respone with the read database. + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the single cosmos database respone with the read database or an error. + */ + public Mono read(){ + return read(new CosmosDatabaseRequestOptions()); + } + + /** + * Reads a database. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos cosmos database respone with the read database. + * In case of failure the {@link Mono} will error. + * + * @param options the request options. + * @return an {@link Mono} containing the single cosmos database response with the read database or an error. + */ + public Mono read(CosmosDatabaseRequestOptions options) { + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(getDocClientWrapper().readDatabase(getLink(), + options.toRequestOptions()) + .map(response -> new CosmosDatabaseResponse(response, getClient())).toSingle())); + } + + /** + * Deletes a database. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos database response with the deleted database. + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the single cosmos database response + */ + public Mono delete() { + return delete(new CosmosRequestOptions()); + } + + /** + * Deletes a database. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos database response with the deleted database. + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the single cosmos database response + */ + public Mono delete(CosmosRequestOptions options) { + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(getDocClientWrapper() + .deleteDatabase(getLink(), options.toRequestOptions()) + .map(response -> new CosmosDatabaseResponse(response, getClient())) + .toSingle())); + } + + /* CosmosContainer operations */ + + /** + * Creates a document container. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos container response with the created + * collection. + * In case of failure the {@link Mono} will error. + * + * @param containerSettings the container settings. + * @return an {@link Flux} containing the single cosmos container response with the created container or an error. + */ + public Mono createContainer(CosmosContainerSettings containerSettings) { + validateResource(containerSettings); + return createContainer(containerSettings, new CosmosContainerRequestOptions()); + } + + /** + * Creates a document container. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos container response with the created + * collection. + * In case of failure the {@link Mono} will error. + * + * @param containerSettings the containerSettings. + * @param options the cosmos container request options + * @return an {@link Flux} containing the cosmos container response with the created container or an error. + */ + public Mono createContainer(CosmosContainerSettings containerSettings, + CosmosContainerRequestOptions options) { + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(getDocClientWrapper().createCollection(this.getLink(), + containerSettings.getV2Collection(), options.toRequestOptions()).map(response -> + new CosmosContainerResponse(response, this)).toSingle())); + } + + /** + * Creates a document container. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos container response with the created + * collection. + * In case of failure the {@link Mono} will error. + * + * @param id the cosmos container id + * @param partitionKeyPath the partition key path + * @return an {@link Flux} containing the cosmos container response with the created container or an error. + */ + public Mono createContainer(String id, String partitionKeyPath) { + return createContainer(new CosmosContainerSettings(id, partitionKeyPath)); + } + + /** + * Creates a document container if it does not exist on the service. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos container response with the created + * or existing collection. + * In case of failure the {@link Mono} will error. + * + * @return a {@link Mono} containing the cosmos container response with the created or existing container or + * an error. + */ + public Mono createContainerIfNotExists(CosmosContainerSettings containerSettings) { + CosmosContainer container = getContainer(containerSettings.getId()); + return createContainerIfNotExistsInternal(containerSettings, container); + } + + /** + * Creates a document container if it does not exist on the service. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos container response with the created + * collection. + * In case of failure the {@link Mono} will error. + * + * @param id the cosmos container id + * @param partitionKeyPath the partition key path + * @return an {@link Flux} containing the cosmos container response with the created container or an error. + */ + public Mono createContainerIfNotExists(String id, String partitionKeyPath) { + CosmosContainer container = getContainer(id); + return createContainerIfNotExistsInternal(new CosmosContainerSettings(id, partitionKeyPath), container); + } + + + private Mono createContainerIfNotExistsInternal(CosmosContainerSettings containerSettings, CosmosContainer container) { + return container.read().onErrorResume(exception -> { + if (exception instanceof DocumentClientException) { + DocumentClientException documentClientException = (DocumentClientException) exception; + if (documentClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { + return createContainer(containerSettings); + } + } + return Mono.error(exception); + }); + } + + + /** + * Reads all cosmos containers. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the read containers. + * In case of failure the {@link Flux} will error. + * + * @param options {@link FeedOptions} + * @return a {@link Flux} containing one or several feed response pages of read containers or an error. + */ + public Flux> listContainers(FeedOptions options) { + //TODO: + return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().readCollections(getLink(), options) + .map(response-> BridgeInternal.createFeedResponse(CosmosContainerSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + /** + * Reads all cosmos containers. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the read containers. + * In case of failure the {@link Flux} will error. + * + * @return a {@link Flux} containing one or several feed response pages of read containers or an error. + */ + public Flux> listContainers() { + return listContainers(new FeedOptions()); + } + + /** + * Query for cosmos containers in a cosmos database. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the obtained containers. + * In case of failure the {@link Flux} will error. + * + * @param query the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained containers or an error. + */ + public Flux> queryContainers(String query, FeedOptions options){ + return queryContainers(new SqlQuerySpec(query), options); + } + + /** + * Query for cosmos containers in a cosmos database. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the obtained containers. + * In case of failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained containers or an error. + */ + public Flux> queryContainers(SqlQuerySpec querySpec, FeedOptions options){ + return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().queryCollections(getLink(), querySpec, + options) + .map(response-> BridgeInternal.createFeedResponse( + CosmosContainerSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + /** + * Gets a CosmosContainer object without making a service call + * @param id id of the container + * @return Cosmos Container + */ + public CosmosContainer getContainer(String id) { + return new CosmosContainer(id, this); + } + + CosmosClient getClient() { + return client; + } + + AsyncDocumentClient getDocClientWrapper(){ + return client.getDocClientWrapper(); + } + + @Override + protected String getURIPathSegment() { + return Paths.DATABASES_PATH_SEGMENT; + } + + @Override + protected String getParentLink() { + return StringUtils.EMPTY; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java new file mode 100644 index 0000000000000..7b5cadf9d7696 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java @@ -0,0 +1,57 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.RequestOptions; + +/** + * Encapsulates options that can be specified for a request issued to cosmos database. + */ +public class CosmosDatabaseRequestOptions extends CosmosRequestOptions{ + private Integer offerThroughput; + + /** + * Gets the throughput in the form of Request Units per second when creating a cosmos database. + * + * @return the throughput value. + */ + public Integer getOfferThroughput() { + return offerThroughput; + } + + /** + * Sets the throughput in the form of Request Units per second when creating a cosmos database. + * + * @param offerThroughput the throughput value. + */ + public void setOfferThroughput(Integer offerThroughput) { + this.offerThroughput = offerThroughput; + } + + @Override + protected RequestOptions toRequestOptions() { + super.toRequestOptions(); + requestOptions.setOfferThroughput(offerThroughput); + return requestOptions; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java new file mode 100644 index 0000000000000..741d4c5ba0fdd --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java @@ -0,0 +1,75 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.ResourceResponse; + +public class CosmosDatabaseResponse extends CosmosResponse{ + private CosmosDatabase database; + + CosmosDatabaseResponse(ResourceResponse response, CosmosClient client) { + super(response); + if(response.getResource() == null){ + super.setResourceSettings(null); + }else{ + super.setResourceSettings(new CosmosDatabaseSettings(response)); + database = new CosmosDatabase(getResourceSettings().getId(), client); + } + } + + /** + * Gets the CosmosDatabase object + * @return + */ + public CosmosDatabase getDatabase() { + return database; + } + + /** + * Gets the cosmos database settings + * @return the cosmos database settings + */ + public CosmosDatabaseSettings getCosmosDatabaseSettings() { + return getResourceSettings(); + } + + /** + * Gets the Max Quota. + * + * @return the database quota. + */ + public long getDatabaseQuota(){ + return resourceResponseWrapper.getDatabaseQuota(); + } + + /** + * Gets the current Usage. + * + * @return the current database usage. + */ + public long getDatabaseUsage(){ + return resourceResponseWrapper.getDatabaseUsage(); + } + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java new file mode 100644 index 0000000000000..2558c009ab5c6 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java @@ -0,0 +1,64 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.ResourceResponse; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * Represents a CosmosDatabase in the Azure Cosmos database service. A cosmos database manages users, permissions and a set of containers + *

+ * Each Azure Cosmos DB Service is able to support multiple independent named databases, with the database being the + * logical container for data. Each Database consists of one or more cosmos containers, each of which in turn contain one or + * more cosmos items. Since databases are an an administrative resource and the Service Key will be required in + * order to access and successfully complete any action using the User APIs. + */ +public class CosmosDatabaseSettings extends Resource { + + ResourceResponse databaseResourceResponse; + + /** + * Constructor + * @param id id of the database + */ + public CosmosDatabaseSettings(String id) { + super.setId(id); + } + + CosmosDatabaseSettings(ResourceResponse response) { + super(response.getResource().toJson()); + } + + // Converting document collection to CosmosContainerSettings + CosmosDatabaseSettings(Database database){ + super(database.toJson()); + } + + static List getFromV2Results(List results){ + return results.stream().map(CosmosDatabaseSettings::new).collect(Collectors.toList()); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java new file mode 100644 index 0000000000000..1d286bc10dbc0 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java @@ -0,0 +1,52 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.Resource; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.stream.Collectors; + +public class CosmosFeedResponse { + private List results; + + //Temporary code. Used for testing conversion(one old resource type to new in feed) + CosmosFeedResponse(FeedResponse feedResponse, Class klass) { + results = feedResponse.getResults().stream().map(resource -> { + T item = null; + try { + item = klass.getConstructor(Resource.class).newInstance(resource); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new IllegalStateException(e); + } + return item; + }).collect(Collectors.toList()); + } + + + List getResults() { + return results; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java new file mode 100644 index 0000000000000..021fc350ad29c --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java @@ -0,0 +1,209 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.internal.Paths; +import com.microsoft.azure.cosmosdb.internal.Utils; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + +public class CosmosItem extends Resource { + + private CosmosContainer container; + final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); + + CosmosItem(String json, CosmosContainer container) { + super(json); + this.container = container; + } + + /** + * Initialize a item object. + */ + public CosmosItem() { + super(); + } + + /** + * Initialize a CosmosItem object from json string. + * + * @param jsonString the json string that represents the document object. + */ + public CosmosItem(String jsonString) { + super(jsonString); + } + + /** + * Reads an item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos item response with the read item + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the cosmos item response with the read item or an error + */ + public Mono read(Object partitionKey) { + return read(new CosmosItemRequestOptions(partitionKey)); + } + + /** + * Reads an item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos item response with the read item + * In case of failure the {@link Mono} will error. + * + * @param requestOptions the request comosItemRequestOptions + * @return an {@link Mono} containing the cosmos item response with the read item or an error + */ + public Mono read(CosmosItemRequestOptions requestOptions) { + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase().getDocClientWrapper() + .readDocument(getLink(), requestOptions.toRequestOptions()) + .map(response -> new CosmosItemResponse(response, container)).toSingle())); + } + + /** + * Replaces an item with the passed in item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * + * @param item the item to replace (containing the document id). + * @param partitionKey the partition key + * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. + */ + public Mono replace(Object item, Object partitionKey){ + return replace(item, new CosmosItemRequestOptions(partitionKey)); + } + + /** + * Replaces an item with the passed in item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * + * @param item the item to replace (containing the document id). + * @param requestOptions the request comosItemRequestOptions + * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. + */ + public Mono replace(Object item, CosmosItemRequestOptions requestOptions){ + Document doc = CosmosItem.fromObject(item); + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .replaceDocument(doc, requestOptions.toRequestOptions()) + .map(response -> new CosmosItemResponse(response, container)).toSingle())); + } + + /** + * Deletes the item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * @param partitionKey + * @return an {@link Mono} containing the cosmos item resource response. + */ + public Mono delete(Object partitionKey) { + return delete(new CosmosItemRequestOptions(partitionKey)); + } + + /** + * Deletes the item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * + * @param options the request options + * @return an {@link Mono} containing the cosmos item resource response. + */ + public Mono delete(CosmosItemRequestOptions options){ + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .deleteDocument(getLink(),options.toRequestOptions()) + .map(response -> new CosmosItemResponse(response, container)) + .toSingle())); + } + + /** + * Initialize an CosmosItem object from json string. + * + * @param jsonString the json string that represents the item object. + * @param objectMapper the custom object mapper + */ + public CosmosItem(String jsonString, ObjectMapper objectMapper) { + super(jsonString, objectMapper); + } + + void setContainer(CosmosContainer container) { + this.container = container; + } + + /** + * fromObject retuns Document for compatibility with V2 sdk + * @param cosmosItem + * @return + */ + static Document fromObject(Object cosmosItem) { + Document typedItem; + if (cosmosItem instanceof CosmosItem) { + typedItem = new Document(((CosmosItem)cosmosItem).toJson()); + } else { + try { + return new Document(CosmosItem.mapper.writeValueAsString(cosmosItem)); + } catch (IOException e) { + throw new IllegalArgumentException("Can't serialize the object into the json string", e); + } + } + return typedItem; + } + + static List getFromV2Results(List results, CosmosContainer container) { + return results.stream().map(document -> new CosmosItem(document.toJson(), container)).collect(Collectors.toList()); + } + + public T getObject(Class klass) throws IOException { + return (T) mapper.readValue(this.toJson(), klass); + } + + private String getLink(){ + StringBuilder builder = new StringBuilder(); + builder.append(container.getLink()); + builder.append("/"); + builder.append(Paths.DOCUMENTS_PATH_SEGMENT); + builder.append("/"); + builder.append(getId()); + return builder.toString(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java new file mode 100644 index 0000000000000..06d98ec217964 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java @@ -0,0 +1,174 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.microsoft.azure.cosmosdb.IndexingDirective; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.RequestOptions; + +import java.util.List; + +/** + * Encapsulates options that can be specified for a request issued to cosmos Item. + */ +public class CosmosItemRequestOptions extends CosmosRequestOptions { + private ConsistencyLevel consistencyLevel; + private IndexingDirective indexingDirective; + private List preTriggerInclude; + private List postTriggerInclude; + private String sessionToken; + private PartitionKey partitionKey; + + /** + * Constructor + */ + public CosmosItemRequestOptions(){ + super(); + } + + /** + * Constructor + * @param partitionKey the partition key + */ + public CosmosItemRequestOptions(Object partitionKey){ + super(); + if (partitionKey instanceof PartitionKey) { + setPartitionKey((PartitionKey) partitionKey); + } else { + setPartitionKey(new PartitionKey(partitionKey)); + } + } + + /** + * Gets the consistency level required for the request. + * + * @return the consistency level. + */ + public ConsistencyLevel getConsistencyLevel() { + return consistencyLevel; + } + + /** + * Sets the consistency level required for the request. + * + * @param consistencyLevel the consistency level. + */ + public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { + this.consistencyLevel = consistencyLevel; + } + + /** + * Gets the indexing directive (index, do not index etc). + * + * @return the indexing directive. + */ + public IndexingDirective getIndexingDirective() { + return indexingDirective; + } + + /** + * Sets the indexing directive (index, do not index etc). + * + * @param indexingDirective the indexing directive. + */ + public void setIndexingDirective(IndexingDirective indexingDirective) { + this.indexingDirective = indexingDirective; + } + + /** + * Gets the triggers to be invoked before the operation. + * + * @return the triggers to be invoked before the operation. + */ + public List getPreTriggerInclude() { + return preTriggerInclude; + } + + /** + * Sets the triggers to be invoked before the operation. + * + * @param preTriggerInclude the triggers to be invoked before the operation. + */ + public void setPreTriggerInclude(List preTriggerInclude) { + this.preTriggerInclude = preTriggerInclude; + } + + /** + * Gets the triggers to be invoked after the operation. + * + * @return the triggers to be invoked after the operation. + */ + public List getPostTriggerInclude() { + return postTriggerInclude; + } + + /** + * Sets the triggers to be invoked after the operation. + * + * @param postTriggerInclude the triggers to be invoked after the operation. + */ + public void setPostTriggerInclude(List postTriggerInclude) { + this.postTriggerInclude = postTriggerInclude; + } + + /** + * Gets the token for use with session consistency. + * + * @return the session token. + */ + public String getSessionToken() { + return sessionToken; + } + + /** + * Sets the token for use with session consistency. + * + * @param sessionToken the session token. + */ + public void setSessionToken(String sessionToken) { + this.sessionToken = sessionToken; + } + + /** + * Sets the partition key + * @param partitionKey + */ + public void setPartitionKey(PartitionKey partitionKey) { + this.partitionKey = partitionKey; + } + + @Override + protected RequestOptions toRequestOptions() { + //TODO: Should we set any default values instead of nulls? + super.toRequestOptions(); + requestOptions.setAccessCondition(getAccessCondition()); + requestOptions.setConsistencyLevel(getConsistencyLevel()); + requestOptions.setIndexingDirective(indexingDirective); + requestOptions.setPreTriggerInclude(preTriggerInclude); + requestOptions.setPostTriggerInclude(postTriggerInclude); + requestOptions.setSessionToken(sessionToken); + requestOptions.setPartitionKey(partitionKey); + return requestOptions; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java new file mode 100644 index 0000000000000..0ee5ea9322fdc --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java @@ -0,0 +1,48 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmosdb.ResourceResponse; + +public class CosmosItemResponse extends CosmosResponse{ + private CosmosItem item; + + CosmosItemResponse(ResourceResponse response, CosmosContainer container) { + super(response); + if(response.getResource() == null){ + super.setResourceSettings(null); + }else{ + super.setResourceSettings(new CosmosItem(response.getResource().toJson())); + item = new CosmosItem(response.getResource().toJson(), container); + } + } + + /** + * Gets the item + * @return the item + */ + public CosmosItem getItem() { + return item; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java new file mode 100644 index 0000000000000..83910dc90d68b --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java @@ -0,0 +1,57 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.AccessCondition; +import com.microsoft.azure.cosmosdb.RequestOptions; + +/** + * Encapsulates options that can be specified for a request + */ +public class CosmosRequestOptions { + protected RequestOptions requestOptions = new RequestOptions(); + private AccessCondition accessCondition; + + /** + * Gets the conditions associated with the request. + * + * @return the access condition. + */ + public AccessCondition getAccessCondition() { + return accessCondition; + } + + /** + * Sets the conditions associated with the request. + * + * @param accessCondition the access condition. + */ + public void setAccessCondition(AccessCondition accessCondition) { + this.accessCondition = accessCondition; + } + + protected RequestOptions toRequestOptions(){ + requestOptions.setAccessCondition(accessCondition); + return requestOptions; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java new file mode 100644 index 0000000000000..46e4c120e20bd --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java @@ -0,0 +1,70 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.Resource; +import org.apache.commons.lang3.StringUtils; + +public abstract class CosmosResource { + + private String id; + + public CosmosResource(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + protected void setId(String id) { + this.id = id; + } + + protected abstract String getURIPathSegment(); + protected abstract String getParentLink(); + + String getLink() { + StringBuilder builder = new StringBuilder(); + builder.append(getParentLink()); + builder.append("/"); + builder.append(getURIPathSegment()); + builder.append("/"); + builder.append(getId()); + return builder.toString(); + } + + protected static void validateResource(Resource resource) { + if (!StringUtils.isEmpty(resource.getId())) { + if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || + resource.getId().indexOf('?') != -1 || resource.getId().indexOf('#') != -1) { + throw new IllegalArgumentException("Id contains illegal chars."); + } + + if (resource.getId().endsWith(" ")) { + throw new IllegalArgumentException("Id ends with a space."); + } + } + } + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java new file mode 100644 index 0000000000000..4154283e16584 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java @@ -0,0 +1,138 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.StoredProcedureResponse; + +import java.util.Map; + +public class CosmosResponse { + private T resourceSettings; + protected ResourceResponse resourceResponseWrapper; + + CosmosResponse(ResourceResponse resourceResponse){ + this.resourceResponseWrapper = resourceResponse; + } + + CosmosResponse(T resourceSettings){ + this.resourceSettings = resourceSettings; + } + + // Only used in CosmosStoredProcedureResponse compatibility with StoredProcedureResponse + CosmosResponse(StoredProcedureResponse response) { + } + + protected T getResourceSettings() { + return resourceSettings; + } + + protected void setResourceSettings(T resourceSettings){ + this.resourceSettings = resourceSettings; + } + + /** + * Gets the maximum size limit for this entity (in megabytes (MB) for server resources and in count for master + * resources). + * + * @return the max resource quota. + */ + public String getMaxResourceQuota() { + return resourceResponseWrapper.getMaxResourceQuota(); + } + + /** + * Gets the current size of this entity (in megabytes (MB) for server resources and in count for master resources) + * + * @return the current resource quota usage. + */ + public String getCurrentResourceQuotaUsage() { + return resourceResponseWrapper.getCurrentResourceQuotaUsage(); + } + + /** + * Gets the Activity ID for the request. + * + * @return the activity id. + */ + public String getActivityId() { + return resourceResponseWrapper.getActivityId(); + } + + /** + * Gets the number of index paths (terms) generated by the operation. + * + * @return the request charge. + */ + public double getRequestCharge() { + return resourceResponseWrapper.getRequestCharge(); + } + + /** + * Gets the progress of an index transformation, if one is underway. + * + * @return the progress of an index transformation. + */ + public long getIndexTransformationProgress() { + return resourceResponseWrapper.getIndexTransformationProgress(); + } + + /** + * Gets the progress of lazy indexing. + * + * @return the progress of lazy indexing. + */ + public long getLazyIndexingProgress() { + return resourceResponseWrapper.getLazyIndexingProgress(); + } + + /** + * Gets the HTTP status code associated with the response. + * + * @return the status code. + */ + public int getStatusCode() { + return resourceResponseWrapper.getStatusCode(); + } + + /** + * Gets the token used for managing client's consistency requirements. + * + * @return the session token. + */ + public String getSessionToken(){ + return resourceResponseWrapper.getSessionToken(); + } + + /** + * Gets the headers associated with the response. + * + * @return the response headers. + */ + public Map getResponseHeaders() { + return resourceResponseWrapper.getResponseHeaders(); + } + + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedure.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedure.java new file mode 100644 index 0000000000000..cb9ffcefb4502 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedure.java @@ -0,0 +1,127 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.StoredProcedure; +import com.microsoft.azure.cosmosdb.internal.Paths; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Mono; + +public class CosmosStoredProcedure extends CosmosResource { + + private CosmosContainer cosmosContainer; + + CosmosStoredProcedure(String id, CosmosContainer cosmosContainer) { + super(id); + this.cosmosContainer = cosmosContainer; + } + + @Override + protected String getURIPathSegment() { + return Paths.STORED_PROCEDURES_PATH_SEGMENT; + } + + @Override + protected String getParentLink() { + return cosmosContainer.getLink(); + } + + /** + * Read a stored procedure by the stored procedure link. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the read stored + * procedure. + * In case of failure the {@link Mono} will error. + * + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the read stored procedure or an error. + */ + public Mono read(RequestOptions options){ + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(cosmosContainer.getDatabase().getDocClientWrapper().readStoredProcedure(getLink(), options) + .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)).toSingle())); + } + + /** + * Deletes a stored procedure by the stored procedure link. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response for the deleted stored procedure. + * In case of failure the {@link Mono} will error. + * + * @param options the request options. + * @return an {@link Mono} containing the single resource response for the deleted stored procedure or an error. + */ + public Mono delete(CosmosRequestOptions options){ + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(cosmosContainer.getDatabase() + .getDocClientWrapper() + .deleteStoredProcedure(getLink(), options.toRequestOptions()) + .map(response -> new CosmosResponse(response.getResource())) + .toSingle())); + } + + /** + * Executes a stored procedure by the stored procedure link. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the stored procedure response. + * In case of failure the {@link Mono} will error. + * + * @param procedureParams the array of procedure parameter values. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the stored procedure response or an error. + */ + public Mono execute(Object[] procedureParams, RequestOptions options){ + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(cosmosContainer.getDatabase() + .getDocClientWrapper() + .executeStoredProcedure(getLink(), options, procedureParams) + .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)) + .toSingle())); + } + + /** + * Replaces a stored procedure. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the replaced stored procedure. + * In case of failure the {@link Mono} will error. + * + * @param storedProcedureSettings the stored procedure settings. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the replaced stored procedure or an error. + */ + public Mono replace(CosmosStoredProcedureSettings storedProcedureSettings, + RequestOptions options){ + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(cosmosContainer.getDatabase() + .getDocClientWrapper() + .replaceStoredProcedure(new StoredProcedure(storedProcedureSettings.toJson()), options) + .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)) + .toSingle())); + } + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java new file mode 100644 index 0000000000000..8294c4b4e6550 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java @@ -0,0 +1,99 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.RequestOptions; + +/** + * Encapsulates options that can be specified for a request issued to cosmos stored procedure. + */ +public class CosmosStoredProcedureRequestOptions extends CosmosRequestOptions { + private ConsistencyLevel consistencyLevel; + private PartitionKey partitionKey; + private String sessionToken; + + /** + * Gets the consistency level required for the request. + * + * @return the consistency level. + */ + public ConsistencyLevel getConsistencyLevel() { + return consistencyLevel; + } + + /** + * Sets the consistency level required for the request. + * + * @param consistencyLevel the consistency level. + */ + public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { + this.consistencyLevel = consistencyLevel; + } + + /** + * Gets the partition key used to identify the current request's target partition. + * + * @return the partition key value. + */ + public PartitionKey getPartitionKey() { + return partitionKey; + } + + /** + * Sets the partition key used to identify the current request's target partition. + * + * @param partitionKey the partition key value. + */ + public void setPartitionKey(PartitionKey partitionKey) { + this.partitionKey = partitionKey; + } + + /** + * Gets the token for use with session consistency. + * + * @return the session token. + */ + public String getSessionToken() { + return sessionToken; + } + + /** + * Sets the token for use with session consistency. + * + * @param sessionToken the session token. + */ + public void setSessionToken(String sessionToken) { + this.sessionToken = sessionToken; + } + + @Override + protected RequestOptions toRequestOptions() { + super.toRequestOptions(); + requestOptions.setConsistencyLevel(getConsistencyLevel()); + requestOptions.setPartitionKey(partitionKey); + requestOptions.setSessionToken(sessionToken); + return requestOptions; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureResponse.java new file mode 100644 index 0000000000000..757c659992f57 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureResponse.java @@ -0,0 +1,132 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.StoredProcedure; +import com.microsoft.azure.cosmosdb.StoredProcedureResponse; + +public class CosmosStoredProcedureResponse extends CosmosResponse { + + private CosmosStoredProcedure storedProcedure; + private StoredProcedureResponse storedProcedureResponse; + + CosmosStoredProcedureResponse(ResourceResponse response, CosmosContainer cosmosContainer) { + super(response); + if(response.getResource() != null){ + super.setResourceSettings(new CosmosStoredProcedureSettings(response)); + storedProcedure = new CosmosStoredProcedure(getResourceSettings().getId(), cosmosContainer); + } + } + + CosmosStoredProcedureResponse(StoredProcedureResponse response, CosmosContainer cosmosContainer) { + super(response); + this.storedProcedureResponse = response; + } + + /** + * Gets the stored procedure settings + * @return the stored procedure settings or null + */ + public CosmosStoredProcedureSettings getStoredProcedureSettings() { + return super.getResourceSettings(); + } + + /** + * Gets the stored procedure object + * @return the stored procedure object or null + */ + public CosmosStoredProcedure getStoredProcedure() { + return this.storedProcedure; + } + + /** + * Gets the Activity ID for the request. + * + * @return the activity id. + */ + @Override + public String getActivityId() { + if(storedProcedureResponse != null){ + return this.storedProcedureResponse.getActivityId(); + } + return super.getActivityId(); + } + + /** + * Gets the token used for managing client's consistency requirements. + * + * @return the session token. + */ + @Override + public String getSessionToken() { + if(storedProcedureResponse != null){ + return this.storedProcedureResponse.getSessionToken(); + } + return super.getSessionToken(); + } + + /** + * Gets the HTTP status code associated with the response. + * + * @return the status code. + */ + @Override + public int getStatusCode() { + if(storedProcedureResponse != null){ + return this.storedProcedureResponse.getStatusCode(); + } + return super.getStatusCode(); + } + + /** + * Gets the number of index paths (terms) generated by the operation. + * + * @return the request charge. + */ + @Override + public double getRequestCharge() { + if(storedProcedureResponse != null){ + return storedProcedureResponse.getRequestCharge(); + } + return super.getRequestCharge(); + } + + /** + * Gets the response of the stored procedure as a string. + * + * @return the response as a string. + */ + public String getResponseAsString() { + return this.storedProcedureResponse.getResponseAsString(); + } + + /** + * Gets the output from stored procedure console.log() statements. + * + * @return the output string from the stored procedure console.log() statements. + */ + public String getScriptLog() { + return this.storedProcedureResponse.getScriptLog(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java new file mode 100644 index 0000000000000..3cd5ccda352ff --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java @@ -0,0 +1,57 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.StoredProcedure; + +import java.util.List; +import java.util.stream.Collectors; + +public class CosmosStoredProcedureSettings extends StoredProcedure { + + /** + * Constructor + */ + public CosmosStoredProcedureSettings() { + super(); + } + + /** + * Constructor. + * + * @param jsonString the json string that represents the stored procedure. + */ + public CosmosStoredProcedureSettings(String jsonString) { + super(jsonString); + } + + CosmosStoredProcedureSettings(ResourceResponse response) { + super(response.getResource().toJson()); + } + + + static List getFromV2Results(List results) { + return results.stream().map(sproc -> new CosmosStoredProcedureSettings(sproc.toJson())).collect(Collectors.toList()); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTrigger.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTrigger.java new file mode 100644 index 0000000000000..7b21c105e4bb2 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTrigger.java @@ -0,0 +1,110 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.Trigger; +import com.microsoft.azure.cosmosdb.internal.Paths; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Mono; + +public class CosmosTrigger extends CosmosResource{ + + private CosmosContainer container; + + CosmosTrigger(String id, CosmosContainer container) { + super(id); + this.container = container; + } + + @Override + protected String getURIPathSegment() { + return Paths.TRIGGERS_PATH_SEGMENT; + } + + @Override + protected String getParentLink() { + return container.getLink(); + } + + /** + * Reads a cosmos trigger by the trigger link. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response for the read trigger. + * In case of failure the {@link Mono} will error. + * + * @param options the request options. + * @return an {@link Mono} containing the single resource response for the read cosmos trigger or an error. + */ + public Mono read(RequestOptions options){ + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .readTrigger(getLink(), options) + .map(response -> new CosmosTriggerResponse(response, container)) + .toSingle())); + } + + + /** + * Replaces a cosmos trigger. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the replaced trigger. + * In case of failure the {@link Mono} will error. + * + * @param triggerSettings the cosmos trigger settings. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the replaced cosmos trigger or an error. + */ + public Mono replace(CosmosTriggerSettings triggerSettings, RequestOptions options){ + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .replaceTrigger(new Trigger(triggerSettings.toJson()), options) + .map(response -> new CosmosTriggerResponse(response, container)) + .toSingle())); + } + + /** + * Deletes a cosmos trigger. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response for the deleted trigger. + * In case of failure the {@link Mono} will error. + * + * @param options the request options. + * @return an {@link Mono} containing the single resource response for the deleted cosmos trigger or an error. + */ + public Mono delete(CosmosRequestOptions options){ + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .deleteTrigger(getLink(), options.toRequestOptions()) + .map(response -> new CosmosResponse(response.getResource())) + .toSingle())); + } + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java new file mode 100644 index 0000000000000..3a05f74ab16b4 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java @@ -0,0 +1,56 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.Trigger; + +public class CosmosTriggerResponse extends CosmosResponse { + + private CosmosTriggerSettings cosmosTriggerSettings; + private CosmosTrigger cosmosTrigger; + + CosmosTriggerResponse(ResourceResponse response, CosmosContainer container) { + super(response); + if(response.getResource() != null) { + cosmosTriggerSettings = new CosmosTriggerSettings(response); + cosmosTrigger = new CosmosTrigger(cosmosTriggerSettings.getId(), container); + } + } + + /** + * Gets the cosmos trigger settings or null + * @return + */ + public CosmosTriggerSettings getCosmosTriggerSettings() { + return cosmosTriggerSettings; + } + + /** + * Gets the cosmos trigger object or null + * @return + */ + public CosmosTrigger getCosmosTrigger() { + return cosmosTrigger; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java new file mode 100644 index 0000000000000..139668ae1ef50 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java @@ -0,0 +1,56 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.Trigger; + +import java.util.List; +import java.util.stream.Collectors; + +public class CosmosTriggerSettings extends Trigger { + + /** + * Constructor + */ + public CosmosTriggerSettings(){ + super(); + } + + /** + * Constructor. + * + * @param jsonString the json string that represents the trigger settings. + */ + public CosmosTriggerSettings(String jsonString){ + super(jsonString); + } + + CosmosTriggerSettings(ResourceResponse response) { + super(response.getResource().toJson()); + } + + static List getFromV2Results(List results) { + return results.stream().map(trigger -> new CosmosTriggerSettings(trigger.toJson())).collect(Collectors.toList()); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunction.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunction.java new file mode 100644 index 0000000000000..0519674e96686 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunction.java @@ -0,0 +1,109 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.UserDefinedFunction; +import com.microsoft.azure.cosmosdb.internal.Paths; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Mono; + +public class CosmosUserDefinedFunction extends CosmosResource{ + + private CosmosContainer container; + + CosmosUserDefinedFunction(String id, CosmosContainer container) { + super(id); + this.container = container; + } + + /** + * Read a user defined function. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response for the read user defined + * function. + * In case of failure the {@link Mono} will error. + * @param options the request options. + * @return an {@link Mono} containing the single resource response for the read user defined function or an error. + */ + public Mono read(RequestOptions options){ + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase().getDocClientWrapper().readUserDefinedFunction(getLink(), options) + .map(response -> new CosmosUserDefinedFunctionResponse(response, container)).toSingle())); + } + + /** + * Replaces a cosmos user defined function. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the replaced user + * defined function. + * In case of failure the {@link Mono} will error. + * + * @param udfSettings the cosmos user defined function settings. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the replaced cosmos user defined function + * or an error. + */ + public Mono replace(CosmosUserDefinedFunctionSettings udfSettings, + RequestOptions options){ + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .replaceUserDefinedFunction(new UserDefinedFunction(udfSettings.toJson()) + , options) + .map(response -> new CosmosUserDefinedFunctionResponse(response, container)) + .toSingle())); + } + + /** + * Deletes a cosmos user defined function. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response for the deleted user defined function. + * In case of failure the {@link Mono} will error. + * + * @param options the request options. + * @return an {@link Mono} containing the single resource response for the deleted cosmos user defined function or + * an error. + */ + public Mono delete(CosmosRequestOptions options){ + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .deleteUserDefinedFunction(this.getLink(), options.toRequestOptions()) + .map(response -> new CosmosResponse(response.getResource())) + .toSingle())); + } + + @Override + protected String getURIPathSegment() { + return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT; + } + + @Override + protected String getParentLink() { + return container.getLink(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java new file mode 100644 index 0000000000000..2b4f301b9a45d --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java @@ -0,0 +1,56 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.UserDefinedFunction; + +public class CosmosUserDefinedFunctionResponse extends CosmosResponse { + + private CosmosUserDefinedFunctionSettings cosmosUserDefinedFunctionSettings; + private CosmosUserDefinedFunction cosmosUserDefinedFunction; + + CosmosUserDefinedFunctionResponse(ResourceResponse response, CosmosContainer container) { + super(response); + if(response.getResource() != null) { + cosmosUserDefinedFunctionSettings = new CosmosUserDefinedFunctionSettings(response); + cosmosUserDefinedFunction = new CosmosUserDefinedFunction(cosmosUserDefinedFunctionSettings.getId(), container); + } + } + + /** + * Gets the cosmos user defined function settings + * @return the cosmos user defined function settings + */ + public CosmosUserDefinedFunctionSettings getCosmosUserDefinedFunctionSettings() { + return cosmosUserDefinedFunctionSettings; + } + + /** + * Gets the cosmos user defined function object + * @return the cosmos user defined function object + */ + public CosmosUserDefinedFunction getCosmosUserDefinedFunction() { + return cosmosUserDefinedFunction; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java new file mode 100644 index 0000000000000..f85cd6f765e00 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java @@ -0,0 +1,56 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.UserDefinedFunction; + +import java.util.List; +import java.util.stream.Collectors; + +public class CosmosUserDefinedFunctionSettings extends UserDefinedFunction { + + /** + * Constructor + */ + public CosmosUserDefinedFunctionSettings(){ + super(); + } + + CosmosUserDefinedFunctionSettings(ResourceResponse response) { + super(response.getResource().toJson()); + } + + /** + * Constructor. + * + * @param jsonString the json string that represents the cosmos user defined function settings. + */ + public CosmosUserDefinedFunctionSettings(String jsonString) { + super(jsonString); + } + + static List getFromV2Results(List results) { + return results.stream().map(udf -> new CosmosUserDefinedFunctionSettings(udf.toJson())).collect(Collectors.toList()); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java new file mode 100644 index 0000000000000..e12eb7fa1925a --- /dev/null +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java @@ -0,0 +1,163 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.IndexingMode; +import com.microsoft.azure.cosmosdb.IndexingPolicy; +import com.microsoft.azure.cosmosdb.rx.FailureValidator; + +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import reactor.core.publisher.Mono; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CosmosContainerCrudTest extends CosmosTestSuiteBase { + private final static String PRE_EXISTING_DATABASE_ID = getDatabaseId(CosmosContainerCrudTest.class) + "db1"; + private final static String PRE_EXISTING_CONTAINER_ID = getDatabaseId(CosmosContainerCrudTest.class) + "_CONTAINER"; + private final static String DATABASE_ID2 = getDatabaseId(CosmosContainerCrudTest.class) + "db2"; + private final static String CONTAINER_ID2 = getDatabaseId(CosmosContainerCrudTest.class) + "_CONTAINER_2"; + + private CosmosClient client; + private CosmosConfiguration.Builder configBuilder; + + @Factory(dataProvider = "clientBuilders") + public CosmosContainerCrudTest(CosmosConfiguration.Builder configBuilder) { + this.configBuilder = configBuilder; + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testCreateContainer() throws Exception { + CosmosContainerSettings containerSettings = new CosmosContainerSettings(CONTAINER_ID2, "/mypk"); + CosmosDatabase database = client.getDatabase(PRE_EXISTING_DATABASE_ID); + // create the container + Mono createMono = database.createContainer(containerSettings); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(containerSettings.getId()).build(); + validateSuccess(createMono, validator); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testCreateContainer_AlreadyExists() throws Exception { + CosmosContainerSettings containerSettings = new CosmosContainerSettings("new_container", "/mypk"); + CosmosDatabase database = client.getDatabase(PRE_EXISTING_DATABASE_ID); + + database.createContainer(containerSettings).block(); + + // attempt to create the container again + Mono createMono = database.createContainer(containerSettings); + + // validate + FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); + validateFailure(createMono, validator); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testReadContainer() throws Exception { + // read container + CosmosContainerSettings settings = getContainerSettings(); + CosmosContainer container = + client.getDatabase(PRE_EXISTING_DATABASE_ID).createContainer(settings).block().getContainer(); + Mono containerResponseMono = container.read(); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(settings.getId()).build(); + validateSuccess(containerResponseMono, validator); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testReadContainer_DoesntExist() throws Exception { + CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer("I dont exist"); + // read container + Mono containerResponseMono = container.read(); + // validate + FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(containerResponseMono, validator); + } + + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testDeleteContainer() throws Exception { + Mono deleteMono = client.getDatabase(PRE_EXISTING_DATABASE_ID) + .getContainer(PRE_EXISTING_CONTAINER_ID) + .delete(); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteMono, validator); + //TODO validate after deletion the resource is actually deleted (not found) + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testDeleteContainer_DoesntExist() throws Exception { + Mono deleteMono = client.getDatabase(PRE_EXISTING_DATABASE_ID) + .getContainer("doesnt exixt") + .delete(); + + // validate + FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(deleteMono, validator); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testreplaceContainer() throws Exception { + CosmosDatabase database = client.getDatabase(PRE_EXISTING_DATABASE_ID); + + Mono containerMono = database.createContainer(getContainerSettings()); + CosmosContainerResponse containerResponse = containerMono.block(); + CosmosContainer container = containerResponse.getContainer(); + CosmosContainerSettings settings = containerResponse.getCosmosContainerSettings(); + // sanity check + assertThat(settings.getIndexingPolicy().getIndexingMode()).isEqualTo(IndexingMode.Consistent); + + // replace indexing mode + IndexingPolicy indexingMode = new IndexingPolicy(); + indexingMode.setIndexingMode(IndexingMode.Lazy); + settings.setIndexingPolicy(indexingMode); + Mono replaceMono = container.replace(settings, null); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .indexingMode(IndexingMode.Lazy).build(); + validateSuccess(replaceMono, validator); + } + + @BeforeClass(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) + public void beforeClass() { + client = CosmosClient.create(configBuilder.build()); + createDatabase(client, PRE_EXISTING_DATABASE_ID); + createContainerInDB(client, PRE_EXISTING_CONTAINER_ID, PRE_EXISTING_DATABASE_ID); + } + + @AfterClass(groups = { "cosmosv3" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeDeleteDatabase(client, PRE_EXISTING_DATABASE_ID); + safeClose(client); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java new file mode 100644 index 0000000000000..4647aacb05ac7 --- /dev/null +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java @@ -0,0 +1,141 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.rx.FailureValidator; + +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +import reactor.core.publisher.Mono; + +public class CosmosDatabaseCrudTest extends CosmosTestSuiteBase { + private final static String PRE_EXISTING_DATABASE_ID = getDatabaseId(CosmosDatabaseCrudTest.class) + "1"; + private final static String DATABASE_ID2 = getDatabaseId(CosmosDatabaseCrudTest.class) + "2"; + + private CosmosClient client; + private CosmosConfiguration.Builder configBuilder; + + @Factory(dataProvider = "clientBuilders") + public CosmosDatabaseCrudTest(CosmosConfiguration.Builder configBuilder) { + this.configBuilder = configBuilder; + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void createDatabase() throws Exception { + CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings(DATABASE_ID2); + + // create the database + Mono createMono = client.createDatabase(databaseSettings); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(databaseSettings.getId()).build(); + validateSuccess(createMono , validator); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void createDatabase_AlreadyExists() throws Exception { + CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings(DATABASE_ID2); + + client.createDatabase(databaseSettings).block(); + + // attempt to create the database again + Mono createMono = client.createDatabase(databaseSettings); + + // validate + FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); + validateFailure(createMono, validator); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void readDatabase() throws Exception { + // read database + Mono readMono = client.getDatabase(PRE_EXISTING_DATABASE_ID).read(); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(PRE_EXISTING_DATABASE_ID).build(); + validateSuccess(readMono, validator); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void readDatabase_DoesntExist() throws Exception { + // read database + Mono readMono = client.getDatabase("I dont exist").read(); + + // validate + FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(readMono, validator); + } + + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void deleteDatabase() throws Exception { + // delete the database + Mono deleteMono = client.getDatabase(PRE_EXISTING_DATABASE_ID).delete(); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteMono, validator); +// //TODO validate after deletion the resource is actually deleted (not found) + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void deleteDatabase_DoesntExist() throws Exception { + // delete the database + Mono deleteMono = client + .getDatabase("I don't exist").delete(); + + // validate + FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(deleteMono, validator); + + } + + @BeforeClass(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) + public void beforeClass() { + client = CosmosClient.create(configBuilder.build()); + } + + @AfterClass(groups = { "cosmosv3" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeClose(client); + } + + @AfterMethod(groups = { "cosmosv3" }, timeOut = SHUTDOWN_TIMEOUT) + public void afterMethod() { + safeDeleteDatabase(client, PRE_EXISTING_DATABASE_ID); + safeDeleteDatabase(client, DATABASE_ID2); + } + + @BeforeMethod(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) + public void beforeMethod() { + createDatabase(client, PRE_EXISTING_DATABASE_ID); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java new file mode 100644 index 0000000000000..5efb553179b68 --- /dev/null +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java @@ -0,0 +1,147 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.rx.FailureValidator; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import reactor.core.publisher.Mono; + +import java.util.UUID; + +public class CosmosItemCrudTest extends CosmosTestSuiteBase { + private final static String PRE_EXISTING_DATABASE_ID = getDatabaseId(CosmosItemCrudTest.class) + "db1"; + private final static String PRE_EXISTING_CONTAINER_ID = getDatabaseId(CosmosItemCrudTest.class) + "_CONTAINER"; + private final static String DATABASE_ID2 = getDatabaseId(CosmosItemCrudTest.class) + "db2"; + private final static String CONTAINER_ID2 = getDatabaseId(CosmosItemCrudTest.class) + "_CONTAINER_2"; + + private CosmosClient client; + private CosmosConfiguration.Builder configBuilder; + + @Factory(dataProvider = "clientBuilders") + public CosmosItemCrudTest(CosmosConfiguration.Builder configBuilder) { + this.configBuilder = configBuilder; + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testCreateItem() throws Exception { + CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); + CosmosItem itemDefinition = getItemDefinition(); + // create the item + System.out.println("itemDefinition = " + itemDefinition); + Mono createMono = container.createItem(itemDefinition, "mypk"); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(itemDefinition.getId()).build(); + validateSuccess(createMono, validator); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testCreateItem_AlreadyExists() throws Exception { + CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); + CosmosItem itemDefinition = getItemDefinition(); + // create the item + container.createItem(itemDefinition, itemDefinition.get("mypk")).block(); + + // try creating the same item again + Mono createMono = container.createItem(itemDefinition, itemDefinition.get("mypk")); + + // validate + FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); + validateFailure(createMono, validator); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testReadItem() throws Exception { + // read item + CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); + CosmosItem itemDefinition = getItemDefinition(); + // create the item + CosmosItem item = container.createItem(itemDefinition, "mypk").block().getItem(); + Mono readMono = item.read("mypk"); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(itemDefinition.getId()).build(); + validateSuccess(readMono, validator); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testDeleteItem() throws Exception { + CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); + CosmosItem itemDefinition = getItemDefinition(); + // create the item + CosmosItem item = container.createItem(itemDefinition, "mypk").block().getItem(); + Mono deleteMono = item.delete("mypk"); + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteMono, validator); + //TODO validate after deletion the resource is actually deleted (not found) + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT) + public void testreplaceItem() throws Exception { + CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); + CosmosItem itemDefinition = getItemDefinition(); + // create the item + CosmosItem item = container.createItem(itemDefinition, "mypk").block().getItem(); + + String newPropValue = UUID.randomUUID().toString(); + item.set("newProp", newPropValue); + + // replace document + Mono readMono = item.replace(item, "mypk"); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withProperty("newProp", newPropValue).build(); + validateSuccess(readMono, validator); + } + + @BeforeClass(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) + public void beforeClass() { + client = CosmosClient.create(configBuilder.build()); + createDatabase(client, PRE_EXISTING_DATABASE_ID); + createContainerInDB(client, PRE_EXISTING_CONTAINER_ID, PRE_EXISTING_DATABASE_ID); + } + + @AfterClass(groups = { "cosmosv3" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeDeleteDatabase(client, PRE_EXISTING_DATABASE_ID); + safeClose(client); + } + + private CosmosItem getItemDefinition() { + String uuid = UUID.randomUUID().toString(); + return new CosmosItem(String.format("{ " + + "\"id\": \"%s\", " + + "\"mypk\": \"%s\", " + + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + + "}" + , uuid, "mypk")); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java new file mode 100644 index 0000000000000..be93657a49e29 --- /dev/null +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java @@ -0,0 +1,109 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.IndexingMode; +import com.microsoft.azure.cosmosdb.Resource; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public interface CosmosResponseValidator { + void validate(T cosmosResponse); + + class Builder { + private List> validators = new ArrayList<>(); + + public CosmosResponseValidator build() { + return new CosmosResponseValidator() { + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void validate(T resourceResponse) { + for (CosmosResponseValidator validator : validators) { + validator.validate(resourceResponse); + } + } + }; + } + + public Builder withId(final String resourceId) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(T resourceResponse) { + assertThat(getResource(resourceResponse)).isNotNull(); + assertThat(getResource(resourceResponse).getId()).as("check Resource Id").isEqualTo(resourceId); + } + }); + return this; + } + + private Resource getResource(T resourceResponse) { + if(resourceResponse instanceof CosmosDatabaseResponse){ + return ((CosmosDatabaseResponse)resourceResponse).getCosmosDatabaseSettings(); + }else if(resourceResponse instanceof CosmosContainerResponse){ + return ((CosmosContainerResponse)resourceResponse).getCosmosContainerSettings(); + }else if(resourceResponse instanceof CosmosItemResponse){ + return ((CosmosItemResponse)resourceResponse).getItem(); + } + return null; + } + + public Builder nullResource() { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(T resourceResponse) { + assertThat(getResource(resourceResponse)).isNull(); + } + }); + return this; + } + + public Builder indexingMode(IndexingMode mode) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosContainerResponse resourceResponse) { + assertThat(resourceResponse.getCosmosContainerSettings()).isNotNull(); + assertThat(resourceResponse.getCosmosContainerSettings().getIndexingPolicy()).isNotNull(); + assertThat(resourceResponse.getCosmosContainerSettings().getIndexingPolicy().getIndexingMode()).isEqualTo(mode); + } + }); + return this; + } + + public Builder withProperty(String propertyName, String value) { + validators.add(new CosmosResponseValidator() { + @Override + public void validate(T cosmosResponse) { + assertThat(getResource(cosmosResponse)).isNotNull(); + assertThat(getResource(cosmosResponse).get(propertyName)).isEqualTo(value); + } + }); + return this; + } + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java new file mode 100644 index 0000000000000..6dc36f1bdf77a --- /dev/null +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java @@ -0,0 +1,176 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ConnectionMode; +import com.microsoft.azure.cosmosdb.ConnectionPolicy; +import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.RetryOptions; +import com.microsoft.azure.cosmosdb.rx.FailureValidator; +import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientImpl; +import io.reactivex.subscribers.TestSubscriber; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.DataProvider; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CosmosTestSuiteBase { + + protected static final int TIMEOUT = 8000; + protected static final int SETUP_TIMEOUT = 30000; + protected static final int SHUTDOWN_TIMEOUT = 12000; + protected static final int SUITE_SETUP_TIMEOUT = 120000; + private static final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); + + protected int subscriberValidationTimeout = TIMEOUT; + + public static String getDatabaseId(Class klass) { + return String.format("java.rx.%s", klass.getName()); + } + + public void validateSuccess(Mono single, + CosmosResponseValidator validator) throws InterruptedException { + validateSuccess(single.flux(), validator, subscriberValidationTimeout); + } + + public static void validateSuccess(Flux flowable, + CosmosResponseValidator validator, long timeout) throws InterruptedException { + + TestSubscriber testSubscriber = new TestSubscriber<>(); + + flowable.subscribe(testSubscriber); + testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + testSubscriber.assertNoErrors(); + testSubscriber.assertComplete(); + testSubscriber.assertValueCount(1); + validator.validate( testSubscriber.values().get(0)); + } + + public void validateFailure(Mono mono, + FailureValidator validator) throws InterruptedException { + validateFailure(mono.flux(), validator, subscriberValidationTimeout); + } + + public static void validateFailure(Flux flowable, + FailureValidator validator, long timeout) throws InterruptedException { + + TestSubscriber testSubscriber = new TestSubscriber<>(); + + flowable.subscribe(testSubscriber); + testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + assertThat(testSubscriber.errors()).hasSize(1); + validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); + } + + @DataProvider + public static Object[][] clientBuilders() { + return new Object[][] { { createGatewayRxCosmosClient() } }; + } + + static protected CosmosConfiguration.Builder createGatewayRxCosmosClient() { + ConnectionPolicy connectionPolicy = new ConnectionPolicy(); + connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + RetryOptions options = new RetryOptions(); + options.setMaxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); + connectionPolicy.setRetryOptions(options); + return new CosmosConfiguration.Builder().withConnectionPolicy(connectionPolicy) + .withServiceEndpoint(TestConfigurations.HOST) + .withKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withServiceEndpoint(TestConfigurations.HOST) + .withConsistencyLevel(ConsistencyLevel.Session); + } + + static protected CosmosDatabase safeCreateDatabase(CosmosClient client, CosmosDatabaseSettings databaseSettings) { + safeDeleteDatabase(client, databaseSettings.getId()); + return createDatabase(client, databaseSettings); + } + + static protected CosmosDatabase createDatabase(CosmosClient client, String databaseId) { + Mono databaseSingle = client.createDatabase(databaseId); + return databaseSingle.block().getDatabase(); + } + + static protected CosmosContainer createContainerInDB(CosmosClient client, String containerID, String databaseId) { + CosmosDatabase cosmosDatabaseProxy = client.getDatabase(databaseId); + Mono containerSingle = cosmosDatabaseProxy.createContainer(containerID, "/mypk"); + return containerSingle.block().getContainer(); + } + + static private CosmosDatabase createDatabase(CosmosClient client, CosmosDatabaseSettings databaseSettings) { + Mono databaseSingle = client.createDatabase(databaseSettings, + new CosmosDatabaseRequestOptions()); + return databaseSingle.block().getDatabase(); + } + + static protected void safeDeleteDatabase(CosmosClient client, String databaseId) { + CosmosDatabase database = client.getDatabase(databaseId); + if (client != null) { + try { + database.delete().block(); + } catch (Exception e) { + } + } + } + + static protected void safeDeleteContainer(CosmosClient client, String containerId, String databaseId) { + CosmosContainer container = client.getDatabase(databaseId).getContainer(containerId); + if (client != null) { + try { + container.delete().block(); + } catch (Exception e) { + } + } + } + + static protected CosmosContainerSettings getContainerSettings() { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList<>(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + + CosmosContainerSettings settings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + return settings; + } + + static protected void safeClose(CosmosClient client) { + if (client != null) { + try { + client.close(); + } catch (Exception e) { + logger.error("Error: ", e); + } + } + } +} From 3710df5700687003de11931af331b96c471f19a2 Mon Sep 17 00:00:00 2001 From: Christopher Anderson Date: Wed, 8 May 2019 16:18:55 -0700 Subject: [PATCH 02/85] Add christopheranderson and kushagraThapar to CODEOWNERS (v3) (#101) * Add christopheranderson to CODEOWNERS (v3) Bus factor 0 is bad mmkay * Add Kushagra as well --- CODEOWNERS | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CODEOWNERS b/CODEOWNERS index a48af4d00401d..4a35340c990b9 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -7,4 +7,6 @@ # https://help.github.com/articles/about-codeowners/ # Default owner for repo -* @moderakh \ No newline at end of file +* @moderakh +* @christopheranderson +* @kushagraThapar From 4975b6b925c78949cdeb4f6dabaaca48b5c89c57 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Thu, 9 May 2019 13:15:55 -0700 Subject: [PATCH 03/85] fixed syntax --- CODEOWNERS | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/CODEOWNERS b/CODEOWNERS index 4a35340c990b9..26da20e9f2cf2 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -7,6 +7,4 @@ # https://help.github.com/articles/about-codeowners/ # Default owner for repo -* @moderakh -* @christopheranderson -* @kushagraThapar +* @moderakh @christopheranderson @kushagraThapar From b544717d7a2289280fe1cd5733beb1e71fb875eb Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Wed, 29 May 2019 09:33:45 -0700 Subject: [PATCH 04/85] bumped timeouts --- .../com/microsoft/azure/cosmosdb/rx/DCDocumentCrudTest.java | 2 +- .../java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DCDocumentCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DCDocumentCrudTest.java index fc8b79637e954..7a73fa0e04bde 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DCDocumentCrudTest.java @@ -67,7 +67,7 @@ * The tests in other test classes validate the actual behaviour and different scenarios. */ public class DCDocumentCrudTest extends TestSuiteBase { - private final static int QUERY_TIMEOUT = 30000; + private final static int QUERY_TIMEOUT = 40000; private final static String PARTITION_KEY_FIELD_NAME = "mypk"; private static Database createdDatabase; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java index d77fd497ccd48..e6b9bafe3dadf 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java @@ -88,7 +88,7 @@ public class TestSuiteBase { private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; private static final ObjectMapper objectMapper = new ObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); - protected static final int TIMEOUT = 8000; + protected static final int TIMEOUT = 16000; protected static final int FEED_TIMEOUT = 12000; protected static final int SETUP_TIMEOUT = 30000; protected static final int SHUTDOWN_TIMEOUT = 12000; From 4f58bc0acff4b0085c4aed5ee68028d3589dcba7 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Wed, 29 May 2019 10:23:20 -0700 Subject: [PATCH 05/85] bumped timeouts --- .../java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java | 4 ++-- .../microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java index e6b9bafe3dadf..2ab8452c111d4 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java @@ -89,8 +89,8 @@ public class TestSuiteBase { private static final ObjectMapper objectMapper = new ObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); protected static final int TIMEOUT = 16000; - protected static final int FEED_TIMEOUT = 12000; - protected static final int SETUP_TIMEOUT = 30000; + protected static final int FEED_TIMEOUT = 24000; + protected static final int SETUP_TIMEOUT = 60000; protected static final int SHUTDOWN_TIMEOUT = 12000; protected static final int SUITE_SETUP_TIMEOUT = 120000; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java index fa92ee2af6342..0635668a44bfa 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java @@ -90,9 +90,9 @@ public class TestSuiteBase { private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; private static final ObjectMapper objectMapper = new ObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); - protected static final int TIMEOUT = 8000; - protected static final int FEED_TIMEOUT = 12000; - protected static final int SETUP_TIMEOUT = 30000; + protected static final int TIMEOUT = 16000; + protected static final int FEED_TIMEOUT = 24000; + protected static final int SETUP_TIMEOUT = 60000; protected static final int SHUTDOWN_TIMEOUT = 12000; protected static final int SUITE_SETUP_TIMEOUT = 120000; From e613d3c4717383498f858f19385aa79eec4487a7 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Wed, 29 May 2019 12:59:09 -0700 Subject: [PATCH 06/85] bumped timeout --- .../java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java | 2 +- .../com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java index 2ab8452c111d4..e24c766cf8f82 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java @@ -88,7 +88,7 @@ public class TestSuiteBase { private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; private static final ObjectMapper objectMapper = new ObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); - protected static final int TIMEOUT = 16000; + protected static final int TIMEOUT = 30000; protected static final int FEED_TIMEOUT = 24000; protected static final int SETUP_TIMEOUT = 60000; protected static final int SHUTDOWN_TIMEOUT = 12000; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java index 0635668a44bfa..149ea0691a825 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java @@ -90,7 +90,7 @@ public class TestSuiteBase { private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; private static final ObjectMapper objectMapper = new ObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); - protected static final int TIMEOUT = 16000; + protected static final int TIMEOUT = 30000; protected static final int FEED_TIMEOUT = 24000; protected static final int SETUP_TIMEOUT = 60000; protected static final int SHUTDOWN_TIMEOUT = 12000; From e0179c1a6be3230212c04152e58716ae6dd136f8 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Wed, 29 May 2019 16:00:15 -0700 Subject: [PATCH 07/85] bump timeout --- .../com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java index 3aa4b54519cf7..e7004c42ff44c 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java @@ -50,7 +50,7 @@ import rx.Observable; public class CollectionCrudTest extends TestSuiteBase { - private static final int TIMEOUT = 30000; + private static final int TIMEOUT = 50000; private static final int SETUP_TIMEOUT = 20000; private static final int SHUTDOWN_TIMEOUT = 20000; private final String databaseId = DatabaseForTest.generateId(); From 41db075fa622e0d2773f3b7365b9293f96586b12 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Wed, 29 May 2019 17:02:06 -0700 Subject: [PATCH 08/85] added read my write test --- .../ReadMyWritesConsistencyTest.java | 208 ++++++++++++++++++ pom.xml | 15 ++ 2 files changed, 223 insertions(+) create mode 100644 benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java diff --git a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java new file mode 100644 index 0000000000000..c05744b9261f4 --- /dev/null +++ b/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java @@ -0,0 +1,208 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.microsoft.azure.cosmosdb.benchmark; + +import com.beust.jcommander.JCommander; +import com.google.common.base.Strings; +import com.microsoft.azure.cosmosdb.DataType; +import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.IncludedPath; +import com.microsoft.azure.cosmosdb.Index; +import com.microsoft.azure.cosmosdb.IndexingPolicy; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import rx.Observable; +import rx.schedulers.Schedulers; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ReadMyWritesConsistencyTest { + private final static Logger logger = LoggerFactory.getLogger(ReadMyWritesConsistencyTest.class); + private final static int TIMEOUT = 60 * 60 * 1000; + private final AtomicBoolean failed = new AtomicBoolean(false); + private final String desiredConsistency = + System.getProperty("DESIRED_CONSISTENCY", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("DESIRED_CONSISTENCY")), "Strong")); + + private final String numberOfOperationsAsString = + System.getProperty("NUMBER_OF_OPERATIONS", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("NUMBER_OF_OPERATIONS")), Integer.toString(400_000))); + private Database database; + private DocumentCollection collection; + + @Test(dataProvider = "collectionLinkTypeArgProvider", groups = "e2e", timeOut = TIMEOUT) + public void readMyWrites(boolean useNameLink) throws Exception { + int numberOfOperations = Integer.parseInt(numberOfOperationsAsString); + int concurrency = 5; + String cmdFormat = "-serviceEndpoint %s -masterKey %s" + + " -databaseId %s -collectionId %s" + + " -consistencyLevel %s -concurrency %d -numberOfOperations %s" + + " -operation ReadMyWrites -connectionMode Direct -numberOfPreCreatedDocuments 100 " + + " -printingInterval 60"; + + String cmd = String.format(cmdFormat, + TestConfigurations.HOST, + TestConfigurations.MASTER_KEY, + database.getId(), + collection.getId(), + desiredConsistency, + concurrency, + numberOfOperations) + + (useNameLink ? " -useNameLink" : ""); + + Configuration cfg = new Configuration(); + new JCommander(cfg, StringUtils.split(cmd)); + + AtomicInteger success = new AtomicInteger(); + AtomicInteger error = new AtomicInteger(); + + ReadMyWriteWorkflow wf = new ReadMyWriteWorkflow(cfg) { + @Override + protected void onError(Throwable throwable) { + error.incrementAndGet(); + } + + @Override + protected void onSuccess() { + success.incrementAndGet(); + } + }; + + // schedules a collection scale up in 2 minutes + scheduleScaleUp(120, 100_000); + + wf.run(); + wf.shutdown(); + + assertThat(error).hasValue(0); + assertThat(success).hasValue(numberOfOperations); + assertThat(failed).isFalse(); + } + + @BeforeClass(groups = "e2e", timeOut = TIMEOUT) + public void beforeClass() { + RequestOptions options = new RequestOptions(); + options.setOfferThroughput(10000); + AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); + database = Utils.createDatabaseForTest(housekeepingClient); + collection = housekeepingClient.createCollection("dbs/" + database.getId(), + getCollectionDefinitionWithRangeRangeIndex(), + options) + .toBlocking().single().getResource(); + housekeepingClient.close(); + } + + @DataProvider(name = "collectionLinkTypeArgProvider") + public Object[][] collectionLinkTypeArgProvider() { + return new Object[][]{ + // is namebased + {true}, + // {false}, + }; + } + + @AfterClass(groups = "e2e", timeOut = TIMEOUT) + public void afterClass() { + AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); + Utils.safeCleanDatabases(housekeepingClient); + Utils.safeClean(housekeepingClient, database); + Utils.safeClose(housekeepingClient); + } + + DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList<>(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + IndexingPolicy indexingPolicy = new IndexingPolicy(); + Collection includedPaths = new ArrayList<>(); + IncludedPath includedPath = new IncludedPath(); + includedPath.setPath("/*"); + Collection indexes = new ArrayList<>(); + Index stringIndex = Index.Range(DataType.String); + stringIndex.set("precision", -1); + indexes.add(stringIndex); + + Index numberIndex = Index.Range(DataType.Number); + numberIndex.set("precision", -1); + indexes.add(numberIndex); + includedPath.setIndexes(indexes); + includedPaths.add(includedPath); + indexingPolicy.setIncludedPaths(includedPaths); + + DocumentCollection collectionDefinition = new DocumentCollection(); + collectionDefinition.setIndexingPolicy(indexingPolicy); + collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.setPartitionKey(partitionKeyDef); + + return collectionDefinition; + } + + private void scheduleScaleUp(int delayStartInSeconds, int newThroughput) { + AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); + Observable.timer(delayStartInSeconds, TimeUnit.SECONDS, Schedulers.newThread()).flatMap(aVoid -> { + + // increase throughput to max for a single partition collection to avoid throttling + // for bulk insert and later queries. + return housekeepingClient.queryOffers( + String.format("SELECT * FROM r WHERE r.offerResourceId = '%s'", + collection.getResourceId()) + , null).flatMap(page -> Observable.from(page.getResults())) + .first().flatMap(offer -> { + logger.info("going to scale up collection, newThroughput {}", newThroughput); + offer.setThroughput(newThroughput); + return housekeepingClient.replaceOffer(offer); + }); + }).doOnTerminate(() -> housekeepingClient.close()) + .subscribe(aVoid -> { + }, e -> { + logger.error("failed to scale up collection", e); + failed.set(true); + }, + () -> { + logger.info("Collection Scale up request sent to the service"); + + } + ); + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 840ec341e97b2..66119ea309925 100644 --- a/pom.xml +++ b/pom.xml @@ -207,6 +207,21 @@ + + + e2e + + e2e + + + + + org.apache.maven.plugins + maven-failsafe-plugin + + + + From 32d4f4fa9c0ccb5ea6b598e9103e4260a4bcec76 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Wed, 29 May 2019 20:08:34 -0700 Subject: [PATCH 09/85] added support for time bound testing --- .../cosmosdb/benchmark/AsyncBenchmark.java | 45 +++++++++++++--- .../cosmosdb/benchmark/Configuration.java | 20 +++++++ .../ReadMyWritesConsistencyTest.java | 52 ++++++++++++------- 3 files changed, 93 insertions(+), 24 deletions(-) diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java index 477118e3d51cc..feadcd2f17250 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java @@ -47,17 +47,18 @@ import rx.Subscriber; import java.net.InetSocketAddress; +import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; abstract class AsyncBenchmark { private final MetricRegistry metricsRegistry = new MetricRegistry(); private final ScheduledReporter reporter; - private final CountDownLatch operationCounterLatch; private final String nameCollectionLink; private Meter successMeter; @@ -87,7 +88,6 @@ abstract class AsyncBenchmark { nameCollectionLink = String.format("dbs/%s/colls/%s", database.getId(), collection.getId()); partitionKey = collection.getPartitionKey().getPaths().iterator().next().split("/")[1]; concurrencyControlSemaphore = new Semaphore(cfg.getConcurrency()); - operationCounterLatch = new CountDownLatch(cfg.getNumberOfOperations()); configuration = cfg; ArrayList> createDocumentObservables = new ArrayList<>(); @@ -166,6 +166,25 @@ protected String getDocumentLink(Document doc) { protected abstract void performWorkload(Subscriber subs, long i) throws Exception; + + private boolean shouldContinue(long startTimeMillis, long iterationCount) { + Duration maxDurationTime = configuration.getMaxRunningTimeDuration(); + int maxNumberOfOperations = configuration.getNumberOfOperations(); + if (maxDurationTime == null) { + return iterationCount < maxNumberOfOperations; + } + + if (startTimeMillis + maxDurationTime.toMillis() < System.currentTimeMillis()) { + return false; + } + + if (maxNumberOfOperations < 0) { + return true; + } + + return iterationCount < maxNumberOfOperations; + } + void run() throws Exception { successMeter = metricsRegistry.meter("#Successful Operations"); @@ -178,7 +197,10 @@ void run() throws Exception { long startTime = System.currentTimeMillis(); - for (long i = 1; i <= configuration.getNumberOfOperations(); i++) { + int maxNumberOfOperations = configuration.getNumberOfOperations(); + CountDownLatch terminationLatch = new CountDownLatch(1); + AtomicInteger count = new AtomicInteger(0); + for (long i = 1; (maxNumberOfOperations < 0 ? true : i < maxNumberOfOperations) && terminationLatch.getCount() > 0; i++) { Subscriber subs = new Subscriber() { @@ -190,8 +212,11 @@ public void onStart() { public void onCompleted() { successMeter.mark(); concurrencyControlSemaphore.release(); - operationCounterLatch.countDown(); AsyncBenchmark.this.onSuccess(); + + if (!shouldContinue(startTime, count.incrementAndGet())) { + terminationLatch.countDown(); + } } @Override @@ -200,8 +225,12 @@ public void onError(Throwable e) { logger.error("Encountered failure {} on thread {}" , e.getMessage(), Thread.currentThread().getName(), e); concurrencyControlSemaphore.release(); - operationCounterLatch.countDown(); AsyncBenchmark.this.onError(e); + count.incrementAndGet(); + + if (!shouldContinue(startTime, count.incrementAndGet())) { + terminationLatch.countDown(); + } } @Override @@ -212,7 +241,8 @@ public void onNext(T value) { performWorkload(subs, i); } - operationCounterLatch.await(); + terminationLatch.await(); + long endTime = System.currentTimeMillis(); logger.info("[{}] operations performed in [{}] seconds.", configuration.getNumberOfOperations(), (int) ((endTime - startTime) / 1000)); @@ -220,4 +250,7 @@ public void onNext(T value) { reporter.report(); reporter.close(); } + + + } diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java index 915591f8b7c9f..53d92aa15612f 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java +++ b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java @@ -23,6 +23,7 @@ package com.microsoft.azure.cosmosdb.benchmark; +import java.time.Duration; import java.util.Arrays; import org.apache.commons.lang3.StringUtils; @@ -99,6 +100,20 @@ class Configuration { @Parameter(names = "-numberOfOperations", description = "Total Number Of Documents To Insert") private int numberOfOperations = 100000; + static class DurationConverter implements IStringConverter { + @Override + public Duration convert(String value) { + if (value == null) { + return null; + } + + return Duration.parse(value); + } + } + + @Parameter(names = "-maxRunningTimeDuration", description = "Max Running Time Duration", converter = DurationConverter.class) + private Duration maxRunningTimeDuration; + @Parameter(names = "-printingInterval", description = "Interval of time after which Metrics should be printed (seconds)") private int printingInterval = 10; @@ -181,6 +196,11 @@ public ConsistencyLevel convert(String value) { } } + + Duration getMaxRunningTimeDuration() { + return maxRunningTimeDuration; + } + Operation getOperationType() { return operation; } diff --git a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java index c05744b9261f4..d417bf5cdbf4f 100644 --- a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java @@ -45,6 +45,7 @@ import rx.Observable; import rx.schedulers.Schedulers; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; @@ -56,27 +57,37 @@ public class ReadMyWritesConsistencyTest { private final static Logger logger = LoggerFactory.getLogger(ReadMyWritesConsistencyTest.class); - private final static int TIMEOUT = 60 * 60 * 1000; - private final AtomicBoolean failed = new AtomicBoolean(false); + private final int initialCollectionThroughput = 10_000; + private final int newCollectionThroughput = 100_000; + private final int delayForInitiationCollectionScaleUpInSeconds = 120; + private final Duration defaultMaxRunningTimeInSeconds = Duration.ofMinutes(40); + + private final String maxRunningTime = + System.getProperty("MAX_RUNNING_TIME", StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("MAX_RUNNING_TIME")), defaultMaxRunningTimeInSeconds.toString())); + + private final AtomicBoolean collectionScaleUpFailed = new AtomicBoolean(false); private final String desiredConsistency = System.getProperty("DESIRED_CONSISTENCY", StringUtils.defaultString(Strings.emptyToNull( - System.getenv().get("DESIRED_CONSISTENCY")), "Strong")); + System.getenv().get("DESIRED_CONSISTENCY")), "Session")); private final String numberOfOperationsAsString = System.getProperty("NUMBER_OF_OPERATIONS", StringUtils.defaultString(Strings.emptyToNull( - System.getenv().get("NUMBER_OF_OPERATIONS")), Integer.toString(400_000))); + System.getenv().get("NUMBER_OF_OPERATIONS")), "-1")); + private Database database; private DocumentCollection collection; - @Test(dataProvider = "collectionLinkTypeArgProvider", groups = "e2e", timeOut = TIMEOUT) + @Test(dataProvider = "collectionLinkTypeArgProvider", groups = "e2e") public void readMyWrites(boolean useNameLink) throws Exception { - int numberOfOperations = Integer.parseInt(numberOfOperationsAsString); int concurrency = 5; String cmdFormat = "-serviceEndpoint %s -masterKey %s" + " -databaseId %s -collectionId %s" + - " -consistencyLevel %s -concurrency %d -numberOfOperations %s" + + " -consistencyLevel %s -concurrency %d" + + " -numberOfOperations %s" + + " -maxRunningTimeDuration %s" + " -operation ReadMyWrites -connectionMode Direct -numberOfPreCreatedDocuments 100 " + " -printingInterval 60"; @@ -87,7 +98,8 @@ public void readMyWrites(boolean useNameLink) throws Exception { collection.getId(), desiredConsistency, concurrency, - numberOfOperations) + numberOfOperationsAsString, + maxRunningTime) + (useNameLink ? " -useNameLink" : ""); Configuration cfg = new Configuration(); @@ -108,21 +120,26 @@ protected void onSuccess() { } }; - // schedules a collection scale up in 2 minutes - scheduleScaleUp(120, 100_000); + // schedules a collection scale up after a delay + scheduleScaleUp(delayForInitiationCollectionScaleUpInSeconds, newCollectionThroughput); wf.run(); wf.shutdown(); + int numberOfOperations = Integer.parseInt(numberOfOperationsAsString); + assertThat(error).hasValue(0); - assertThat(success).hasValue(numberOfOperations); - assertThat(failed).isFalse(); + assertThat(collectionScaleUpFailed).isFalse(); + + if (numberOfOperations > 0) { + assertThat(success).hasValue(numberOfOperations); + } } - @BeforeClass(groups = "e2e", timeOut = TIMEOUT) + @BeforeClass(groups = "e2e") public void beforeClass() { RequestOptions options = new RequestOptions(); - options.setOfferThroughput(10000); + options.setOfferThroughput(initialCollectionThroughput); AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); database = Utils.createDatabaseForTest(housekeepingClient); collection = housekeepingClient.createCollection("dbs/" + database.getId(), @@ -137,11 +154,10 @@ public Object[][] collectionLinkTypeArgProvider() { return new Object[][]{ // is namebased {true}, - // {false}, }; } - @AfterClass(groups = "e2e", timeOut = TIMEOUT) + @AfterClass(groups = "e2e") public void afterClass() { AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); Utils.safeCleanDatabases(housekeepingClient); @@ -196,8 +212,8 @@ private void scheduleScaleUp(int delayStartInSeconds, int newThroughput) { }).doOnTerminate(() -> housekeepingClient.close()) .subscribe(aVoid -> { }, e -> { - logger.error("failed to scale up collection", e); - failed.set(true); + logger.error("collectionScaleUpFailed to scale up collection", e); + collectionScaleUpFailed.set(true); }, () -> { logger.info("Collection Scale up request sent to the service"); From 9ba584bcfed181c04bda1c3876fa0b7ccb691456 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Wed, 29 May 2019 20:22:54 -0700 Subject: [PATCH 10/85] updated timeouts --- .../java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java | 4 ++-- .../microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java index e24c766cf8f82..d0823237bf362 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java @@ -88,8 +88,8 @@ public class TestSuiteBase { private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; private static final ObjectMapper objectMapper = new ObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); - protected static final int TIMEOUT = 30000; - protected static final int FEED_TIMEOUT = 24000; + protected static final int TIMEOUT = 40000; + protected static final int FEED_TIMEOUT = 40000; protected static final int SETUP_TIMEOUT = 60000; protected static final int SHUTDOWN_TIMEOUT = 12000; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java index 149ea0691a825..da3b6b946d98c 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java @@ -90,8 +90,8 @@ public class TestSuiteBase { private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; private static final ObjectMapper objectMapper = new ObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); - protected static final int TIMEOUT = 30000; - protected static final int FEED_TIMEOUT = 24000; + protected static final int TIMEOUT = 40000; + protected static final int FEED_TIMEOUT = 40000; protected static final int SETUP_TIMEOUT = 60000; protected static final int SHUTDOWN_TIMEOUT = 12000; From 5627f77cc83ec3aa1ae588ae50c14f04a08a1c87 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Thu, 30 May 2019 09:47:48 -0700 Subject: [PATCH 11/85] cleanup --- .../microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java | 5 ----- .../microsoft/azure/cosmosdb/benchmark/Configuration.java | 1 - 2 files changed, 6 deletions(-) diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java index feadcd2f17250..a6d9b0408223d 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java @@ -166,7 +166,6 @@ protected String getDocumentLink(Document doc) { protected abstract void performWorkload(Subscriber subs, long i) throws Exception; - private boolean shouldContinue(long startTimeMillis, long iterationCount) { Duration maxDurationTime = configuration.getMaxRunningTimeDuration(); int maxNumberOfOperations = configuration.getNumberOfOperations(); @@ -242,7 +241,6 @@ public void onNext(T value) { } terminationLatch.await(); - long endTime = System.currentTimeMillis(); logger.info("[{}] operations performed in [{}] seconds.", configuration.getNumberOfOperations(), (int) ((endTime - startTime) / 1000)); @@ -250,7 +248,4 @@ public void onNext(T value) { reporter.report(); reporter.close(); } - - - } diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java index 53d92aa15612f..2b1e350afcf1f 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java +++ b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java @@ -196,7 +196,6 @@ public ConsistencyLevel convert(String value) { } } - Duration getMaxRunningTimeDuration() { return maxRunningTimeDuration; } From fd9c4bdb159f489b478fbf14bc4c71b2b1ad6bce Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Thu, 30 May 2019 11:11:08 -0700 Subject: [PATCH 12/85] remove system.exit to avoid killing jvm on test --- .../main/java/com/microsoft/azure/cosmosdb/benchmark/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Main.java b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Main.java index 18c20c619fafc..ecfc9c5823ca0 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Main.java +++ b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Main.java @@ -93,7 +93,7 @@ public static void main(String[] args) throws Exception { // if any error in parsing the cmd-line options print out the usage help System.err.println("Invalid Usage: " + e.getMessage()); System.err.println("Try '-help' for more information."); - System.exit(1); + throw e; } } } From c64bd1af8b71322770d5d951c67751d5017dcdf0 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Thu, 30 May 2019 11:38:27 -0700 Subject: [PATCH 13/85] minor update --- .../azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java index d417bf5cdbf4f..88f90813b37de 100644 --- a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java @@ -60,7 +60,7 @@ public class ReadMyWritesConsistencyTest { private final int initialCollectionThroughput = 10_000; private final int newCollectionThroughput = 100_000; private final int delayForInitiationCollectionScaleUpInSeconds = 120; - private final Duration defaultMaxRunningTimeInSeconds = Duration.ofMinutes(40); + private final Duration defaultMaxRunningTimeInSeconds = Duration.ofMinutes(45); private final String maxRunningTime = System.getProperty("MAX_RUNNING_TIME", StringUtils.defaultString(Strings.emptyToNull( From d6f58aba78c32a683e89c391189ea99b6f5fb44b Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Thu, 30 May 2019 13:28:44 -0700 Subject: [PATCH 14/85] fixed test --- .../azure/cosmosdb/benchmark/AsyncBenchmark.java | 2 +- .../microsoft/azure/cosmosdb/rx/CollectionCrudTest.java | 9 ++------- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java index a6d9b0408223d..8a62428a9bf50 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java @@ -199,7 +199,7 @@ void run() throws Exception { int maxNumberOfOperations = configuration.getNumberOfOperations(); CountDownLatch terminationLatch = new CountDownLatch(1); AtomicInteger count = new AtomicInteger(0); - for (long i = 1; (maxNumberOfOperations < 0 ? true : i < maxNumberOfOperations) && terminationLatch.getCount() > 0; i++) { + for (long i = 0; (maxNumberOfOperations < 0 ? true : i < maxNumberOfOperations) && terminationLatch.getCount() > 0; i++) { Subscriber subs = new Subscriber() { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java index e7004c42ff44c..5e194e2903450 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java @@ -262,13 +262,9 @@ public void replaceCollection(String collectionName, boolean isNameBased) { public void sessionTokenConsistencyCollectionDeleteCreateSameName() { AsyncDocumentClient client1 = clientBuilder.build(); AsyncDocumentClient client2 = clientBuilder.build(); - - String dbId = "db"; - String collectionId = "coll"; try { - Database databaseDefinition = new Database(); - databaseDefinition.setId(dbId); - createDatabase(client1, dbId); + String dbId = database.getId(); + String collectionId = "coll"; DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setId(collectionId); @@ -307,7 +303,6 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { assertThat(readDocument.getId().equals(newDocument.getId())).isTrue(); assertThat(readDocument.get("name").equals(newDocument.get("name"))).isTrue(); } finally { - safeDeleteDatabase(client1, dbId); safeClose(client1); safeClose(client2); } From b508fde85e6746e45ceb5ecabc5a403d29dd2918 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Thu, 30 May 2019 13:34:42 -0700 Subject: [PATCH 15/85] fixed test --- .../azure/cosmosdb/rx/CollectionCrudTest.java | 55 ++++++++++--------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java index 5e194e2903450..d60b94f64c44a 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java @@ -1,17 +1,17 @@ /* * The MIT License (MIT) * Copyright (c) 2018 Microsoft Corporation - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -92,13 +92,13 @@ private DocumentCollection getCollectionDefinition(String collectionName) { @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") public void createCollection(String collectionName, boolean isNameBased) { DocumentCollection collectionDefinition = getCollectionDefinition(collectionName); - + Observable> createObservable = client .createCollection(getDatabaseLink(database, isNameBased), collectionDefinition, null); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .withId(collectionDefinition.getId()).build(); - + validateSuccess(createObservable, validator); safeDeleteAllCollections(client, database); } @@ -124,17 +124,17 @@ public void createCollectionWithCompositeIndexAndSpatialSpec() { compositePath5.setOrder(CompositePathSortOrder.Descending); CompositePath compositePath6 = new CompositePath(); compositePath6.setPath("/path6"); - + ArrayList compositeIndex1 = new ArrayList(); compositeIndex1.add(compositePath1); compositeIndex1.add(compositePath2); compositeIndex1.add(compositePath3); - + ArrayList compositeIndex2 = new ArrayList(); compositeIndex2.add(compositePath4); compositeIndex2.add(compositePath5); compositeIndex2.add(compositePath6); - + Collection> compositeIndexes = new ArrayList>(); compositeIndexes.add(compositeIndex1); compositeIndexes.add(compositeIndex2); @@ -145,7 +145,7 @@ public void createCollectionWithCompositeIndexAndSpatialSpec() { SpatialType.LineString, SpatialType.Polygon, SpatialType.MultiPolygon - }; + }; Collection spatialIndexes = new ArrayList(); for (int index = 0; index < 2; index++) { Collection collectionOfSpatialTypes = new ArrayList(); @@ -159,12 +159,12 @@ public void createCollectionWithCompositeIndexAndSpatialSpec() { spec.setSpatialTypes(collectionOfSpatialTypes); spatialIndexes.add(spec); } - + indexingPolicy.setSpatialIndexes(spatialIndexes); collection.setId(UUID.randomUUID().toString()); collection.setIndexingPolicy(indexingPolicy); - + Observable> createObservable = client .createCollection(database.getSelfLink(), collection, null); @@ -173,7 +173,7 @@ public void createCollectionWithCompositeIndexAndSpatialSpec() { .withCompositeIndexes(compositeIndexes) .withSpatialIndexes(spatialIndexes) .build(); - + validateSuccess(createObservable, validator); safeDeleteAllCollections(client, database); } @@ -181,9 +181,9 @@ public void createCollectionWithCompositeIndexAndSpatialSpec() { @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") public void readCollection(String collectionName, boolean isNameBased) { DocumentCollection collectionDefinition = getCollectionDefinition(collectionName); - + Observable> createObservable = client.createCollection(getDatabaseLink(database, isNameBased), collectionDefinition, - null); + null); DocumentCollection collection = createObservable.toBlocking().single().getResource(); Observable> readObservable = client.readCollection(getCollectionLink(database, collection, isNameBased), null); @@ -197,11 +197,11 @@ public void readCollection(String collectionName, boolean isNameBased) { @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") public void readCollection_NameBase(String collectionName, boolean isNameBased) { DocumentCollection collectionDefinition = getCollectionDefinition(collectionName); - + Observable> createObservable = client.createCollection(getDatabaseLink(database, isNameBased), collectionDefinition, - null); + null); DocumentCollection collection = createObservable.toBlocking().single().getResource(); - + Observable> readObservable = client.readCollection( getCollectionLink(database, collection, isNameBased), null); @@ -224,12 +224,12 @@ public void readCollection_DoesntExist(String collectionName, boolean isNameBase @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") public void deleteCollection(String collectionName, boolean isNameBased) { DocumentCollection collectionDefinition = getCollectionDefinition(collectionName); - + Observable> createObservable = client.createCollection(getDatabaseLink(database, isNameBased), collectionDefinition, null); DocumentCollection collection = createObservable.toBlocking().single().getResource(); Observable> deleteObservable = client.deleteCollection(getCollectionLink(database, collection, isNameBased), - null); + null); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .nullResource().build(); @@ -244,13 +244,13 @@ public void replaceCollection(String collectionName, boolean isNameBased) { DocumentCollection collection = createObservable.toBlocking().single().getResource(); // sanity check assertThat(collection.getIndexingPolicy().getIndexingMode()).isEqualTo(IndexingMode.Consistent); - + // replace indexing mode IndexingPolicy indexingMode = new IndexingPolicy(); indexingMode.setIndexingMode(IndexingMode.Lazy); collection.setIndexingPolicy(indexingMode); Observable> readObservable = client.replaceCollection(collection, null); - + // validate ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .indexingMode(IndexingMode.Lazy).build(); @@ -258,13 +258,17 @@ public void replaceCollection(String collectionName, boolean isNameBased) { safeDeleteAllCollections(client, database); } - @Test(groups = { "emulator" }, timeOut = TIMEOUT) + @Test(groups = { "emulator" }, timeOut = 10 * TIMEOUT) public void sessionTokenConsistencyCollectionDeleteCreateSameName() { AsyncDocumentClient client1 = clientBuilder.build(); AsyncDocumentClient client2 = clientBuilder.build(); + + String dbId = DatabaseForTest.generateId(); + String collectionId = "coll"; try { - String dbId = database.getId(); - String collectionId = "coll"; + Database databaseDefinition = new Database(); + databaseDefinition.setId(dbId); + createDatabase(client1, dbId); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setId(collectionId); @@ -280,7 +284,7 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { document.set("name", "New Updated Document"); ResourceResponse upsertDocumentResponse = client1.upsertDocument(collection.getSelfLink(), document, null, - true).toBlocking().single(); + true).toBlocking().single(); logger.info("Client 1 Upsert Document Client Side Request Statistics {}", upsertDocumentResponse.getRequestDiagnosticsString()); logger.info("Client 1 Upsert Document Latency {}", upsertDocumentResponse.getRequestLatency()); @@ -303,6 +307,7 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { assertThat(readDocument.getId().equals(newDocument.getId())).isTrue(); assertThat(readDocument.get("name").equals(newDocument.get("name"))).isTrue(); } finally { + safeDeleteDatabase(client1, dbId); safeClose(client1); safeClose(client2); } From f7bac1e6b167b9ca81ad759602ef466d678c782e Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Fri, 31 May 2019 10:05:02 -0700 Subject: [PATCH 16/85] added retry --- .../azure/cosmosdb/RetryAnalyzier.java | 56 +++++++++++++++++++ .../azure/cosmosdb/rx/TestConfigurations.java | 7 +++ .../cosmosdb/rx/OrderbyDocumentQueryTest.java | 6 +- .../azure/cosmosdb/rx/TopQueryTests.java | 6 +- 4 files changed, 71 insertions(+), 4 deletions(-) create mode 100644 commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java new file mode 100644 index 0000000000000..51f74439b30aa --- /dev/null +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java @@ -0,0 +1,56 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + + +package com.microsoft.azure.cosmosdb; + +import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestResult; +import org.testng.util.RetryAnalyzerCount; + +import java.util.concurrent.TimeUnit; + +public class RetryAnalyzier extends RetryAnalyzerCount { + private final Logger logger = LoggerFactory.getLogger(RetryAnalyzier.class); + private final int waitBetweenRetriesInSeconds = 120; + private final int retryLimit; + + public RetryAnalyzier() { + this.retryLimit = Integer.parseInt(TestConfigurations.MAX_RETRY_LIMIT); + this.setCount(retryLimit); + } + + @Override + public boolean retryMethod(ITestResult result) { + try { + TimeUnit.SECONDS.sleep(waitBetweenRetriesInSeconds); + } catch (InterruptedException e) { + return false; + } + + return true; + } + +} diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java index a6f115439e9e8..717b81da2d7af 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java @@ -64,4 +64,11 @@ public final class TestConfigurations { System.getProperty("PREFERRED_LOCATIONS", StringUtils.defaultString(Strings.emptyToNull( System.getenv().get("PREFERRED_LOCATIONS")), null)); + + public static String MAX_RETRY_LIMIT = + System.getProperty("MAX_RETRY_LIMIT", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("MAX_RETRY_LIMIT")), + "1")); + } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java index cca649efba67a..7e00e6e573793 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java @@ -35,6 +35,7 @@ import java.util.function.Function; import java.util.stream.Collectors; +import com.microsoft.azure.cosmosdb.RetryAnalyzier; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.core.JsonProcessingException; @@ -58,6 +59,7 @@ import com.microsoft.azure.cosmosdb.rx.internal.query.CompositeContinuationToken; import com.microsoft.azure.cosmosdb.rx.internal.query.OrderByContinuationToken; +import org.testng.util.RetryAnalyzerCount; import rx.Observable; import rx.observers.TestSubscriber; @@ -372,8 +374,8 @@ public void orderByContinuationTokenRoundTrip() throws Exception { assertThat(OrderByContinuationToken.tryParse("{\"property\" : \"Not a valid Order By Token\"}", outOrderByContinuationToken)).isFalse(); } } - - @Test(groups = { "simple" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder") + @Test(groups = { "simple" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder", + retryAnalyzer = RetryAnalyzier.class) public void queryDocumentsWithOrderByContinuationTokensInteger(String sortOrder) throws Exception { // Get Actual String query = String.format("SELECT * FROM c ORDER BY c.propInt %s", sortOrder); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java index f2b1cbb7a163a..88c201a93fbbd 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java @@ -30,6 +30,7 @@ import java.util.Set; import java.util.concurrent.TimeUnit; +import com.microsoft.azure.cosmosdb.RetryAnalyzier; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -66,7 +67,8 @@ public TopQueryTests(AsyncDocumentClient.Builder clientBuilder) { this.clientBuilder = clientBuilder; } - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider", retryAnalyzer = RetryAnalyzier.class + ) public void queryDocumentsWithTop(boolean qmEnabled) throws Exception { FeedOptions options = new FeedOptions(); @@ -151,7 +153,7 @@ public void topContinuationTokenRoundTrips() throws Exception { } } - @Test(groups = { "simple" }, timeOut = TIMEOUT * 10) + @Test(groups = { "simple" }, timeOut = TIMEOUT * 10, retryAnalyzer = RetryAnalyzier.class) public void queryDocumentsWithTopContinuationTokens() throws Exception { String query = "SELECT TOP 8 * FROM c"; this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10 }, 8); From 6168b32961c664a9205654d651e11a6b1e9a3f08 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Fri, 31 May 2019 11:28:29 -0700 Subject: [PATCH 17/85] increased retry --- .../java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java | 4 +--- .../microsoft/azure/cosmosdb/rx/TestConfigurations.java | 2 +- .../azure/cosmosdb/rx/OrderbyDocumentQueryTest.java | 7 +++++++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java index 51f74439b30aa..ebe1ab5c6554c 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java @@ -35,11 +35,9 @@ public class RetryAnalyzier extends RetryAnalyzerCount { private final Logger logger = LoggerFactory.getLogger(RetryAnalyzier.class); private final int waitBetweenRetriesInSeconds = 120; - private final int retryLimit; public RetryAnalyzier() { - this.retryLimit = Integer.parseInt(TestConfigurations.MAX_RETRY_LIMIT); - this.setCount(retryLimit); + this.setCount(Integer.parseInt(TestConfigurations.MAX_RETRY_LIMIT)); } @Override diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java index 717b81da2d7af..4b2ec3d6f9942 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java @@ -69,6 +69,6 @@ public final class TestConfigurations { System.getProperty("MAX_RETRY_LIMIT", StringUtils.defaultString(Strings.emptyToNull( System.getenv().get("MAX_RETRY_LIMIT")), - "1")); + "2")); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java index 7e00e6e573793..69e68daa6d033 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java @@ -41,6 +41,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; @@ -440,6 +441,12 @@ public List bulkInsert(AsyncDocumentClient client, List Date: Fri, 31 May 2019 13:04:22 -0700 Subject: [PATCH 18/85] disabled retry throttle test --- .../azure/cosmosdb/rx/internal/RetryThrottleTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java index 2f438b764604c..63498109452c4 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java @@ -70,7 +70,7 @@ public class RetryThrottleTest extends TestSuiteBase { private Database database; private DocumentCollection collection; - @Test(groups = { "long" }, timeOut = LARGE_TIMEOUT ) + @Test(groups = { "long" }, timeOut = LARGE_TIMEOUT, enabled = false) public void retryCreateDocumentsOnSpike() throws Exception { ConnectionPolicy policy = new ConnectionPolicy(); RetryOptions retryOptions = new RetryOptions(); @@ -118,7 +118,7 @@ public Observable answer(InvocationOnMock invocation) System.out.println("total count is " + totalCount.get()); } - @Test(groups = { "long" }, timeOut = TIMEOUT) + @Test(groups = { "long" }, timeOut = TIMEOUT, enabled = false) public void retryDocumentCreate() throws Exception { client = SpyClientUnderTestFactory.createClientWithGatewaySpy(createGatewayRxDocumentClient()); @@ -153,12 +153,12 @@ public Observable answer(InvocationOnMock invocation) validateSuccess(createObservable, validator, TIMEOUT); } - @AfterMethod(groups = { "long" }) + @AfterMethod(groups = { "long" }, enabled = false) private void afterMethod() { safeClose(client); } - @BeforeClass(groups = { "long" }, timeOut = SETUP_TIMEOUT) + @BeforeClass(groups = { "long" }, timeOut = SETUP_TIMEOUT, enabled = false) public void beforeClass() { // set up the client database = SHARED_DATABASE; @@ -176,7 +176,7 @@ private Document getDocumentDefinition() { return doc; } - @AfterClass(groups = { "long" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + @AfterClass(groups = { "long" }, timeOut = SHUTDOWN_TIMEOUT, enabled = false) public void afterClass() { } } From cbd6b9f3a3da152f8ba0e9cee16fdc48187dac9f Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Fri, 31 May 2019 14:04:45 -0700 Subject: [PATCH 19/85] retry added --- .../com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java | 3 ++- .../azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java index d60b94f64c44a..0d1758dee2017 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java @@ -30,6 +30,7 @@ import com.microsoft.azure.cosmosdb.DatabaseForTest; import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; +import com.microsoft.azure.cosmosdb.RetryAnalyzier; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; @@ -258,7 +259,7 @@ public void replaceCollection(String collectionName, boolean isNameBased) { safeDeleteAllCollections(client, database); } - @Test(groups = { "emulator" }, timeOut = 10 * TIMEOUT) + @Test(groups = { "emulator" }, timeOut = 10 * TIMEOUT, retryAnalyzer = RetryAnalyzier.class) public void sessionTokenConsistencyCollectionDeleteCreateSameName() { AsyncDocumentClient client1 = clientBuilder.build(); AsyncDocumentClient client2 = clientBuilder.build(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java index b196a888e376d..d46b88561d9a5 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java @@ -26,6 +26,7 @@ import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.RetryAnalyzier; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import org.apache.commons.lang3.StringUtils; @@ -53,7 +54,7 @@ public VeryLargeDocumentQueryTest(Builder clientBuilder) { this.clientBuilder = clientBuilder; } - @Test(groups = { "emulator" }, timeOut = TIMEOUT) + @Test(groups = { "emulator" }, timeOut = TIMEOUT, retryAnalyzer = RetryAnalyzier.class) public void queryLargeDocuments() { int cnt = 5; for(int i = 0; i < cnt; i++) { From f53a8f8103804df1726938704812a14cbc74deab Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Fri, 31 May 2019 18:22:28 -0700 Subject: [PATCH 20/85] added support for reading test config from env --- .../azure/cosmosdb/rx/TestConfigurations.java | 11 + .../azure/cosmosdb/rx/ParsingEnvTest.java | 66 ++ .../azure/cosmosdb/rx/TestSuiteBase.java | 141 ++- .../cosmosdb/rx/internal/TestSuiteBase.java | 1012 ----------------- 4 files changed, 161 insertions(+), 1069 deletions(-) create mode 100644 sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParsingEnvTest.java delete mode 100644 sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java index 4b2ec3d6f9942..a6847021992e5 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java @@ -71,4 +71,15 @@ public final class TestConfigurations { System.getenv().get("MAX_RETRY_LIMIT")), "2")); + public static String DESIRED_CONSISTENCIES = + System.getProperty("DESIRED_CONSISTENCIES", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("DESIRED_CONSISTENCIES")), + null)); + + public static String PROTOCOLS = + System.getProperty("PROTOCOLS", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("PROTOCOLS")), + null)); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParsingEnvTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParsingEnvTest.java new file mode 100644 index 0000000000000..e0e0eb8d1c020 --- /dev/null +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParsingEnvTest.java @@ -0,0 +1,66 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.microsoft.azure.cosmosdb.rx; + +import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import org.testng.annotations.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ParsingEnvTest { + + @Test(groups = "unit") + public void parseDesiredConsistencies() { + assertThat(TestSuiteBase.parseDesiredConsistencies("[ \"Session\" , \"Strong\" ]")).containsExactly( + ConsistencyLevel.Session, ConsistencyLevel.Strong); + } + + @Test(groups = "unit") + public void parseDesiredConsistencies_null() { + assertThat(TestSuiteBase.parseDesiredConsistencies(null)).isNull(); + } + + @Test(groups = "unit") + public void lowerConsistencies() { + assertThat(TestSuiteBase.allEqualOrLowerConsistencies(ConsistencyLevel.Session)) + .containsExactly(ConsistencyLevel.Session, ConsistencyLevel.ConsistentPrefix, ConsistencyLevel.Eventual); + } + + @Test(groups = "unit") + public void parsePreferredLocation() { + assertThat(TestSuiteBase.parsePreferredLocation("[ \"central us\" , \"central us2\" ]")) + .containsExactly("central us", "central us2"); + } + + @Test(groups = "unit") + public void parsePreferredLocation_null() { + assertThat(TestSuiteBase.parsePreferredLocation(null)).isNull(); + } + + @Test(groups = "unit") + public void protocols() { + assertThat(TestSuiteBase.parseProtocols("[ \"Tcp\" , \"Https\" ]")).containsExactly(Protocol.Tcp, Protocol.Https); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java index d0823237bf362..ef23f4e6c4232 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java @@ -40,6 +40,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; import com.microsoft.azure.cosmosdb.DataType; import com.microsoft.azure.cosmosdb.DatabaseForTest; import com.microsoft.azure.cosmosdb.DocumentClientException; @@ -52,6 +53,7 @@ import com.microsoft.azure.cosmosdb.internal.PathParser; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; import com.microsoft.azure.cosmosdb.rx.internal.Configs; +import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.mockito.stubbing.Answer; import org.slf4j.Logger; @@ -98,10 +100,12 @@ public class TestSuiteBase { protected static final int WAIT_REPLICA_CATCH_UP_IN_MILLIS = 4000; - protected int subscriberValidationTimeout = TIMEOUT; - - protected static ConsistencyLevel accountConsistency; + protected final static ConsistencyLevel accountConsistency; + protected static final ImmutableList preferredLocations; + private static final ImmutableList desiredConsistencies; + private static final ImmutableList protocols; + protected int subscriberValidationTimeout = TIMEOUT; protected Builder clientBuilder; protected static Database SHARED_DATABASE; @@ -110,6 +114,15 @@ public class TestSuiteBase { protected static DocumentCollection SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; protected static DocumentCollection SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES; + static { + accountConsistency = parseConsistency(TestConfigurations.CONSISTENCY); + desiredConsistencies = immutableListOrNull( + ObjectUtils.defaultIfNull(parseDesiredConsistencies(TestConfigurations.DESIRED_CONSISTENCIES), + allEqualOrLowerConsistencies(accountConsistency))); + preferredLocations = immutableListOrNull(parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS)); + protocols = ObjectUtils.defaultIfNull(immutableListOrNull(parseProtocols(TestConfigurations.PROTOCOLS)), + ImmutableList.of(Protocol.Https, Protocol.Tcp)); + } protected TestSuiteBase() { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -119,7 +132,11 @@ protected TestSuiteBase() { logger.debug("Initializing {} ...", this.getClass().getSimpleName()); } - @BeforeMethod(groups = { "simple", "long", "direct", "multi-master", "emulator", "non-emulator" }) + private static ImmutableList immutableListOrNull(List list) { + return list != null ? ImmutableList.copyOf(list) : null; + } + + @BeforeMethod(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}) public void beforeMethod(Method method) { if (this.clientBuilder != null) { logger.info("Starting {}::{} using {} {} mode with {} consistency", @@ -132,7 +149,7 @@ public void beforeMethod(Method method) { logger.info("Starting {}::{}", method.getDeclaringClass().getSimpleName(), method.getName()); } - @AfterMethod(groups = { "simple", "long", "direct", "multi-master", "emulator", "non-emulator" }) + @AfterMethod(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}) public void afterMethod(Method m) { Test t = m.getAnnotation(Test.class); logger.info("Finished {}:{}.", m.getDeclaringClass().getSimpleName(), m.getName()); @@ -166,7 +183,7 @@ public Observable> deleteDatabase(String id) { } } - @BeforeSuite(groups = { "simple", "long", "direct", "multi-master", "emulator", "non-emulator" }, timeOut = SUITE_SETUP_TIMEOUT) + @BeforeSuite(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}, timeOut = SUITE_SETUP_TIMEOUT) public static void beforeSuite() { logger.info("beforeSuite Started"); AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); @@ -184,7 +201,7 @@ public static void beforeSuite() { } } - @AfterSuite(groups = { "simple", "long", "direct", "multi-master", "emulator", "non-emulator" }, timeOut = SUITE_SHUTDOWN_TIMEOUT) + @AfterSuite(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}, timeOut = SUITE_SHUTDOWN_TIMEOUT) public static void afterSuite() { logger.info("afterSuite Started"); AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); @@ -653,7 +670,7 @@ static protected void safeDeleteAllCollections(AsyncDocumentClient client, Datab .toBlocking() .single(); - for(DocumentCollection collection: collections) { + for (DocumentCollection collection : collections) { client.deleteCollection(collection.getSelfLink(), null).toBlocking().single().getResource(); } } @@ -760,15 +777,15 @@ public static void validateQueryFailure(Observable parsePreferredLocation(String preferredLocations) { + static List parsePreferredLocation(String preferredLocations) { if (StringUtils.isEmpty(preferredLocations)) { return null; } try { - return objectMapper.readValue(preferredLocations, new TypeReference>(){}); + return objectMapper.readValue(preferredLocations, new TypeReference>() { + }); } catch (Exception e) { logger.error("Invalid configured test preferredLocations [{}].", preferredLocations); throw new IllegalStateException("Invalid configured test preferredLocations " + preferredLocations); } } + static List parseProtocols(String protocols) { + if (StringUtils.isEmpty(protocols)) { + return null; + } + + try { + return objectMapper.readValue(protocols, new TypeReference>() { + }); + } catch (Exception e) { + logger.error("Invalid configured test protocols [{}].", protocols); + throw new IllegalStateException("Invalid configured test protocols " + protocols); + } + } + @DataProvider public static Object[][] simpleClientBuildersWithDirect() { - return simpleClientBuildersWithDirect(Protocol.Https, Protocol.Tcp); + return simpleClientBuildersWithDirect(toArray(protocols)); } @DataProvider @@ -808,31 +840,11 @@ public static Object[][] simpleClientBuildersWithDirectHttps() { return simpleClientBuildersWithDirect(Protocol.Https); } - @DataProvider - public static Object[][] simpleClientBuildersWithDirectTcp() { - return simpleClientBuildersWithDirect(Protocol.Tcp); - } - private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) { - - accountConsistency = parseConsistency(TestConfigurations.CONSISTENCY); logger.info("Max test consistency to use is [{}]", accountConsistency); - List testConsistencies = new ArrayList<>(); - - switch (accountConsistency) { - case Strong: - case BoundedStaleness: - case Session: - case ConsistentPrefix: - case Eventual: - testConsistencies.add(ConsistencyLevel.Eventual); - break; - default: - throw new IllegalStateException("Invalid configured test consistency " + accountConsistency); - } - - List preferredLocation = parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS); - boolean isMultiMasterEnabled = preferredLocation != null && accountConsistency == ConsistencyLevel.Session; + List testConsistencies = ImmutableList.of(ConsistencyLevel.Eventual); + + boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.Session; List builders = new ArrayList<>(); builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null)); @@ -841,7 +853,7 @@ private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) testConsistencies.forEach(consistencyLevel -> builders.add(createDirectRxDocumentClient(consistencyLevel, protocol, isMultiMasterEnabled, - preferredLocation))); + preferredLocations))); } builders.forEach(b -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", @@ -855,7 +867,7 @@ private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) @DataProvider public static Object[][] clientBuildersWithDirect() { - return clientBuildersWithDirectAllConsistencies(Protocol.Https, Protocol.Tcp); + return clientBuildersWithDirectAllConsistencies(toArray(protocols)); } @DataProvider @@ -864,24 +876,41 @@ public static Object[][] clientBuildersWithDirectHttps() { } @DataProvider - public static Object[][] clientBuildersWithDirectTcp() { - return clientBuildersWithDirectAllConsistencies(Protocol.Tcp); + public static Object[][] clientBuildersWithDirectSession() { + return clientBuildersWithDirectSession(toArray(protocols)); } - @DataProvider - public static Object[][] clientBuildersWithDirectSession() { - return clientBuildersWithDirectSession(Protocol.Https, Protocol.Tcp); + static Protocol[] toArray(List protocols) { + return protocols.toArray(new Protocol[0]); } - + private static Object[][] clientBuildersWithDirectSession(Protocol... protocols) { - return clientBuildersWithDirect(new ArrayList(){{add(ConsistencyLevel.Session);}} , protocols); + return clientBuildersWithDirect(new ArrayList() {{ + add(ConsistencyLevel.Session); + }}, protocols); } private static Object[][] clientBuildersWithDirectAllConsistencies(Protocol... protocols) { - accountConsistency = parseConsistency(TestConfigurations.CONSISTENCY); logger.info("Max test consistency to use is [{}]", accountConsistency); - List testConsistencies = new ArrayList<>(); + return clientBuildersWithDirect(desiredConsistencies, protocols); + } + static List parseDesiredConsistencies(String consistencies) { + if (StringUtils.isEmpty(consistencies)) { + return null; + } + + try { + return objectMapper.readValue(consistencies, new TypeReference>() { + }); + } catch (Exception e) { + logger.error("Invalid consistency test desiredConsistencies [{}].", consistencies); + throw new IllegalStateException("Invalid configured test desiredConsistencies " + consistencies); + } + } + + static List allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { + List testConsistencies = new ArrayList<>(); switch (accountConsistency) { case Strong: testConsistencies.add(ConsistencyLevel.Strong); @@ -897,22 +926,20 @@ private static Object[][] clientBuildersWithDirectAllConsistencies(Protocol... p default: throw new IllegalStateException("Invalid configured test consistency " + accountConsistency); } - return clientBuildersWithDirect(testConsistencies, protocols); + return testConsistencies; } - - private static Object[][] clientBuildersWithDirect(List testConsistencies, Protocol... protocols) { - List preferredLocation = parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS); - boolean isMultiMasterEnabled = preferredLocation != null && accountConsistency == ConsistencyLevel.Session; + private static Object[][] clientBuildersWithDirect(List testConsistencies, Protocol... protocols) { + boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.Session; List builders = new ArrayList<>(); - builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, isMultiMasterEnabled, preferredLocation)); + builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, isMultiMasterEnabled, preferredLocations)); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> builders.add(createDirectRxDocumentClient(consistencyLevel, protocol, isMultiMasterEnabled, - preferredLocation))); + preferredLocations))); } builders.forEach(b -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java deleted file mode 100644 index da3b6b946d98c..0000000000000 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java +++ /dev/null @@ -1,1012 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.microsoft.azure.cosmosdb.CompositePath; -import com.microsoft.azure.cosmosdb.CompositePathSortOrder; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.Index; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.RetryOptions; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.internal.PathParser; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.FeedResponseListValidator; -import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import org.apache.commons.lang3.StringUtils; -import org.mockito.stubbing.Answer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import rx.Observable; -import rx.observers.TestSubscriber; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.spy; - -public class TestSuiteBase { - private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; - private static final ObjectMapper objectMapper = new ObjectMapper(); - protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); - protected static final int TIMEOUT = 40000; - protected static final int FEED_TIMEOUT = 40000; - protected static final int SETUP_TIMEOUT = 60000; - protected static final int SHUTDOWN_TIMEOUT = 12000; - - protected static final int SUITE_SETUP_TIMEOUT = 120000; - protected static final int SUITE_SHUTDOWN_TIMEOUT = 60000; - - protected static final int WAIT_REPLICA_CATCH_UP_IN_MILLIS = 4000; - - protected int subscriberValidationTimeout = TIMEOUT; - - protected static ConsistencyLevel accountConsistency; - - protected Builder clientBuilder; - - protected static Database SHARED_DATABASE; - protected static DocumentCollection SHARED_MULTI_PARTITION_COLLECTION; - protected static DocumentCollection SHARED_SINGLE_PARTITION_COLLECTION; - protected static DocumentCollection SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - protected static DocumentCollection SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES; - - - protected TestSuiteBase() { - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); - objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); - objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); - logger.debug("Initializing {} ...", this.getClass().getSimpleName()); - } - - @BeforeMethod(groups = { "simple", "long", "direct", "multi-master", "emulator" }) - public void beforeMethod(Method method) { - if (this.clientBuilder != null) { - logger.info("Starting {}::{} using {} {} mode with {} consistency", - method.getDeclaringClass().getSimpleName(), method.getName(), - this.clientBuilder.getConnectionPolicy().getConnectionMode(), - this.clientBuilder.getConfigs().getProtocol(), - this.clientBuilder.getDesiredConsistencyLevel()); - return; - } - logger.info("Starting {}::{}", method.getDeclaringClass().getSimpleName(), method.getName()); - } - - @AfterMethod(groups = { "simple", "long", "direct", "multi-master", "emulator" }) - public void afterMethod(Method m) { - Test t = m.getAnnotation(Test.class); - logger.info("Finished {}:{}.", m.getDeclaringClass().getSimpleName(), m.getName()); - } - - private static class DatabaseManagerImpl implements DatabaseForTest.DatabaseManager { - public static DatabaseManagerImpl getInstance(AsyncDocumentClient client) { - return new DatabaseManagerImpl(client); - } - - private final AsyncDocumentClient client; - - private DatabaseManagerImpl(AsyncDocumentClient client) { - this.client = client; - } - - @Override - public Observable> queryDatabases(SqlQuerySpec query) { - return client.queryDatabases(query, null); - } - - @Override - public Observable> createDatabase(Database databaseDefinition) { - return client.createDatabase(databaseDefinition, null); - } - - @Override - public Observable> deleteDatabase(String id) { - - return client.deleteDatabase("dbs/" + id, null); - } - } - - @BeforeSuite(groups = { "simple", "long", "direct", "multi-master", "emulator" }, timeOut = SUITE_SETUP_TIMEOUT) - public static void beforeSuite() { - logger.info("beforeSuite Started"); - AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); - try { - DatabaseForTest dbForTest = DatabaseForTest.create(DatabaseManagerImpl.getInstance(houseKeepingClient)); - SHARED_DATABASE = dbForTest.createdDatabase; - RequestOptions options = new RequestOptions(); - options.setOfferThroughput(10100); - SHARED_MULTI_PARTITION_COLLECTION = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinitionWithRangeRangeIndex(), options); - SHARED_SINGLE_PARTITION_COLLECTION = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinition(), null); - SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinitionSinglePartitionWithoutPartitionKey()); - SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes(), options); - } finally { - houseKeepingClient.close(); - } - } - - @AfterSuite(groups = { "simple", "long", "direct", "multi-master", "emulator" }, timeOut = SUITE_SHUTDOWN_TIMEOUT) - public static void afterSuite() { - logger.info("afterSuite Started"); - AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); - try { - safeDeleteDatabase(houseKeepingClient, SHARED_DATABASE); - DatabaseForTest.cleanupStaleTestDatabases(DatabaseManagerImpl.getInstance(houseKeepingClient)); - } finally { - safeClose(houseKeepingClient); - } - } - - protected static void truncateCollection(DocumentCollection collection) { - logger.info("Truncating collection {} ...", collection.getId()); - AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); - try { - List paths = collection.getPartitionKey().getPaths(); - - FeedOptions options = new FeedOptions(); - options.setMaxDegreeOfParallelism(-1); - options.setEnableCrossPartitionQuery(true); - options.setMaxItemCount(100); - - logger.info("Truncating collection {} documents ...", collection.getId()); - - houseKeepingClient.queryDocuments(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) - .flatMap(doc -> { - RequestOptions requestOptions = new RequestOptions(); - - if (paths != null && !paths.isEmpty()) { - List pkPath = PathParser.getPathParts(paths.get(0)); - Object propertyValue = doc.getObjectByPath(pkPath); - if (propertyValue == null) { - propertyValue = Undefined.Value(); - } - - requestOptions.setPartitionKey(new PartitionKey(propertyValue)); - } - - return houseKeepingClient.deleteDocument(doc.getSelfLink(), requestOptions); - }).toCompletable().await(); - - logger.info("Truncating collection {} triggers ...", collection.getId()); - - houseKeepingClient.queryTriggers(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) - .flatMap(trigger -> { - RequestOptions requestOptions = new RequestOptions(); - -// if (paths != null && !paths.isEmpty()) { -// Object propertyValue = trigger.getObjectByPath(PathParser.getPathParts(paths.get(0))); -// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); -// } - - return houseKeepingClient.deleteTrigger(trigger.getSelfLink(), requestOptions); - }).toCompletable().await(); - - logger.info("Truncating collection {} storedProcedures ...", collection.getId()); - - houseKeepingClient.queryStoredProcedures(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) - .flatMap(storedProcedure -> { - RequestOptions requestOptions = new RequestOptions(); - -// if (paths != null && !paths.isEmpty()) { -// Object propertyValue = storedProcedure.getObjectByPath(PathParser.getPathParts(paths.get(0))); -// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); -// } - - return houseKeepingClient.deleteStoredProcedure(storedProcedure.getSelfLink(), requestOptions); - }).toCompletable().await(); - - logger.info("Truncating collection {} udfs ...", collection.getId()); - - houseKeepingClient.queryUserDefinedFunctions(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) - .flatMap(udf -> { - RequestOptions requestOptions = new RequestOptions(); - -// if (paths != null && !paths.isEmpty()) { -// Object propertyValue = udf.getObjectByPath(PathParser.getPathParts(paths.get(0))); -// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); -// } - - return houseKeepingClient.deleteUserDefinedFunction(udf.getSelfLink(), requestOptions); - }).toCompletable().await(); - - } finally { - houseKeepingClient.close(); - } - - logger.info("Finished truncating collection {}.", collection.getId()); - } - - protected static void waitIfNeededForReplicasToCatchUp(AsyncDocumentClient.Builder clientBuilder) { - switch (clientBuilder.getDesiredConsistencyLevel()) { - case Eventual: - case ConsistentPrefix: - logger.info(" additional wait in Eventual mode so the replica catch up"); - // give times to replicas to catch up after a write - try { - TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); - } catch (Exception e) { - logger.error("unexpected failure", e); - } - - case Session: - case BoundedStaleness: - case Strong: - default: - break; - } - } - - private static DocumentCollection getCollectionDefinitionSinglePartitionWithoutPartitionKey() { - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); - - return collectionDefinition; - } - - - public static DocumentCollection createCollection(String databaseId, - DocumentCollection collection, - RequestOptions options) { - AsyncDocumentClient client = createGatewayHouseKeepingDocumentClient().build(); - try { - return client.createCollection("dbs/" + databaseId, collection, options).toBlocking().single().getResource(); - } finally { - client.close(); - } - } - - public static DocumentCollection createCollection(AsyncDocumentClient client, String databaseId, - DocumentCollection collection, RequestOptions options) { - return client.createCollection("dbs/" + databaseId, collection, options).toBlocking().single().getResource(); - } - - public static DocumentCollection createCollection(AsyncDocumentClient client, String databaseId, - DocumentCollection collection) { - return client.createCollection("dbs/" + databaseId, collection, null).toBlocking().single().getResource(); - } - - private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { - final String NUMBER_FIELD = "numberField"; - final String STRING_FIELD = "stringField"; - final String NUMBER_FIELD_2 = "numberField2"; - final String STRING_FIELD_2 = "stringField2"; - final String BOOL_FIELD = "boolField"; - final String NULL_FIELD = "nullField"; - final String OBJECT_FIELD = "objectField"; - final String ARRAY_FIELD = "arrayField"; - final String SHORT_STRING_FIELD = "shortStringField"; - final String MEDIUM_STRING_FIELD = "mediumStringField"; - final String LONG_STRING_FIELD = "longStringField"; - final String PARTITION_KEY = "pk"; - - DocumentCollection documentCollection = new DocumentCollection(); - - IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection> compositeIndexes = new ArrayList>(); - - //Simple - ArrayList compositeIndexSimple = new ArrayList(); - CompositePath compositePath1 = new CompositePath(); - compositePath1.setPath("/" + NUMBER_FIELD); - compositePath1.setOrder(CompositePathSortOrder.Ascending); - - CompositePath compositePath2 = new CompositePath(); - compositePath2.setPath("/" + STRING_FIELD); - compositePath2.setOrder(CompositePathSortOrder.Descending); - - compositeIndexSimple.add(compositePath1); - compositeIndexSimple.add(compositePath2); - - //Max Columns - ArrayList compositeIndexMaxColumns = new ArrayList(); - CompositePath compositePath3 = new CompositePath(); - compositePath3.setPath("/" + NUMBER_FIELD); - compositePath3.setOrder(CompositePathSortOrder.Descending); - - CompositePath compositePath4 = new CompositePath(); - compositePath4.setPath("/" + STRING_FIELD); - compositePath4.setOrder(CompositePathSortOrder.Ascending); - - CompositePath compositePath5 = new CompositePath(); - compositePath5.setPath("/" + NUMBER_FIELD_2); - compositePath5.setOrder(CompositePathSortOrder.Descending); - - CompositePath compositePath6 = new CompositePath(); - compositePath6.setPath("/" + STRING_FIELD_2); - compositePath6.setOrder(CompositePathSortOrder.Ascending); - - compositeIndexMaxColumns.add(compositePath3); - compositeIndexMaxColumns.add(compositePath4); - compositeIndexMaxColumns.add(compositePath5); - compositeIndexMaxColumns.add(compositePath6); - - //Primitive Values - ArrayList compositeIndexPrimitiveValues = new ArrayList(); - CompositePath compositePath7 = new CompositePath(); - compositePath7.setPath("/" + NUMBER_FIELD); - compositePath7.setOrder(CompositePathSortOrder.Descending); - - CompositePath compositePath8 = new CompositePath(); - compositePath8.setPath("/" + STRING_FIELD); - compositePath8.setOrder(CompositePathSortOrder.Ascending); - - CompositePath compositePath9 = new CompositePath(); - compositePath9.setPath("/" + BOOL_FIELD); - compositePath9.setOrder(CompositePathSortOrder.Descending); - - CompositePath compositePath10 = new CompositePath(); - compositePath10.setPath("/" + NULL_FIELD); - compositePath10.setOrder(CompositePathSortOrder.Ascending); - - compositeIndexPrimitiveValues.add(compositePath7); - compositeIndexPrimitiveValues.add(compositePath8); - compositeIndexPrimitiveValues.add(compositePath9); - compositeIndexPrimitiveValues.add(compositePath10); - - //Long Strings - ArrayList compositeIndexLongStrings = new ArrayList(); - CompositePath compositePath11 = new CompositePath(); - compositePath11.setPath("/" + STRING_FIELD); - - CompositePath compositePath12 = new CompositePath(); - compositePath12.setPath("/" + SHORT_STRING_FIELD); - - CompositePath compositePath13 = new CompositePath(); - compositePath13.setPath("/" + MEDIUM_STRING_FIELD); - - CompositePath compositePath14 = new CompositePath(); - compositePath14.setPath("/" + LONG_STRING_FIELD); - - compositeIndexLongStrings.add(compositePath11); - compositeIndexLongStrings.add(compositePath12); - compositeIndexLongStrings.add(compositePath13); - compositeIndexLongStrings.add(compositePath14); - - compositeIndexes.add(compositeIndexSimple); - compositeIndexes.add(compositeIndexMaxColumns); - compositeIndexes.add(compositeIndexPrimitiveValues); - compositeIndexes.add(compositeIndexLongStrings); - - indexingPolicy.setCompositeIndexes(compositeIndexes); - documentCollection.setIndexingPolicy(indexingPolicy); - - PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); - ArrayList partitionKeyPaths = new ArrayList(); - partitionKeyPaths.add("/" + PARTITION_KEY); - partitionKeyDefinition.setPaths(partitionKeyPaths); - documentCollection.setPartitionKey(partitionKeyDefinition); - - documentCollection.setId(UUID.randomUUID().toString()); - - return documentCollection; - } - - public static Document createDocument(AsyncDocumentClient client, String databaseId, String collectionId, Document document) { - return createDocument(client, databaseId, collectionId, document, null); - } - - public static Document createDocument(AsyncDocumentClient client, String databaseId, String collectionId, Document document, RequestOptions options) { - return client.createDocument(com.microsoft.azure.cosmosdb.rx.Utils.getCollectionNameLink(databaseId, collectionId), document, options, false).toBlocking().single().getResource(); - } - - public Observable> bulkInsert(AsyncDocumentClient client, - String collectionLink, - List documentDefinitionList, - int concurrencyLevel) { - ArrayList>> result = new ArrayList>>(documentDefinitionList.size()); - for (Document docDef : documentDefinitionList) { - result.add(client.createDocument(collectionLink, docDef, null, false)); - } - - return Observable.merge(result, concurrencyLevel); - } - - public Observable> bulkInsert(AsyncDocumentClient client, - String collectionLink, - List documentDefinitionList) { - return bulkInsert(client, collectionLink, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL); - } - - public List bulkInsertBlocking(AsyncDocumentClient client, - String collectionLink, - List documentDefinitionList) { - return bulkInsert(client, collectionLink, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) - .map(ResourceResponse::getResource) - .toList() - .toBlocking() - .single(); - } - - public static ConsistencyLevel getAccountDefaultConsistencyLevel(AsyncDocumentClient client) { - return client.getDatabaseAccount().toBlocking().single().getConsistencyPolicy().getDefaultConsistencyLevel(); - } - - public static User createUser(AsyncDocumentClient client, String databaseId, User user) { - return client.createUser("dbs/" + databaseId, user, null).toBlocking().single().getResource(); - } - - public static User safeCreateUser(AsyncDocumentClient client, String databaseId, User user) { - deleteUserIfExists(client, databaseId, user.getId()); - return createUser(client, databaseId, user); - } - - private static DocumentCollection safeCreateCollection(AsyncDocumentClient client, String databaseId, DocumentCollection collection, RequestOptions options) { - deleteCollectionIfExists(client, databaseId, collection.getId()); - return createCollection(client, databaseId, collection, options); - } - - public static String getCollectionLink(DocumentCollection collection) { - return collection.getSelfLink(); - } - - static protected DocumentCollection getCollectionDefinition() { - PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); - ArrayList paths = new ArrayList(); - paths.add("/mypk"); - partitionKeyDef.setPaths(paths); - - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); - collectionDefinition.setPartitionKey(partitionKeyDef); - - return collectionDefinition; - } - - static protected DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { - PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); - ArrayList paths = new ArrayList<>(); - paths.add("/mypk"); - partitionKeyDef.setPaths(paths); - IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection includedPaths = new ArrayList<>(); - IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); - Collection indexes = new ArrayList<>(); - Index stringIndex = Index.Range(DataType.String); - stringIndex.set("precision", -1); - indexes.add(stringIndex); - - Index numberIndex = Index.Range(DataType.Number); - numberIndex.set("precision", -1); - indexes.add(numberIndex); - includedPath.setIndexes(indexes); - includedPaths.add(includedPath); - indexingPolicy.setIncludedPaths(includedPaths); - - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setIndexingPolicy(indexingPolicy); - collectionDefinition.setId(UUID.randomUUID().toString()); - collectionDefinition.setPartitionKey(partitionKeyDef); - - return collectionDefinition; - } - - public static void deleteCollectionIfExists(AsyncDocumentClient client, String databaseId, String collectionId) { - List res = client.queryCollections("dbs/" + databaseId, - String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null).toBlocking().single() - .getResults(); - if (!res.isEmpty()) { - deleteCollection(client, com.microsoft.azure.cosmosdb.rx.Utils.getCollectionNameLink(databaseId, collectionId)); - } - } - - public static void deleteCollection(AsyncDocumentClient client, String collectionLink) { - client.deleteCollection(collectionLink, null).toBlocking().single(); - } - - public static void deleteDocumentIfExists(AsyncDocumentClient client, String databaseId, String collectionId, String docId) { - FeedOptions options = new FeedOptions(); - options.setPartitionKey(new PartitionKey(docId)); - List res = client - .queryDocuments(com.microsoft.azure.cosmosdb.rx.Utils.getCollectionNameLink(databaseId, collectionId), String.format("SELECT * FROM root r where r.id = '%s'", docId), options) - .toBlocking().single().getResults(); - if (!res.isEmpty()) { - deleteDocument(client, com.microsoft.azure.cosmosdb.rx.Utils.getDocumentNameLink(databaseId, collectionId, docId)); - } - } - - public static void safeDeleteDocument(AsyncDocumentClient client, String documentLink, RequestOptions options) { - if (client != null && documentLink != null) { - try { - client.deleteDocument(documentLink, options).toBlocking().single(); - } catch (Exception e) { - DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e, DocumentClientException.class); - if (dce == null || dce.getStatusCode() != 404) { - throw e; - } - } - } - } - - public static void deleteDocument(AsyncDocumentClient client, String documentLink) { - client.deleteDocument(documentLink, null).toBlocking().single(); - } - - public static void deleteUserIfExists(AsyncDocumentClient client, String databaseId, String userId) { - List res = client - .queryUsers("dbs/" + databaseId, String.format("SELECT * FROM root r where r.id = '%s'", userId), null) - .toBlocking().single().getResults(); - if (!res.isEmpty()) { - deleteUser(client, com.microsoft.azure.cosmosdb.rx.Utils.getUserNameLink(databaseId, userId)); - } - } - - public static void deleteUser(AsyncDocumentClient client, String userLink) { - client.deleteUser(userLink, null).toBlocking().single(); - } - - public static String getDatabaseLink(Database database) { - return database.getSelfLink(); - } - - static private Database safeCreateDatabase(AsyncDocumentClient client, Database database) { - safeDeleteDatabase(client, database.getId()); - return createDatabase(client, database); - } - - static protected Database createDatabase(AsyncDocumentClient client, Database database) { - Observable> databaseObservable = client.createDatabase(database, null); - return databaseObservable.toBlocking().single().getResource(); - } - - static protected Database createDatabase(AsyncDocumentClient client, String databaseId) { - Database databaseDefinition = new Database(); - databaseDefinition.setId(databaseId); - return createDatabase(client, databaseDefinition); - } - - static protected Database createDatabaseIfNotExists(AsyncDocumentClient client, String databaseId) { - return client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null).flatMap(p -> Observable.from(p.getResults())).switchIfEmpty( - Observable.defer(() -> { - - Database databaseDefinition = new Database(); - databaseDefinition.setId(databaseId); - - return client.createDatabase(databaseDefinition, null).map(ResourceResponse::getResource); - }) - ).toBlocking().single(); - } - - static protected void safeDeleteDatabase(AsyncDocumentClient client, Database database) { - if (database != null) { - safeDeleteDatabase(client, database.getId()); - } - } - - static protected void safeDeleteDatabase(AsyncDocumentClient client, String databaseId) { - if (client != null) { - try { - client.deleteDatabase(com.microsoft.azure.cosmosdb.rx.Utils.getDatabaseNameLink(databaseId), null).toBlocking().single(); - } catch (Exception e) { - } - } - } - - static protected void safeDeleteAllCollections(AsyncDocumentClient client, Database database) { - if (database != null) { - List collections = client.readCollections(database.getSelfLink(), null) - .flatMap(p -> Observable.from(p.getResults())) - .toList() - .toBlocking() - .single(); - - for(DocumentCollection collection: collections) { - client.deleteCollection(collection.getSelfLink(), null).toBlocking().single().getResource(); - } - } - } - - static protected void safeDeleteCollection(AsyncDocumentClient client, DocumentCollection collection) { - if (client != null && collection != null) { - try { - client.deleteCollection(collection.getSelfLink(), null).toBlocking().single(); - } catch (Exception e) { - } - } - } - - static protected void safeDeleteCollection(AsyncDocumentClient client, String databaseId, String collectionId) { - if (client != null && databaseId != null && collectionId != null) { - try { - client.deleteCollection("/dbs/" + databaseId + "/colls/" + collectionId, null).toBlocking().single(); - } catch (Exception e) { - } - } - } - - static protected void safeClose(AsyncDocumentClient client) { - if (client != null) { - try { - client.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void validateSuccess(Observable> observable, - ResourceResponseValidator validator) { - validateSuccess(observable, validator, subscriberValidationTimeout); - } - - public static void validateSuccess(Observable> observable, - ResourceResponseValidator validator, long timeout) { - - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - - observable.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); - testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); - } - - public void validateFailure(Observable> observable, - FailureValidator validator) { - validateFailure(observable, validator, subscriberValidationTimeout); - } - - public static void validateFailure(Observable> observable, - FailureValidator validator, long timeout) { - - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - - observable.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); - } - - public void validateQuerySuccess(Observable> observable, - FeedResponseListValidator validator) { - validateQuerySuccess(observable, validator, subscriberValidationTimeout); - } - - public static void validateQuerySuccess(Observable> observable, - FeedResponseListValidator validator, long timeout) { - - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - - observable.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); - validator.validate(testSubscriber.getOnNextEvents()); - } - - public void validateQueryFailure(Observable> observable, - FailureValidator validator) { - validateQueryFailure(observable, validator, subscriberValidationTimeout); - } - - public static void validateQueryFailure(Observable> observable, - FailureValidator validator, long timeout) { - - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - - observable.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); - } - - @DataProvider - public static Object[][] clientBuilders() { - return new Object[][] { { createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null) } }; - } - - @DataProvider - public static Object[][] clientBuildersWithSessionConsistency() { - return new Object[][] { - { createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null) }, - { createDirectRxDocumentClient(ConsistencyLevel.Session, Protocol.Https, false, null) }, - { createDirectRxDocumentClient(ConsistencyLevel.Session, Protocol.Tcp, false, null) } - }; - } - - private static ConsistencyLevel parseConsistency(String consistency) { - if (consistency != null) { - for (ConsistencyLevel consistencyLevel : ConsistencyLevel.values()) { - if (consistencyLevel.name().toLowerCase().equals(consistency.toLowerCase())) { - return consistencyLevel; - } - } - } - - logger.error("Invalid configured test consistency [{}].", consistency); - throw new IllegalStateException("Invalid configured test consistency " + consistency); - } - - private static List parsePreferredLocation(String preferredLocations) { - if (StringUtils.isEmpty(preferredLocations)) { - return null; - } - - try { - return objectMapper.readValue(preferredLocations, new TypeReference>(){}); - } catch (Exception e) { - logger.error("Invalid configured test preferredLocations [{}].", preferredLocations); - throw new IllegalStateException("Invalid configured test preferredLocations " + preferredLocations); - } - } - - @DataProvider - public static Object[][] simpleClientBuildersWithDirect() { - return simpleClientBuildersWithDirect(Protocol.Https, Protocol.Tcp); - } - - @DataProvider - public static Object[][] simpleClientBuildersWithDirectHttps() { - return simpleClientBuildersWithDirect(Protocol.Https); - } - - @DataProvider - public static Object[][] simpleClientBuildersWithDirectTcp() { - return simpleClientBuildersWithDirect(Protocol.Tcp); - } - - private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) { - - accountConsistency = parseConsistency(TestConfigurations.CONSISTENCY); - logger.info("Max test consistency to use is [{}]", accountConsistency); - List testConsistencies = new ArrayList<>(); - - switch (accountConsistency) { - case Strong: - case BoundedStaleness: - case Session: - case ConsistentPrefix: - case Eventual: - testConsistencies.add(ConsistencyLevel.Eventual); - break; - default: - throw new IllegalStateException("Invalid configured test consistency " + accountConsistency); - } - - List preferredLocation = parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS); - boolean isMultiMasterEnabled = preferredLocation != null && accountConsistency == ConsistencyLevel.Session; - - List builders = new ArrayList<>(); - builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null)); - - for (Protocol protocol : protocols) { - testConsistencies.forEach(consistencyLevel -> builders.add(createDirectRxDocumentClient(consistencyLevel, - protocol, - isMultiMasterEnabled, - preferredLocation))); - } - - builders.forEach(b -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", - b.getConnectionPolicy().getConnectionMode(), - b.getDesiredConsistencyLevel(), - b.getConfigs().getProtocol() - )); - - return builders.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); - } - - @DataProvider - public static Object[][] clientBuildersWithDirect() { - return clientBuildersWithDirectAllConsistencies(Protocol.Https, Protocol.Tcp); - } - - @DataProvider - public static Object[][] clientBuildersWithDirectHttps() { - return clientBuildersWithDirectAllConsistencies(Protocol.Https); - } - - @DataProvider - public static Object[][] clientBuildersWithDirectTcp() { - return clientBuildersWithDirectAllConsistencies(Protocol.Tcp); - } - - @DataProvider - public static Object[][] clientBuildersWithDirectSession() { - return clientBuildersWithDirectSession(Protocol.Https, Protocol.Tcp); - } - - private static Object[][] clientBuildersWithDirectSession(Protocol... protocols) { - return clientBuildersWithDirect(new ArrayList(){{add(ConsistencyLevel.Session);}} , protocols); - } - - private static Object[][] clientBuildersWithDirectAllConsistencies(Protocol... protocols) { - accountConsistency = parseConsistency(TestConfigurations.CONSISTENCY); - logger.info("Max test consistency to use is [{}]", accountConsistency); - List testConsistencies = new ArrayList<>(); - - switch (accountConsistency) { - case Strong: - testConsistencies.add(ConsistencyLevel.Strong); - case BoundedStaleness: - testConsistencies.add(ConsistencyLevel.BoundedStaleness); - case Session: - testConsistencies.add(ConsistencyLevel.Session); - case ConsistentPrefix: - testConsistencies.add(ConsistencyLevel.ConsistentPrefix); - case Eventual: - testConsistencies.add(ConsistencyLevel.Eventual); - break; - default: - throw new IllegalStateException("Invalid configured test consistency " + accountConsistency); - } - return clientBuildersWithDirect(testConsistencies, protocols); - } - - private static Object[][] clientBuildersWithDirect(List testConsistencies, Protocol... protocols) { - - List preferredLocation = parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS); - boolean isMultiMasterEnabled = preferredLocation != null && accountConsistency == ConsistencyLevel.Session; - - List builders = new ArrayList<>(); - builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, isMultiMasterEnabled, preferredLocation)); - - for (Protocol protocol : protocols) { - testConsistencies.forEach(consistencyLevel -> builders.add(createDirectRxDocumentClient(consistencyLevel, - protocol, - isMultiMasterEnabled, - preferredLocation))); - } - - builders.forEach(b -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", - b.getConnectionPolicy().getConnectionMode(), - b.getDesiredConsistencyLevel(), - b.getConfigs().getProtocol() - )); - - return builders.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); - } - - static protected AsyncDocumentClient.Builder createGatewayHouseKeepingDocumentClient() { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); - RetryOptions options = new RetryOptions(); - options.setMaxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); - connectionPolicy.setRetryOptions(options); - return new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session); - } - - static protected AsyncDocumentClient.Builder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List preferredLocations) { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); - connectionPolicy.setUsingMultipleWriteLocations(multiMasterEnabled); - connectionPolicy.setPreferredLocations(preferredLocations); - return new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(consistencyLevel); - } - - static protected AsyncDocumentClient.Builder createGatewayRxDocumentClient() { - return createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null); - } - - static protected AsyncDocumentClient.Builder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, - Protocol protocol, - boolean multiMasterEnabled, - List preferredLocations) { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); - - if (preferredLocations != null) { - connectionPolicy.setPreferredLocations(preferredLocations); - } - - if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.Session) { - connectionPolicy.setUsingMultipleWriteLocations(true); - } - - Configs configs = spy(new Configs()); - doAnswer((Answer) invocation -> protocol).when(configs).getProtocol(); - - return new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(consistencyLevel) - .withConfigs(configs); - } - - protected int expectedNumberOfPages(int totalExpectedResult, int maxPageSize) { - return Math.max((totalExpectedResult + maxPageSize - 1 ) / maxPageSize, 1); - } - - @DataProvider(name = "queryMetricsArgProvider") - public Object[][] queryMetricsArgProvider() { - return new Object[][]{ - {true}, - {false}, - }; - } - - public static class VerboseTestSubscriber extends TestSubscriber { - @Override - public void assertNoErrors() { - List onErrorEvents = getOnErrorEvents(); - StringBuilder errorMessageBuilder = new StringBuilder(); - if (!onErrorEvents.isEmpty()) { - for(Throwable throwable : onErrorEvents) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - throwable.printStackTrace(pw); - String sStackTrace = sw.toString(); // stack trace as a string - errorMessageBuilder.append(sStackTrace); - } - - AssertionError ae = new AssertionError(errorMessageBuilder.toString()); - throw ae; - } - } - } -} From b4d49f47986ff0910665d85f8c3da60b6fe77cd1 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Fri, 31 May 2019 22:19:11 -0700 Subject: [PATCH 21/85] fixed sync --- .../cosmosdb/benchmark/AsyncBenchmark.java | 28 +++++++++++-------- .../ReadMyWritesConsistencyTest.java | 2 +- .../azure/cosmosdb/DatabaseForTest.java | 2 +- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java index 8a62428a9bf50..6905b29cd27be 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java @@ -51,10 +51,9 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; abstract class AsyncBenchmark { private final MetricRegistry metricsRegistry = new MetricRegistry(); @@ -196,10 +195,9 @@ void run() throws Exception { long startTime = System.currentTimeMillis(); - int maxNumberOfOperations = configuration.getNumberOfOperations(); - CountDownLatch terminationLatch = new CountDownLatch(1); - AtomicInteger count = new AtomicInteger(0); - for (long i = 0; (maxNumberOfOperations < 0 ? true : i < maxNumberOfOperations) && terminationLatch.getCount() > 0; i++) { + AtomicLong count = new AtomicLong(0); + long i; + for ( i = 0; shouldContinue(startTime, i); i++) { Subscriber subs = new Subscriber() { @@ -213,8 +211,9 @@ public void onCompleted() { concurrencyControlSemaphore.release(); AsyncBenchmark.this.onSuccess(); - if (!shouldContinue(startTime, count.incrementAndGet())) { - terminationLatch.countDown(); + synchronized (count) { + count.incrementAndGet(); + count.notify(); } } @@ -225,10 +224,10 @@ public void onError(Throwable e) { e.getMessage(), Thread.currentThread().getName(), e); concurrencyControlSemaphore.release(); AsyncBenchmark.this.onError(e); - count.incrementAndGet(); - if (!shouldContinue(startTime, count.incrementAndGet())) { - terminationLatch.countDown(); + synchronized (count) { + count.incrementAndGet(); + count.notify(); } } @@ -240,7 +239,12 @@ public void onNext(T value) { performWorkload(subs, i); } - terminationLatch.await(); + synchronized (count) { + while (count.get() < i) { + count.wait(); + } + } + long endTime = System.currentTimeMillis(); logger.info("[{}] operations performed in [{}] seconds.", configuration.getNumberOfOperations(), (int) ((endTime - startTime) / 1000)); diff --git a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java index 88f90813b37de..8970087944837 100644 --- a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java @@ -59,7 +59,7 @@ public class ReadMyWritesConsistencyTest { private final static Logger logger = LoggerFactory.getLogger(ReadMyWritesConsistencyTest.class); private final int initialCollectionThroughput = 10_000; private final int newCollectionThroughput = 100_000; - private final int delayForInitiationCollectionScaleUpInSeconds = 120; + private final int delayForInitiationCollectionScaleUpInSeconds = 60; private final Duration defaultMaxRunningTimeInSeconds = Duration.ofMinutes(45); private final String maxRunningTime = diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/DatabaseForTest.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/DatabaseForTest.java index 1e646d58e6eb3..5711d2fa817e7 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/DatabaseForTest.java +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/DatabaseForTest.java @@ -39,7 +39,7 @@ public class DatabaseForTest { private static Logger logger = LoggerFactory.getLogger(DatabaseForTest.class); public static final String SHARED_DB_ID_PREFIX = "RxJava.SDKTest.SharedDatabase"; - private static final Duration CLEANUP_THRESHOLD_DURATION = Duration.ofHours(1); + private static final Duration CLEANUP_THRESHOLD_DURATION = Duration.ofHours(2); private static final String DELIMITER = "_"; private static DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss"); From c9895b4a5f9d964317f24040bb514e09bf06fc87 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Sat, 1 Jun 2019 04:02:56 -0700 Subject: [PATCH 22/85] test fix --- .../azure/cosmosdb/rx/CollectionCrudTest.java | 4 ++-- .../microsoft/azure/cosmosdb/rx/TestSuiteBase.java | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java index 0d1758dee2017..1620e7c47a7df 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java @@ -309,8 +309,8 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { assertThat(readDocument.get("name").equals(newDocument.get("name"))).isTrue(); } finally { safeDeleteDatabase(client1, dbId); - safeClose(client1); - safeClose(client2); + safeCloseAsync(client1); + safeCloseAsync(client2); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java index ef23f4e6c4232..3df802951f76e 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java @@ -694,6 +694,18 @@ static protected void safeDeleteCollection(AsyncDocumentClient client, String da } } + static protected void safeCloseAsync(AsyncDocumentClient client) { + if (client != null) { + new Thread(() -> { + try { + client.close(); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + } + } + static protected void safeClose(AsyncDocumentClient client) { if (client != null) { try { From cc2e76246a839c61fba50a76886bed5c32a37505 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Sun, 2 Jun 2019 10:25:04 -0700 Subject: [PATCH 23/85] udate test --- .../com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java index 1620e7c47a7df..0d1758dee2017 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java @@ -309,8 +309,8 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { assertThat(readDocument.get("name").equals(newDocument.get("name"))).isTrue(); } finally { safeDeleteDatabase(client1, dbId); - safeCloseAsync(client1); - safeCloseAsync(client2); + safeClose(client1); + safeClose(client2); } } From feba6386e0ab6f39f49a1215a2ecbca2f3ec1f25 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Sun, 2 Jun 2019 10:29:09 -0700 Subject: [PATCH 24/85] cleanup --- .../main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java | 1 - 1 file changed, 1 deletion(-) diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java index ebe1ab5c6554c..47310b975b1fb 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java @@ -50,5 +50,4 @@ public boolean retryMethod(ITestResult result) { return true; } - } From 631d1e3037f12d5bfafe867075041982c16b5433 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Tue, 28 May 2019 22:17:23 -0700 Subject: [PATCH 25/85] improve test timeout --- .../internal/directconnectivity/RntbdTransportClientTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RntbdTransportClientTest.java b/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RntbdTransportClientTest.java index b2ab400ad3841..44ec29a004e1f 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RntbdTransportClientTest.java +++ b/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RntbdTransportClientTest.java @@ -692,7 +692,7 @@ public void verifyRequestFailures( RntbdResponse response ) { final UserAgentContainer userAgent = new UserAgentContainer(); - final Duration timeout = Duration.ofMillis(100); + final Duration timeout = Duration.ofMillis(1000); try (final RntbdTransportClient client = getRntbdTransportClientUnderTest(userAgent, timeout, response)) { From 17351d2b0beaf1cf29cbe253faf9852042004a35 Mon Sep 17 00:00:00 2001 From: mbhaskar Date: Mon, 3 Jun 2019 16:39:40 -0700 Subject: [PATCH 26/85] V3 cosmositem refactoring (#120) * Cosmos Item refactoring #106 fixes #106 --- .../azure/cosmos/examples/BasicDemo.java | 14 +- .../microsoft/azure/cosmos/CosmosClient.java | 3 + .../azure/cosmos/CosmosContainer.java | 79 ++++++++--- .../microsoft/azure/cosmos/CosmosItem.java | 134 ++++++------------ .../cosmos/CosmosItemRequestOptions.java | 10 +- .../azure/cosmos/CosmosItemResponse.java | 25 ++-- .../azure/cosmos/CosmosItemSettings.java | 75 ++++++++++ .../azure/cosmos/CosmosItemCrudTest.java | 35 +++-- .../azure/cosmos/CosmosResponseValidator.java | 2 +- 9 files changed, 229 insertions(+), 148 deletions(-) create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java b/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java index 1fa342e878e82..dd21168dca01b 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java +++ b/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java @@ -22,6 +22,8 @@ */ package com.microsoft.azure.cosmos.examples; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; @@ -29,8 +31,6 @@ import com.microsoft.azure.cosmos.CosmosContainer; import com.microsoft.azure.cosmos.CosmosContainerSettings; import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; import com.microsoft.azure.cosmos.CosmosItemResponse; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -106,10 +106,10 @@ private void createAndReplaceItem() { log("Couldn't create items due to above exceptions"); } if(cosmosItem != null) { - cosmosItem.set("new property", "value"); + replaceObject.setName("new name test3"); //Replace the item and wait for completion - cosmosItem.replace(cosmosItem, new CosmosItemRequestOptions(cosmosItem.get("country"))).block(); + cosmosItem.replace(replaceObject).block(); } } @@ -130,7 +130,7 @@ private void queryItems(){ FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); options.setMaxDegreeOfParallelism(2); - Flux> queryFlux = container.queryItems(query, options); + Flux> queryFlux = container.queryItems(query, options); queryFlux.publishOn(Schedulers.elastic()).subscribe(cosmosItemFeedResponse -> {}, throwable -> {}, @@ -155,8 +155,8 @@ private void queryWithContinuationToken(){ String continuation = null; do{ options.setRequestContinuation(continuation); - Flux> queryFlux = container.queryItems(query, options); - FeedResponse page = queryFlux.blockFirst(); + Flux> queryFlux = container.queryItems(query, options); + FeedResponse page = queryFlux.blockFirst(); assert page != null; log(page.getResults()); continuation = page.getResponseContinuation(); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java index 3e81053a1d214..365dbdc9c53ac 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java @@ -135,6 +135,9 @@ private Mono createDatabaseIfNotExistsInternal(CosmosDat */ public Mono createDatabase(CosmosDatabaseSettings databaseSettings, CosmosDatabaseRequestOptions options) { + if (options == null) { + options = new CosmosDatabaseRequestOptions(); + } Database wrappedDatabase = new Database(); wrappedDatabase.setId(databaseSettings.getId()); return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(asyncDocumentClient.createDatabase(wrappedDatabase, options.toRequestOptions()).map(databaseResourceResponse -> diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java index 3d9a4ce3db4e9..15df971cd8f14 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java @@ -25,6 +25,7 @@ import com.microsoft.azure.cosmosdb.BridgeInternal; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.SqlQuerySpec; import com.microsoft.azure.cosmosdb.StoredProcedure; import com.microsoft.azure.cosmosdb.Trigger; @@ -67,9 +68,12 @@ public Mono read() { * * @return an {@link Mono} containing the single cossmos container response with the read container or an error. */ - public Mono read(CosmosContainerRequestOptions requestOptions) { + public Mono read(CosmosContainerRequestOptions options) { + if (options == null) { + options = new CosmosContainerRequestOptions(); + } return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(database.getDocClientWrapper().readCollection(getLink(), - requestOptions.toRequestOptions()) + options.toRequestOptions()) .map(response -> new CosmosContainerResponse(response, database)).toSingle())); } @@ -80,13 +84,16 @@ public Mono read(CosmosContainerRequestOptions requestO * The {@link Mono} upon successful completion will contain a single cossmos container response for the deleted database. * In case of failure the {@link Mono} will error. * - * @param requestOptions the request options. + * @param options the request options. * @return an {@link Mono} containing the single cossmos container response for the deleted database or an error. */ - public Mono delete(CosmosContainerRequestOptions requestOptions) { + public Mono delete(CosmosContainerRequestOptions options) { + if (options == null) { + options = new CosmosContainerRequestOptions(); + } return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() - .deleteCollection(getLink(),requestOptions.toRequestOptions()) + .deleteCollection(getLink(), options.toRequestOptions()) .map(response -> new CosmosContainerResponse(response, database)) .toSingle())); } @@ -112,18 +119,18 @@ public Mono delete() { * In case of failure the {@link Mono} will error. * * @param containerSettings the item container settings - * @param requestOptions the cosmos container request options. + * @param options the cosmos container request options. * @return an {@link Mono} containing the single cossmos container response with the replaced document container or an error. */ public Mono replace(CosmosContainerSettings containerSettings, - CosmosContainerRequestOptions requestOptions) { + CosmosContainerRequestOptions options) { validateResource(containerSettings); - if(requestOptions == null){ - requestOptions = new CosmosContainerRequestOptions(); + if(options == null){ + options = new CosmosContainerRequestOptions(); } return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() - .replaceCollection(containerSettings.getV2Collection(),requestOptions.toRequestOptions()) + .replaceCollection(containerSettings.getV2Collection(),options.toRequestOptions()) .map(response -> new CosmosContainerResponse(response, database)) .toSingle())); } @@ -171,10 +178,19 @@ public Mono createItem(Object item, Object partitionKey){ * @return an {@link Mono} containing the single resource response with the created cosmos item or an error. */ public Mono createItem(Object item, CosmosItemRequestOptions options) { + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() - .createDocument(getLink(),CosmosItem.fromObject(item),options.toRequestOptions(), true) - .map(response -> new CosmosItemResponse(response, this)) + .createDocument(getLink(), + CosmosItemSettings.fromObject(item), + requestOptions, + true) + .map(response -> new CosmosItemResponse(response, + requestOptions.getPartitionKey(), + this)) .toSingle())); } @@ -190,13 +206,20 @@ public Mono createItem(Object item, CosmosItemRequestOptions * @return an {@link Mono} containing the single resource response with the upserted document or an error. */ public Mono upsertItem(Object item, CosmosItemRequestOptions options){ + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.getDatabase() .getDocClientWrapper() .upsertDocument(this.getLink(), item, options.toRequestOptions(), true) - .map(response -> new CosmosItemResponse(response, this)) + .map(response -> new CosmosItemResponse(response, + requestOptions.getPartitionKey(), + this)) .toSingle())); } @@ -209,7 +232,7 @@ public Mono upsertItem(Object item, CosmosItemRequestOptions * * @return an {@link Flux} containing one or several feed response pages of the read cosmos items or an error. */ - public Flux> listItems() { + public Flux> listItems() { return listItems(new FeedOptions()); } @@ -223,12 +246,12 @@ public Flux> listItems() { * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the read cosmos items or an error. */ - public Flux> listItems(FeedOptions options) { + public Flux> listItems(FeedOptions options) { return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(getDatabase().getDocClientWrapper() .readDocuments(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosItem.getFromV2Results(response.getResults(),this), - response.getResponseHeaders())))); + .map(response-> BridgeInternal.createFeedResponse(CosmosItemSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); } /** @@ -242,7 +265,7 @@ public Flux> listItems(FeedOptions options) { * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. */ - public Flux> queryItems(String query, FeedOptions options){ + public Flux> queryItems(String query, FeedOptions options){ return queryItems(new SqlQuerySpec(query), options); } @@ -257,14 +280,15 @@ public Flux> queryItems(String query, FeedOptions optio * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. */ - public Flux> queryItems(SqlQuerySpec querySpec, FeedOptions options){ + public Flux> queryItems(SqlQuerySpec querySpec, FeedOptions options){ return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(getDatabase() .getDocClientWrapper() .queryDocuments(getLink(), querySpec, options) .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( - CosmosItem.getFromV2Results(response.getResults(), this), - response.getResponseHeaders(), response.getQueryMetrics())))); + CosmosItemSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders(), + response.getQueryMetrics())))); } /** @@ -272,8 +296,8 @@ public Flux> queryItems(SqlQuerySpec querySpec, FeedOpt * @param id id of the item * @return a cosmos item */ - public CosmosItem getItem(String id){ - return new CosmosItem(id, this); + public CosmosItem getItem(String id, Object partitionKey){ + return new CosmosItem(id, partitionKey, this); } /* CosmosStoredProcedure operations */ @@ -292,6 +316,9 @@ public CosmosItem getItem(String id){ */ public Mono createStoredProcedure(CosmosStoredProcedureSettings settings, CosmosStoredProcedureRequestOptions options){ + if(options == null){ + options = new CosmosStoredProcedureRequestOptions(); + } StoredProcedure sProc = new StoredProcedure(); sProc.setId(settings.getId()); sProc.setBody(settings.getBody()); @@ -378,6 +405,9 @@ public Mono createUserDefinedFunction(CosmosU UserDefinedFunction udf = new UserDefinedFunction(); udf.setId(settings.getId()); udf.setBody(settings.getBody()); + if(options == null){ + options = new CosmosRequestOptions(); + } return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() .createUserDefinedFunction(getLink(), udf, options.toRequestOptions()) @@ -452,6 +482,9 @@ public Flux> queryUserDefinedFun public Mono createTrigger(CosmosTriggerSettings settings, CosmosRequestOptions options){ Trigger trigger = new Trigger(settings.toJson()); + if(options == null){ + options = new CosmosRequestOptions(); + } return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() .createTrigger(getLink(), trigger,options.toRequestOptions()) diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java index 021fc350ad29c..fca34f5d8480c 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java @@ -22,45 +22,23 @@ */ package com.microsoft.azure.cosmos; -import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.internal.Paths; -import com.microsoft.azure.cosmosdb.internal.Utils; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Mono; -import java.io.IOException; -import java.util.List; -import java.util.stream.Collectors; - -public class CosmosItem extends Resource { - +public class CosmosItem extends CosmosResource{ + private Object partitionKey; private CosmosContainer container; - final static ObjectMapper mapper = Utils.getSimpleObjectMapper(); - CosmosItem(String json, CosmosContainer container) { - super(json); + CosmosItem(String id, Object partitionKey, CosmosContainer container) { + super(id); + this.partitionKey = partitionKey; this.container = container; } - /** - * Initialize a item object. - */ - public CosmosItem() { - super(); - } - - /** - * Initialize a CosmosItem object from json string. - * - * @param jsonString the json string that represents the document object. - */ - public CosmosItem(String jsonString) { - super(jsonString); - } - /** * Reads an item. * @@ -70,7 +48,7 @@ public CosmosItem(String jsonString) { * * @return an {@link Mono} containing the cosmos item response with the read item or an error */ - public Mono read(Object partitionKey) { + public Mono read() { return read(new CosmosItemRequestOptions(partitionKey)); } @@ -81,13 +59,18 @@ public Mono read(Object partitionKey) { * The {@link Mono} upon successful completion will contain a cosmos item response with the read item * In case of failure the {@link Mono} will error. * - * @param requestOptions the request comosItemRequestOptions + * @param options the request comosItemRequestOptions * @return an {@link Mono} containing the cosmos item response with the read item or an error */ - public Mono read(CosmosItemRequestOptions requestOptions) { + public Mono read(CosmosItemRequestOptions options) { + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase().getDocClientWrapper() - .readDocument(getLink(), requestOptions.toRequestOptions()) - .map(response -> new CosmosItemResponse(response, container)).toSingle())); + .readDocument(getLink(), requestOptions) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) + .toSingle())); } /** @@ -98,10 +81,9 @@ public Mono read(CosmosItemRequestOptions requestOptions) { * In case of failure the {@link Mono} will error. * * @param item the item to replace (containing the document id). - * @param partitionKey the partition key * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. */ - public Mono replace(Object item, Object partitionKey){ + public Mono replace(Object item){ return replace(item, new CosmosItemRequestOptions(partitionKey)); } @@ -113,27 +95,31 @@ public Mono replace(Object item, Object partitionKey){ * In case of failure the {@link Mono} will error. * * @param item the item to replace (containing the document id). - * @param requestOptions the request comosItemRequestOptions + * @param options the request comosItemRequestOptions * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. */ - public Mono replace(Object item, CosmosItemRequestOptions requestOptions){ - Document doc = CosmosItem.fromObject(item); + public Mono replace(Object item, CosmosItemRequestOptions options){ + Document doc = CosmosItemSettings.fromObject(item); + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase() .getDocClientWrapper() - .replaceDocument(doc, requestOptions.toRequestOptions()) - .map(response -> new CosmosItemResponse(response, container)).toSingle())); + .replaceDocument(getLink(), doc, requestOptions) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) + .toSingle())); } - + /** * Deletes the item. * * After subscription the operation will be performed. * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. * In case of failure the {@link Mono} will error. - * @param partitionKey * @return an {@link Mono} containing the cosmos item resource response. */ - public Mono delete(Object partitionKey) { + public Mono delete() { return delete(new CosmosItemRequestOptions(partitionKey)); } @@ -148,62 +134,30 @@ public Mono delete(Object partitionKey) { * @return an {@link Mono} containing the cosmos item resource response. */ public Mono delete(CosmosItemRequestOptions options){ + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(container.getDatabase() - .getDocClientWrapper() - .deleteDocument(getLink(),options.toRequestOptions()) - .map(response -> new CosmosItemResponse(response, container)) - .toSingle())); - } - - /** - * Initialize an CosmosItem object from json string. - * - * @param jsonString the json string that represents the item object. - * @param objectMapper the custom object mapper - */ - public CosmosItem(String jsonString, ObjectMapper objectMapper) { - super(jsonString, objectMapper); + .getDocClientWrapper() + .deleteDocument(getLink(), requestOptions) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) + .toSingle())); } void setContainer(CosmosContainer container) { this.container = container; } - /** - * fromObject retuns Document for compatibility with V2 sdk - * @param cosmosItem - * @return - */ - static Document fromObject(Object cosmosItem) { - Document typedItem; - if (cosmosItem instanceof CosmosItem) { - typedItem = new Document(((CosmosItem)cosmosItem).toJson()); - } else { - try { - return new Document(CosmosItem.mapper.writeValueAsString(cosmosItem)); - } catch (IOException e) { - throw new IllegalArgumentException("Can't serialize the object into the json string", e); - } - } - return typedItem; + @Override + protected String getURIPathSegment() { + return Paths.DOCUMENTS_PATH_SEGMENT; } - static List getFromV2Results(List results, CosmosContainer container) { - return results.stream().map(document -> new CosmosItem(document.toJson(), container)).collect(Collectors.toList()); - } - - public T getObject(Class klass) throws IOException { - return (T) mapper.readValue(this.toJson(), klass); - } - - private String getLink(){ - StringBuilder builder = new StringBuilder(); - builder.append(container.getLink()); - builder.append("/"); - builder.append(Paths.DOCUMENTS_PATH_SEGMENT); - builder.append("/"); - builder.append(getId()); - return builder.toString(); + @Override + protected String getParentLink() { + return this.container.getLink(); } + } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java index 06d98ec217964..62f017ab337dc 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java @@ -152,12 +152,20 @@ public void setSessionToken(String sessionToken) { /** * Sets the partition key - * @param partitionKey + * @param partitionKey the partition key */ public void setPartitionKey(PartitionKey partitionKey) { this.partitionKey = partitionKey; } + /** + * Gets the partition key + * @return the partition key + */ + public PartitionKey getPartitionKey() { + return partitionKey; + } + @Override protected RequestOptions toRequestOptions() { //TODO: Should we set any default values instead of nulls? diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java index 0ee5ea9322fdc..f150206113cf8 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java @@ -23,26 +23,35 @@ package com.microsoft.azure.cosmos; import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmosdb.PartitionKey; import com.microsoft.azure.cosmosdb.ResourceResponse; -public class CosmosItemResponse extends CosmosResponse{ - private CosmosItem item; +public class CosmosItemResponse extends CosmosResponse{ + private CosmosItem itemClient; - CosmosItemResponse(ResourceResponse response, CosmosContainer container) { + CosmosItemResponse(ResourceResponse response, PartitionKey partitionKey, CosmosContainer container) { super(response); if(response.getResource() == null){ super.setResourceSettings(null); }else{ - super.setResourceSettings(new CosmosItem(response.getResource().toJson())); - item = new CosmosItem(response.getResource().toJson(), container); + super.setResourceSettings(new CosmosItemSettings(response.getResource().toJson())); + itemClient = new CosmosItem(response.getResource().getId(),partitionKey, container); } } /** - * Gets the item - * @return the item + * Gets the itemSettings + * @return the itemSettings + */ + public CosmosItemSettings getCosmosItemSettings() { + return getResourceSettings(); + } + + /** + * Gets the CosmosItem + * @return the cosmos item */ public CosmosItem getItem() { - return item; + return itemClient; } } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java new file mode 100644 index 0000000000000..18bb79b8233ee --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java @@ -0,0 +1,75 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.internal.Utils; + +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; + +public class CosmosItemSettings extends Resource { + + private static final ObjectMapper mapper = Utils.getSimpleObjectMapper(); + + /** + * Initialize a CosmosItemSettings object from json string. + * + * @param jsonString the json string that represents the document object. + */ + public CosmosItemSettings(String jsonString) { + super(jsonString); + } + + /** + * fromObject retuns Document for compatibility with V2 sdk + * + * @param cosmosItem + * @return + */ + static Document fromObject(Object cosmosItem) { + Document typedItem; + if (cosmosItem instanceof CosmosItemSettings) { + typedItem = new Document(((CosmosItemSettings) cosmosItem).toJson()); + } else { + try { + return new Document(CosmosItemSettings.mapper.writeValueAsString(cosmosItem)); + } catch (IOException e) { + throw new IllegalArgumentException("Can't serialize the object into the json string", e); + } + } + return typedItem; + } + + static List getFromV2Results(List results) { + return results.stream().map(document -> new CosmosItemSettings(document.toJson())).collect(Collectors.toList()); + } + + public T getObject(Class klass) throws IOException { + return (T) mapper.readValue(this.toJson(), klass); + } + +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java index 5efb553179b68..3f0e7c65203ad 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java @@ -45,12 +45,11 @@ public CosmosItemCrudTest(CosmosConfiguration.Builder configBuilder) { this.configBuilder = configBuilder; } - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + @Test(groups = { "simple" }, timeOut = TIMEOUT) public void testCreateItem() throws Exception { CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItem itemDefinition = getItemDefinition(); + CosmosItemSettings itemDefinition = getItemDefinition(); // create the item - System.out.println("itemDefinition = " + itemDefinition); Mono createMono = container.createItem(itemDefinition, "mypk"); // validate @@ -59,10 +58,10 @@ public void testCreateItem() throws Exception { validateSuccess(createMono, validator); } - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + @Test(groups = { "simple" }, timeOut = TIMEOUT) public void testCreateItem_AlreadyExists() throws Exception { CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItem itemDefinition = getItemDefinition(); + CosmosItemSettings itemDefinition = getItemDefinition(); // create the item container.createItem(itemDefinition, itemDefinition.get("mypk")).block(); @@ -74,14 +73,14 @@ public void testCreateItem_AlreadyExists() throws Exception { validateFailure(createMono, validator); } - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + @Test(groups = { "simple" }, timeOut = TIMEOUT) public void testReadItem() throws Exception { // read item CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItem itemDefinition = getItemDefinition(); + CosmosItemSettings itemDefinition = getItemDefinition(); // create the item CosmosItem item = container.createItem(itemDefinition, "mypk").block().getItem(); - Mono readMono = item.read("mypk"); + Mono readMono = item.read(); // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -89,13 +88,13 @@ public void testReadItem() throws Exception { validateSuccess(readMono, validator); } - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + @Test(groups = { "simple" }, timeOut = TIMEOUT) public void testDeleteItem() throws Exception { CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItem itemDefinition = getItemDefinition(); + CosmosItemSettings itemDefinition = getItemDefinition(); // create the item CosmosItem item = container.createItem(itemDefinition, "mypk").block().getItem(); - Mono deleteMono = item.delete("mypk"); + Mono deleteMono = item.delete(); // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .nullResource().build(); @@ -106,15 +105,15 @@ public void testDeleteItem() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void testreplaceItem() throws Exception { CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItem itemDefinition = getItemDefinition(); + CosmosItemSettings itemDefinition = getItemDefinition(); // create the item CosmosItem item = container.createItem(itemDefinition, "mypk").block().getItem(); String newPropValue = UUID.randomUUID().toString(); - item.set("newProp", newPropValue); + itemDefinition.set("newProp", newPropValue); // replace document - Mono readMono = item.replace(item, "mypk"); + Mono readMono = item.replace(itemDefinition); // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -122,22 +121,22 @@ public void testreplaceItem() throws Exception { validateSuccess(readMono, validator); } - @BeforeClass(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = CosmosClient.create(configBuilder.build()); createDatabase(client, PRE_EXISTING_DATABASE_ID); createContainerInDB(client, PRE_EXISTING_CONTAINER_ID, PRE_EXISTING_DATABASE_ID); } - @AfterClass(groups = { "cosmosv3" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeDeleteDatabase(client, PRE_EXISTING_DATABASE_ID); safeClose(client); } - private CosmosItem getItemDefinition() { + private CosmosItemSettings getItemDefinition() { String uuid = UUID.randomUUID().toString(); - return new CosmosItem(String.format("{ " + return new CosmosItemSettings(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java index be93657a49e29..1dba279227cc7 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java @@ -66,7 +66,7 @@ private Resource getResource(T resourceResponse) { }else if(resourceResponse instanceof CosmosContainerResponse){ return ((CosmosContainerResponse)resourceResponse).getCosmosContainerSettings(); }else if(resourceResponse instanceof CosmosItemResponse){ - return ((CosmosItemResponse)resourceResponse).getItem(); + return ((CosmosItemResponse)resourceResponse).getCosmosItemSettings(); } return null; } From ad7ba3af3ca7129da53d205880bc2be571489f50 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Mon, 3 Jun 2019 18:21:44 -0700 Subject: [PATCH 27/85] retry analyzer name typo fixed --- .../cosmosdb/{RetryAnalyzier.java => RetryAnalyzer.java} | 6 +++--- .../microsoft/azure/cosmosdb/rx/CollectionCrudTest.java | 4 ++-- .../azure/cosmosdb/rx/OrderbyDocumentQueryTest.java | 5 ++--- .../com/microsoft/azure/cosmosdb/rx/TopQueryTests.java | 7 +++---- .../azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java | 4 ++-- 5 files changed, 12 insertions(+), 14 deletions(-) rename commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/{RetryAnalyzier.java => RetryAnalyzer.java} (94%) diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzer.java similarity index 94% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java rename to commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzer.java index 47310b975b1fb..36766d50c9bd4 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzier.java +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzer.java @@ -32,11 +32,11 @@ import java.util.concurrent.TimeUnit; -public class RetryAnalyzier extends RetryAnalyzerCount { - private final Logger logger = LoggerFactory.getLogger(RetryAnalyzier.class); +public class RetryAnalyzer extends RetryAnalyzerCount { + private final Logger logger = LoggerFactory.getLogger(RetryAnalyzer.class); private final int waitBetweenRetriesInSeconds = 120; - public RetryAnalyzier() { + public RetryAnalyzer() { this.setCount(Integer.parseInt(TestConfigurations.MAX_RETRY_LIMIT)); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java index 0d1758dee2017..7f157cf677bc3 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java @@ -30,7 +30,7 @@ import com.microsoft.azure.cosmosdb.DatabaseForTest; import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RetryAnalyzier; +import com.microsoft.azure.cosmosdb.RetryAnalyzer; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; @@ -259,7 +259,7 @@ public void replaceCollection(String collectionName, boolean isNameBased) { safeDeleteAllCollections(client, database); } - @Test(groups = { "emulator" }, timeOut = 10 * TIMEOUT, retryAnalyzer = RetryAnalyzier.class) + @Test(groups = { "emulator" }, timeOut = 10 * TIMEOUT, retryAnalyzer = RetryAnalyzer.class) public void sessionTokenConsistencyCollectionDeleteCreateSameName() { AsyncDocumentClient client1 = clientBuilder.build(); AsyncDocumentClient client2 = clientBuilder.build(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java index 69e68daa6d033..21829fd366f87 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java @@ -35,7 +35,7 @@ import java.util.function.Function; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.RetryAnalyzier; +import com.microsoft.azure.cosmosdb.RetryAnalyzer; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.core.JsonProcessingException; @@ -60,7 +60,6 @@ import com.microsoft.azure.cosmosdb.rx.internal.query.CompositeContinuationToken; import com.microsoft.azure.cosmosdb.rx.internal.query.OrderByContinuationToken; -import org.testng.util.RetryAnalyzerCount; import rx.Observable; import rx.observers.TestSubscriber; @@ -376,7 +375,7 @@ public void orderByContinuationTokenRoundTrip() throws Exception { } } @Test(groups = { "simple" }, timeOut = TIMEOUT * 10, dataProvider = "sortOrder", - retryAnalyzer = RetryAnalyzier.class) + retryAnalyzer = RetryAnalyzer.class) public void queryDocumentsWithOrderByContinuationTokensInteger(String sortOrder) throws Exception { // Get Actual String query = String.format("SELECT * FROM c ORDER BY c.propInt %s", sortOrder); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java index 88c201a93fbbd..b40b22609e7ea 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java @@ -30,7 +30,7 @@ import java.util.Set; import java.util.concurrent.TimeUnit; -import com.microsoft.azure.cosmosdb.RetryAnalyzier; +import com.microsoft.azure.cosmosdb.RetryAnalyzer; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -44,7 +44,6 @@ import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; import com.microsoft.azure.cosmosdb.rx.internal.query.TakeContinuationToken; @@ -67,7 +66,7 @@ public TopQueryTests(AsyncDocumentClient.Builder clientBuilder) { this.clientBuilder = clientBuilder; } - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider", retryAnalyzer = RetryAnalyzier.class + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider", retryAnalyzer = RetryAnalyzer.class ) public void queryDocumentsWithTop(boolean qmEnabled) throws Exception { @@ -153,7 +152,7 @@ public void topContinuationTokenRoundTrips() throws Exception { } } - @Test(groups = { "simple" }, timeOut = TIMEOUT * 10, retryAnalyzer = RetryAnalyzier.class) + @Test(groups = { "simple" }, timeOut = TIMEOUT * 10, retryAnalyzer = RetryAnalyzer.class) public void queryDocumentsWithTopContinuationTokens() throws Exception { String query = "SELECT TOP 8 * FROM c"; this.queryWithContinuationTokensAndPageSizes(query, new int[] { 1, 5, 10 }, 8); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java index d46b88561d9a5..bbb9072868dbf 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java @@ -26,7 +26,7 @@ import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.RetryAnalyzier; +import com.microsoft.azure.cosmosdb.RetryAnalyzer; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import org.apache.commons.lang3.StringUtils; @@ -54,7 +54,7 @@ public VeryLargeDocumentQueryTest(Builder clientBuilder) { this.clientBuilder = clientBuilder; } - @Test(groups = { "emulator" }, timeOut = TIMEOUT, retryAnalyzer = RetryAnalyzier.class) + @Test(groups = { "emulator" }, timeOut = TIMEOUT, retryAnalyzer = RetryAnalyzer.class) public void queryLargeDocuments() { int cnt = 5; for(int i = 0; i < cnt; i++) { From b3ff05517fb59b0e0bd774b8467c5d897f3a5883 Mon Sep 17 00:00:00 2001 From: Mohammad Derakhshani Date: Mon, 3 Jun 2019 19:55:59 -0700 Subject: [PATCH 28/85] code review --- .../java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java index 3df802951f76e..546061b827855 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java @@ -700,7 +700,7 @@ static protected void safeCloseAsync(AsyncDocumentClient client) { try { client.close(); } catch (Exception e) { - e.printStackTrace(); + logger.error("failed to close client", e); } }).start(); } @@ -711,7 +711,7 @@ static protected void safeClose(AsyncDocumentClient client) { try { client.close(); } catch (Exception e) { - e.printStackTrace(); + logger.error("failed to close client", e); } } } @@ -893,7 +893,7 @@ public static Object[][] clientBuildersWithDirectSession() { } static Protocol[] toArray(List protocols) { - return protocols.toArray(new Protocol[0]); + return protocols.toArray(new Protocol[protocols.size()]); } private static Object[][] clientBuildersWithDirectSession(Protocol... protocols) { From a39813a895d08ada3194e03d3a023e88415cbdcd Mon Sep 17 00:00:00 2001 From: Christopher Anderson Date: Fri, 7 Jun 2019 17:32:33 -0700 Subject: [PATCH 29/85] use OffsetDateTime - fixes #154 (#170) * use OffsetDateTime - fixes #154 * Date should not have ms in it for comparison --- .../rx/ResourceResponseValidator.java | 7 ++-- .../microsoft/azure/cosmosdb/Resource.java | 17 ++++----- .../azure/cosmosdb/DocumentTests.java | 6 ++-- .../azure/cosmosdb/rx/DocumentCrudTest.java | 10 +++--- .../rx/internal/ConsistencyTestsBase.java | 36 +++++++++---------- 5 files changed, 40 insertions(+), 36 deletions(-) diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceResponseValidator.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceResponseValidator.java index 0686e7df13364..1af8ef372b6da 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceResponseValidator.java +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceResponseValidator.java @@ -25,8 +25,8 @@ import static org.assertj.core.api.Assertions.assertThat; import java.time.Instant; +import java.time.OffsetDateTime; import java.util.ArrayList; -import java.util.Date; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; @@ -51,6 +51,7 @@ import com.microsoft.azure.cosmosdb.TriggerType; import com.microsoft.azure.cosmosdb.UserDefinedFunction; import com.microsoft.azure.cosmosdb.SpatialType; +import org.assertj.core.data.Offset; public interface ResourceResponseValidator { @@ -133,7 +134,7 @@ public Builder withTimestampIsAfterOrEqualTo(Instant time) { public void validate(ResourceResponse resourceResponse) { assertThat(resourceResponse.getResource()).isNotNull(); assertThat(resourceResponse.getResource().getTimestamp()).isNotNull(); - Date d = resourceResponse.getResource().getTimestamp(); + OffsetDateTime d = resourceResponse.getResource().getTimestamp(); System.out.println(d.toString()); assertThat(d.toInstant()).isAfterOrEqualTo(time); } @@ -148,7 +149,7 @@ public Builder withTimestampIsBeforeOrEqualTo(Instant time) { public void validate(ResourceResponse resourceResponse) { assertThat(resourceResponse.getResource()).isNotNull(); assertThat(resourceResponse.getResource().getTimestamp()).isNotNull(); - Date d = resourceResponse.getResource().getTimestamp(); + OffsetDateTime d = resourceResponse.getResource().getTimestamp(); assertThat(d.toInstant()).isBeforeOrEqualTo(time); } }); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java index eb84bf89a0b14..2ceb5fdb6cf0e 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java @@ -23,8 +23,9 @@ package com.microsoft.azure.cosmosdb; -import java.util.Date; -import java.util.concurrent.TimeUnit; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -143,10 +144,10 @@ void setSelfLink(String selfLink) { * * @return the timestamp. */ - public Date getTimestamp() { - Double seconds = super.getDouble(Constants.Properties.LAST_MODIFIED); + public OffsetDateTime getTimestamp() { + Long seconds = super.getLong(Constants.Properties.LAST_MODIFIED); if (seconds == null) return null; - return new Date(TimeUnit.SECONDS.toMillis(seconds.longValue())); + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds.longValue()), ZoneOffset.UTC); } /** @@ -154,9 +155,9 @@ public Date getTimestamp() { * * @param timestamp the timestamp. */ - void setTimestamp(Date timestamp) { - double millisec = timestamp.getTime(); - super.set(Constants.Properties.LAST_MODIFIED, TimeUnit.MILLISECONDS.toSeconds((long) millisec)); + void setTimestamp(OffsetDateTime timestamp) { + long seconds = timestamp.toEpochSecond(); + super.set(Constants.Properties.LAST_MODIFIED, seconds); } /** diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentTests.java b/commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentTests.java index d3777240f00f9..d4ed8f4c87c25 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentTests.java +++ b/commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentTests.java @@ -25,16 +25,18 @@ import static org.assertj.core.api.Assertions.assertThat; -import java.util.Date; import org.testng.annotations.Test; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; + public class DocumentTests { @Test(groups = { "unit" }) public void timestamp() { Document d = new Document(); - Date time = new Date(86400 * 1000); + OffsetDateTime time = OffsetDateTime.of(2019, 8, 6, 12, 53, 29, 0, ZoneOffset.UTC); d.setTimestamp(time); assertThat(d.getTimestamp()).isEqualTo(time); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java index 2c13e78df1efd..6c995e8682e53 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java @@ -41,7 +41,7 @@ import org.testng.annotations.Test; import rx.Observable; -import java.util.Date; +import java.time.OffsetDateTime; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -195,7 +195,7 @@ public void readDocument(String documentId, boolean isNameBased) { @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") public void timestamp(String documentId, boolean isNameBased) throws Exception { - Date before = new Date(); + OffsetDateTime before = OffsetDateTime.now(); Document docDefinition = getDocumentDefinition(documentId); Thread.sleep(1000); Document document = client @@ -208,10 +208,10 @@ public void timestamp(String documentId, boolean isNameBased) throws Exception { Observable> readObservable = client.readDocument(getDocumentLink(document, isNameBased), options); Document readDocument = readObservable.toBlocking().single().getResource(); Thread.sleep(1000); - Date after = new Date(); + OffsetDateTime after = OffsetDateTime.now(); - assertThat(readDocument.getTimestamp()).isAfterOrEqualsTo(before); - assertThat(readDocument.getTimestamp()).isBeforeOrEqualsTo(after); + assertThat(readDocument.getTimestamp()).isAfterOrEqualTo(before); + assertThat(readDocument.getTimestamp()).isBeforeOrEqualTo(after); } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java index c262464360947..fd2a6dba097cd 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java @@ -63,8 +63,8 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Field; +import java.time.OffsetDateTime; import java.util.Arrays; -import java.util.Date; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -91,7 +91,7 @@ void validateStrongConsistency(Resource resourceToWorkWith) throws Exception { Resource writeResource = resourceToWorkWith; while (numberOfTestIteration-- > 0) //Write from a client and do point read through second client and ensure TS matches. { - Date sourceTimestamp = writeResource.getTimestamp(); + OffsetDateTime sourceTimestamp = writeResource.getTimestamp(); Thread.sleep(1000); //Timestamp is in granularity of seconds. Resource updatedResource = null; if (resourceToWorkWith instanceof User) { @@ -101,7 +101,7 @@ void validateStrongConsistency(Resource resourceToWorkWith) throws Exception { options.setPartitionKey(new PartitionKey(resourceToWorkWith.get("mypk"))); updatedResource = this.writeClient.upsertDocument(createdCollection.getSelfLink(), (Document) writeResource, options, false).toBlocking().first().getResource(); } - assertThat(updatedResource.getTimestamp().after(sourceTimestamp)).isTrue(); + assertThat(updatedResource.getTimestamp().isAfter(sourceTimestamp)).isTrue(); User readResource = this.readClient.readUser(resourceToWorkWith.getSelfLink(), null).toBlocking().first().getResource(); assertThat(updatedResource.getTimestamp().equals(readResource.getTimestamp())); @@ -175,12 +175,12 @@ void validateStrongConsistency(Document documentToWorkWith) throws InterruptedEx int numberOfTestIteration = 5; Document writeDocument = documentToWorkWith; while (numberOfTestIteration-- > 0) { - Date sourceTimestamp = writeDocument.getTimestamp(); + OffsetDateTime sourceTimestamp = writeDocument.getTimestamp(); Thread.sleep(1000);//Timestamp is in granularity of seconds. RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentToWorkWith.get("mypk"))); Document updatedDocument = this.writeClient.replaceDocument(writeDocument, options).toBlocking().first().getResource(); - assertThat(updatedDocument.getTimestamp().after(sourceTimestamp)).isTrue(); + assertThat(updatedDocument.getTimestamp().isAfter(sourceTimestamp)).isTrue(); Document readDocument = this.readClient.readDocument(documentToWorkWith.getSelfLink(), options).toBlocking().first().getResource(); assertThat(updatedDocument.getTimestamp().equals(readDocument.getTimestamp())); @@ -265,12 +265,12 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { boolean validateConsistentPrefix(Resource resourceToWorkWith) throws InterruptedException { int numberOfTestIteration = 5; - Date lastReadDateTime = resourceToWorkWith.getTimestamp(); + OffsetDateTime lastReadDateTime = resourceToWorkWith.getTimestamp(); boolean readLagging = false; Resource writeResource = resourceToWorkWith; while (numberOfTestIteration-- > 0) { //Write from a client and do point read through second client and ensure TS monotonically increases. - Date sourceTimestamp = writeResource.getTimestamp(); + OffsetDateTime sourceTimestamp = writeResource.getTimestamp(); Thread.sleep(1000); //Timestamp is in granularity of seconds. Resource updatedResource = null; if (resourceToWorkWith instanceof User) { @@ -278,7 +278,7 @@ boolean validateConsistentPrefix(Resource resourceToWorkWith) throws Interrupted } else if (resourceToWorkWith instanceof Document) { updatedResource = this.writeClient.upsertDocument(createdCollection.getSelfLink(), (Document) writeResource, null, false).toBlocking().first().getResource(); } - assertThat(updatedResource.getTimestamp().after(sourceTimestamp)).isTrue(); + assertThat(updatedResource.getTimestamp().isAfter(sourceTimestamp)).isTrue(); writeResource = updatedResource; Resource readResource = null; @@ -291,7 +291,7 @@ boolean validateConsistentPrefix(Resource resourceToWorkWith) throws Interrupted } assertThat(readResource.getTimestamp().compareTo(lastReadDateTime) >= 0).isTrue(); lastReadDateTime = readResource.getTimestamp(); - if (readResource.getTimestamp().before(updatedResource.getTimestamp())) { + if (readResource.getTimestamp().isBefore(updatedResource.getTimestamp())) { readLagging = true; } } @@ -300,18 +300,18 @@ boolean validateConsistentPrefix(Resource resourceToWorkWith) throws Interrupted boolean validateReadSession(Resource resourceToWorkWith) throws InterruptedException { int numberOfTestIteration = 5; - Date lastReadDateTime = new java.sql.Date(0); + OffsetDateTime lastReadDateTime = OffsetDateTime.MIN; boolean readLagging = false; Resource writeResource = resourceToWorkWith; while (numberOfTestIteration-- > 0) { - Date sourceTimestamp = writeResource.getTimestamp(); + OffsetDateTime sourceTimestamp = writeResource.getTimestamp(); Thread.sleep(1000); Resource updatedResource = null; if (resourceToWorkWith instanceof Document) { updatedResource = this.writeClient.upsertDocument(createdCollection.getSelfLink(), writeResource, null, false).toBlocking().single().getResource(); } - assertThat(updatedResource.getTimestamp().after(sourceTimestamp)).isTrue(); + assertThat(updatedResource.getTimestamp().isAfter(sourceTimestamp)).isTrue(); writeResource = updatedResource; Resource readResource = null; @@ -323,7 +323,7 @@ boolean validateReadSession(Resource resourceToWorkWith) throws InterruptedExcep assertThat(readResource.getTimestamp().compareTo(lastReadDateTime) >= 0).isTrue(); lastReadDateTime = readResource.getTimestamp(); - if (readResource.getTimestamp().before(updatedResource.getTimestamp())) { + if (readResource.getTimestamp().isBefore(updatedResource.getTimestamp())) { readLagging = true; } } @@ -332,18 +332,18 @@ boolean validateReadSession(Resource resourceToWorkWith) throws InterruptedExcep boolean validateWriteSession(Resource resourceToWorkWith) throws InterruptedException { int numberOfTestIteration = 5; - Date lastReadDateTime = new java.sql.Date(0); + OffsetDateTime lastReadDateTime = OffsetDateTime.MIN; boolean readLagging = false; Resource writeResource = resourceToWorkWith; while (numberOfTestIteration-- > 0) { - Date sourceTimestamp = writeResource.getTimestamp(); + OffsetDateTime sourceTimestamp = writeResource.getTimestamp(); Thread.sleep(1000); Resource updatedResource = null; if (resourceToWorkWith instanceof Document) { updatedResource = this.writeClient.upsertDocument(createdCollection.getSelfLink(), writeResource, null, false).toBlocking().single().getResource(); } - assertThat(updatedResource.getTimestamp().after(sourceTimestamp)).isTrue(); + assertThat(updatedResource.getTimestamp().isAfter(sourceTimestamp)).isTrue(); writeResource = updatedResource; Resource readResource = null; @@ -355,7 +355,7 @@ boolean validateWriteSession(Resource resourceToWorkWith) throws InterruptedExce assertThat(readResource.getTimestamp().compareTo(lastReadDateTime) >= 0).isTrue(); lastReadDateTime = readResource.getTimestamp(); - if (readResource.getTimestamp().before(updatedResource.getTimestamp())) { + if (readResource.getTimestamp().isBefore(updatedResource.getTimestamp())) { readLagging = true; } @@ -364,7 +364,7 @@ boolean validateWriteSession(Resource resourceToWorkWith) throws InterruptedExce if (resourceToWorkWith instanceof Document) { readResource = this.writeClient.upsertDocument(createdCollection.getSelfLink(), readResource, requestOptions, false).toBlocking().first().getResource(); //Now perform write on session } - assertThat(readResource.getTimestamp().after(lastReadDateTime)); + assertThat(readResource.getTimestamp().isAfter(lastReadDateTime)); this.readClient.setSession(this.writeClient.getSession()); } From f410e4f6ec9b52a5dbb2d5710f6387d732ca41c3 Mon Sep 17 00:00:00 2001 From: mbhaskar Date: Sat, 8 Jun 2019 14:05:50 -0700 Subject: [PATCH 30/85] Refactoring cosmos client, options and adding user (#139) - closes #151 * Refactoring CosmosClient adding a Builder Removed cosmos configuration Adding getters for scripts Adding CosmosUser Changing Options to composition * Minor refactoring Adding listUsers and queryUsers * Implementing PR comments * Fixing javadoc warnings * Fixing typo in doc * Merging V3 * Fixing doc issues --- .../azure/cosmos/examples/BasicDemo.java | 5 +- .../microsoft/azure/cosmos/CosmosClient.java | 91 +++++++--- .../azure/cosmos/CosmosClientBuilder.java | 152 +++++++++++++++++ .../azure/cosmos/CosmosConfiguration.java | 159 ------------------ .../azure/cosmos/CosmosContainer.java | 34 +++- .../cosmos/CosmosContainerRequestOptions.java | 16 +- .../azure/cosmos/CosmosContainerSettings.java | 3 +- .../azure/cosmos/CosmosDatabase.java | 84 ++++++++- .../cosmos/CosmosDatabaseRequestOptions.java | 4 +- .../azure/cosmos/CosmosDatabaseResponse.java | 4 +- .../azure/cosmos/CosmosDatabaseSettings.java | 2 - .../azure/cosmos/CosmosRequestOptions.java | 4 +- .../azure/cosmos/CosmosTriggerResponse.java | 6 +- .../microsoft/azure/cosmos/CosmosUser.java | 62 +++++++ .../azure/cosmos/CosmosUserResponse.java | 38 +++++ .../azure/cosmos/CosmosUserSettings.java | 57 +++++++ .../azure/cosmos/CosmosContainerCrudTest.java | 8 +- .../azure/cosmos/CosmosDatabaseCrudTest.java | 8 +- .../azure/cosmos/CosmosItemCrudTest.java | 8 +- .../azure/cosmos/CosmosTestSuiteBase.java | 12 +- 20 files changed, 534 insertions(+), 223 deletions(-) create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java delete mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosConfiguration.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java b/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java index dd21168dca01b..16e4f9bb963e7 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java +++ b/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java @@ -52,7 +52,10 @@ public static void main(String[] args) { private void start(){ // Get client - client = CosmosClient.create(AccountSettings.HOST, AccountSettings.MASTER_KEY); + client = CosmosClient.builder() + .endpoint(AccountSettings.HOST) + .key(AccountSettings.MASTER_KEY) + .build(); //Create a database and a container createDbAndContainerBlocking(); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java index 365dbdc9c53ac..50fcb1cb25846 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java @@ -23,10 +23,13 @@ package com.microsoft.azure.cosmos; import com.microsoft.azure.cosmosdb.BridgeInternal; +import com.microsoft.azure.cosmosdb.ConnectionPolicy; +import com.microsoft.azure.cosmosdb.ConsistencyLevel; import com.microsoft.azure.cosmosdb.Database; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.Permission; import com.microsoft.azure.cosmosdb.SqlQuerySpec; import com.microsoft.azure.cosmosdb.internal.HttpConstants; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; @@ -35,49 +38,84 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import java.util.List; + /** * Provides a client-side logical representation of the Azure Cosmos database service. * This asynchronous client is used to configure and execute requests * against the service. */ - public class CosmosClient { +public class CosmosClient { //Document client wrapper - private AsyncDocumentClient asyncDocumentClient; + private final AsyncDocumentClient asyncDocumentClient; + private final String serviceEndpoint; + private final String keyOrResourceToken; + private final ConnectionPolicy connectionPolicy; + private final ConsistencyLevel desiredConsistencyLevel; + private final List permissions; + + + CosmosClient(CosmosClientBuilder builder) { + this.serviceEndpoint = builder.getServiceEndpoint(); + this.keyOrResourceToken = builder.getKeyOrResourceToken(); + this.connectionPolicy = builder.getConnectionPolicy(); + this.desiredConsistencyLevel = builder.getDesiredConsistencyLevel(); + this.permissions = builder.getPermissions(); + this.asyncDocumentClient = new AsyncDocumentClient.Builder() + .withServiceEndpoint(this.serviceEndpoint) + .withMasterKeyOrResourceToken(this.keyOrResourceToken) + .withConnectionPolicy(this.connectionPolicy) + .withConsistencyLevel(this.desiredConsistencyLevel) + .build(); + } /** - * Creates a cosmos client with given cosmosConfiguration - * @param cosmosConfiguration the cosmosConfiguration - * @return cosmos client + * Instantiate the cosmos client builder to build cosmos client + * @return {@link CosmosClientBuilder} */ - public static CosmosClient create(CosmosConfiguration cosmosConfiguration) { - return new CosmosClient(cosmosConfiguration); + public static CosmosClientBuilder builder(){ + return new CosmosClientBuilder(); } /** - * Creates a cosmos client with given endpoint and key - * @param endpoint the service end point - * @param key the key - * @return cosmos clients + * Get the service endpoint + * @return the service endpoint */ - public static CosmosClient create(String endpoint, String key) { - CosmosConfiguration cosmosConfiguration = new CosmosConfiguration.Builder() - .withServiceEndpoint(endpoint) - .withKeyOrResourceToken(key).build(); - return create(cosmosConfiguration); + public String getServiceEndpoint() { + return serviceEndpoint; } /** - * Creates a cosmos client with given cosmos configuration - * @param cosmosConfiguration the cosmos configuration + * Gets the key or resource token + * @return get the key or resource token */ - private CosmosClient(CosmosConfiguration cosmosConfiguration) { - this.asyncDocumentClient = new AsyncDocumentClient.Builder() - .withServiceEndpoint(cosmosConfiguration.getServiceEndpoint().toString()) - .withMasterKeyOrResourceToken(cosmosConfiguration.getKeyOrResourceToken()) - .withConnectionPolicy(cosmosConfiguration.getConnectionPolicy()) - .withConsistencyLevel(cosmosConfiguration.getDesiredConsistencyLevel()) - .build(); + String getKeyOrResourceToken() { + return keyOrResourceToken; + } + + /** + * Get the connection policy + * @return {@link ConnectionPolicy} + */ + public ConnectionPolicy getConnectionPolicy() { + return connectionPolicy; + } + + /** + * Gets the consistency level + * @return the (@link ConsistencyLevel) + */ + public ConsistencyLevel getDesiredConsistencyLevel() { + return desiredConsistencyLevel; + } + + /** + * Gets the permission list + * @return the permission list + */ + public List getPermissions() { + return permissions; } AsyncDocumentClient getDocClientWrapper(){ @@ -239,8 +277,9 @@ public Flux> queryDatabases(SqlQuerySpec qu /** * Gets a database object without making a service call. + * * @param id name of the database - * @return + * @return {@link CosmosDatabase} */ public CosmosDatabase getDatabase(String id) { return new CosmosDatabase(id, this); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java new file mode 100644 index 0000000000000..eb0266bc6ecf8 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java @@ -0,0 +1,152 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ConnectionPolicy; +import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.microsoft.azure.cosmosdb.Permission; + +import java.util.List; + +/** + * Helper class to build {@link CosmosClient} instances + * as logical representation of the Azure Cosmos database service. + * + *

+ * {@code
+ * ConnectionPolicy connectionPolicy = new ConnectionPolicy();
+ * connectionPolicy.setConnectionMode(ConnectionMode.Direct);
+ * CosmonsClient client = new CosmosClient.builder()
+ *         .endpoint(serviceEndpoint)
+ *         .key(key)
+ *         .connectionPolicy(connectionPolicy)
+ *         .consistencyLevel(ConsistencyLevel.Session)
+ *         .build();
+ * }
+ * 
+ */ +public class CosmosClientBuilder { + + private String serviceEndpoint; + private String keyOrResourceToken; + private ConnectionPolicy connectionPolicy; + private ConsistencyLevel desiredConsistencyLevel; + private List permissions; + + CosmosClientBuilder() { + } + + /** + * The service endpoint url + * @param serviceEndpoint the service endpoint + * @return current Builder + */ + public CosmosClientBuilder endpoint(String serviceEndpoint) { + this.serviceEndpoint = serviceEndpoint; + return this; + } + + /** + * This method will take either key or resource token and perform authentication + * for accessing resource. + * + * @param keyOrResourceToken key or resourceToken for authentication . + * @return current Builder. + */ + public CosmosClientBuilder key(String keyOrResourceToken) { + this.keyOrResourceToken = keyOrResourceToken; + return this; + } + + /** + * This method will accept the permission list , which contains the + * resource tokens needed to access resources. + * + * @param permissions Permission list for authentication. + * @return current Builder. + */ + public CosmosClientBuilder permissions(List permissions) { + this.permissions = permissions; + return this; + } + + /** + * This method accepts the (@link ConsistencyLevel) to be used + * @param desiredConsistencyLevel {@link ConsistencyLevel} + * @return current Builder + */ + public CosmosClientBuilder consistencyLevel(ConsistencyLevel desiredConsistencyLevel) { + this.desiredConsistencyLevel = desiredConsistencyLevel; + return this; + } + + /** + * The (@link ConnectionPolicy) to be used + * @param connectionPolicy {@link ConnectionPolicy} + * @return current Builder + */ + public CosmosClientBuilder connectionPolicy(ConnectionPolicy connectionPolicy) { + this.connectionPolicy = connectionPolicy; + return this; + } + + private void ifThrowIllegalArgException(boolean value, String error) { + if (value) { + throw new IllegalArgumentException(error); + } + } + + /** + * Builds a cosmos configuration object with the provided settings + * @return CosmosClient + */ + public CosmosClient build() { + + ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint"); + ifThrowIllegalArgException( + this.keyOrResourceToken == null && (permissions == null || permissions.isEmpty()), + "cannot build client without key or resource token"); + + return new CosmosClient(this); + } + + String getServiceEndpoint() { + return serviceEndpoint; + } + + String getKeyOrResourceToken() { + return keyOrResourceToken; + } + + ConnectionPolicy getConnectionPolicy() { + return connectionPolicy; + } + + ConsistencyLevel getDesiredConsistencyLevel() { + return desiredConsistencyLevel; + } + + List getPermissions() { + return permissions; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosConfiguration.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosConfiguration.java deleted file mode 100644 index 3e111f4c692d2..0000000000000 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosConfiguration.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Permission; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; - -public class CosmosConfiguration { - private URI serviceEndpoint; - private String keyOrResourceToken; - private ConnectionPolicy connectionPolicy; - private ConsistencyLevel desiredConsistencyLevel; - private List permissions; - - private CosmosConfiguration(Builder builder) { - this.serviceEndpoint = builder.serviceEndpoint; - this.keyOrResourceToken = builder.keyOrResourceToken; - this.connectionPolicy = builder.connectionPolicy; - this.desiredConsistencyLevel = builder.desiredConsistencyLevel; - this.permissions = builder.permissions; - } - - public static class Builder { - - URI serviceEndpoint; - String keyOrResourceToken; - ConnectionPolicy connectionPolicy; //can set a default value here - ConsistencyLevel desiredConsistencyLevel; //can set a default value here - List permissions; //can set a default value here - int eventLoopSize = -1; - - public Builder withServiceEndpoint(String serviceEndpoint) { - try { - this.serviceEndpoint = new URI(serviceEndpoint); - } catch (URISyntaxException e) { - throw new IllegalArgumentException(e.getMessage()); - } - return this; - } - - /** - * This method will take either key or resource token and perform authentication - * for accessing resource. - * - * @param keyOrResourceToken key or resourceToken for authentication . - * @return current Builder. - */ - public Builder withKeyOrResourceToken(String keyOrResourceToken) { - this.keyOrResourceToken = keyOrResourceToken; - return this; - } - - /** - * This method will accept the permission list , which contains the - * resource tokens needed to access resources. - * - * @param permissions Permission list for authentication. - * @return current Builder. - */ - public Builder withPermissions(List permissions) { - this.permissions = permissions; - return this; - } - - /** - * This method accepts the (@link ConsistencyLevel) to be used - * @param desiredConsistencyLevel (@link ConsistencyLevel) - * @return - */ - public Builder withConsistencyLevel(ConsistencyLevel desiredConsistencyLevel) { - this.desiredConsistencyLevel = desiredConsistencyLevel; - return this; - } - - /** - * The (@link ConnectionPolicy) to be used - * @param connectionPolicy - * @return - */ - public Builder withConnectionPolicy(ConnectionPolicy connectionPolicy) { - this.connectionPolicy = connectionPolicy; - return this; - } - - private void ifThrowIllegalArgException(boolean value, String error) { - if (value) { - throw new IllegalArgumentException(error); - } - } - - /** - * Builds a cosmos configuration object with the provided settings - * @return CosmosConfiguration - */ - public CosmosConfiguration build() { - - ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint"); - ifThrowIllegalArgException( - this.keyOrResourceToken == null && (permissions == null || permissions.isEmpty()), - "cannot build client without key or resource token"); - - return new CosmosConfiguration(this); - } - - } - - public URI getServiceEndpoint() { - return serviceEndpoint; - } - - String getKeyOrResourceToken() { - return keyOrResourceToken; - } - - ConnectionPolicy getConnectionPolicy() { - return connectionPolicy; - } - - /** - * Gets the consistency level - * @return the (@link ConsistencyLevel) - */ - public ConsistencyLevel getDesiredConsistencyLevel() { - return desiredConsistencyLevel; - } - - /** - * Gets the permission list - * @return the permission list - */ - public List getPermissions() { - return permissions; - } -} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java index 15df971cd8f14..1f702e19650c0 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java @@ -65,7 +65,7 @@ public Mono read() { * After subscription the operation will be performed. * The {@link Mono} upon successful completion will contain a single cossmos container response with the read container. * In case of failure the {@link Mono} will error. - * + * @param options the cosmos container request options * @return an {@link Mono} containing the single cossmos container response with the read container or an error. */ public Mono read(CosmosContainerRequestOptions options) { @@ -293,7 +293,9 @@ public Flux> queryItems(SqlQuerySpec querySpec, /** * Gets a CosmosItem object without making a service call - * @param id id of the item + * + * @param id id of the item + * @param partitionKey the partition key * @return a cosmos item */ public CosmosItem getItem(String id, Object partitionKey){ @@ -386,6 +388,15 @@ public Flux> queryStoredProcedures(S response.getResponseHeaders())))); } + /** + * Gets a CosmosStoredProcedure object without making a service call + * @param id id of the stored procedure + * @return a cosmos stored procedure + */ + public CosmosStoredProcedure getStoredProcedure(String id){ + return new CosmosStoredProcedure(id, this); + } + /* UDF Operations */ @@ -468,6 +479,15 @@ public Flux> queryUserDefinedFun response.getResponseHeaders())))); } + /** + * Gets a CosmosUserDefinedFunction object without making a service call + * @param id id of the user defined function + * @return a cosmos user defined function + */ + public CosmosUserDefinedFunction getUserDefinedFunction(String id){ + return new CosmosUserDefinedFunction(id, this); + } + /* Trigger Operations */ /** * Creates a Cosmos trigger. @@ -476,6 +496,7 @@ public Flux> queryUserDefinedFun * The {@link Mono} upon successful completion will contain a cosmos trigger response * In case of failure the {@link Mono} will error. * + * @param settings the cosmos trigger settings * @param options the request options. * @return an {@link Mono} containing the single resource response with the created trigger or an error. */ @@ -545,6 +566,15 @@ public Flux> queryTriggers(SqlQuerySpec quer response.getResponseHeaders())))); } + /** + * Gets a CosmosTrigger object without making a service call + * @param id id of the cosmos trigger + * @return a cosmos trigger + */ + public CosmosTrigger getTrigger(String id){ + return new CosmosTrigger(id, this); + } + /** * Gets the parent Database * @return the (@link CosmosDatabase) diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java index 8dc3c121f6fe3..1ba2413c293bd 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java @@ -47,9 +47,11 @@ public Integer getOfferThroughput() { * Sets the throughput in the form of Request Units per second when creating a cosmos container. * * @param offerThroughput the throughput value. + * @return the current request options */ - public void setOfferThroughput(Integer offerThroughput) { + public CosmosContainerRequestOptions offerThroughput(Integer offerThroughput) { this.offerThroughput = offerThroughput; + return this; } /** @@ -69,9 +71,11 @@ public boolean isPopulateQuotaInfo() { * collection read requests. * * @param populateQuotaInfo a boolean value indicating whether PopulateQuotaInfo is enabled or not + * @return the current request options */ - public void setPopulateQuotaInfo(boolean populateQuotaInfo) { + public CosmosContainerRequestOptions populateQuotaInfo(boolean populateQuotaInfo) { this.populateQuotaInfo = populateQuotaInfo; + return this; } /** @@ -87,9 +91,11 @@ public ConsistencyLevel getConsistencyLevel() { * Sets the consistency level required for the request. * * @param consistencyLevel the consistency level. + * @return the current request options */ - public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { + public CosmosContainerRequestOptions consistencyLevel(ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; + return this; } /** @@ -105,9 +111,11 @@ public String getSessionToken() { * Sets the token for use with session consistency. * * @param sessionToken the session token. + * @return the current request options */ - public void setSessionToken(String sessionToken) { + public CosmosContainerRequestOptions sessionToken(String sessionToken) { this.sessionToken = sessionToken; + return this; } @Override diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java index a5635b0ec36de..62989947a4f91 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java @@ -104,7 +104,8 @@ public IndexingPolicy getIndexingPolicy() { /** * Sets the container's indexing policy - * @param indexingPolicy + * + * @param indexingPolicy {@link IndexingPolicy} the indexing policy */ public void setIndexingPolicy(IndexingPolicy indexingPolicy) { if (indexingPolicy == null) { diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java index 6327e174dd442..e8306ff8bc7f0 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java @@ -93,11 +93,12 @@ public Mono delete() { /** * Deletes a database. - * - * After subscription the operation will be performed. + *

+ * After subscription the operation will be performed. * The {@link Mono} upon successful completion will contain a cosmos database response with the deleted database. * In case of failure the {@link Mono} will error. * + * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono delete(CosmosRequestOptions options) { @@ -163,12 +164,13 @@ public Mono createContainer(String id, String partition /** * Creates a document container if it does not exist on the service. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos container response with the created + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos container response with the created * or existing collection. * In case of failure the {@link Mono} will error. * + * @param containerSettings the container settings * @return a {@link Mono} containing the cosmos container response with the created or existing container or * an error. */ @@ -280,6 +282,78 @@ public Flux> queryContainers(SqlQuerySpec public CosmosContainer getContainer(String id) { return new CosmosContainer(id, this); } + + /** User operations **/ + + /** + * Creates a user + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the created user. + * In case of failure the {@link Mono} will error. + * + * @param settings the cosmos user settings + * @param options the request options + * @return an {@link Mono} containing the single resource response with the created cosmos user or an error. + */ + public Mono createUser(CosmosUserSettings settings, RequestOptions options){ + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(getDocClientWrapper().createUser(this.getLink(), + settings.getV2User(), options).map(response -> + new CosmosUserResponse(response, this)).toSingle())); + } + + /** + * Upsert a user + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the created user. + * In case of failure the {@link Mono} will error. + * + * @param settings the cosmos user settings + * @param options the request options + * @return an {@link Mono} containing the single resource response with the upserted user or an error. + */ + public Mono upsertUser(CosmosUserSettings settings, RequestOptions options){ + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(getDocClientWrapper().upsertUser(this.getLink(), + settings.getV2User(), options).map(response -> + new CosmosUserResponse(response, this)).toSingle())); + } + + /** + * Reads all cosmos users in a database. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the read cosmos users. + * In case of failure the {@link Flux} will error. + * + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the read cosmos users or an error. + */ + public Flux> listUsers(FeedOptions options){ + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(getDocClientWrapper() + .readUsers(getLink(), options) + .map(response-> BridgeInternal.createFeedResponse(CosmosUserSettings.getFromV2Results(response.getResults(),this), + response.getResponseHeaders())))); + } + + /** + * Query for cosmos users in a database. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the obtained users. + * In case of failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained users or an error. + */ + public Flux> queryUsers(SqlQuerySpec querySpec, FeedOptions options){ + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(getDocClientWrapper() + .queryUsers(getLink(), querySpec, options) + .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( + CosmosUserSettings.getFromV2Results(response.getResults(), this), + response.getResponseHeaders(), response.getQueryMetrics())))); + } CosmosClient getClient() { return client; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java index 7b5cadf9d7696..77a60f70d98f0 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java @@ -43,9 +43,11 @@ public Integer getOfferThroughput() { * Sets the throughput in the form of Request Units per second when creating a cosmos database. * * @param offerThroughput the throughput value. + * @return the current request options */ - public void setOfferThroughput(Integer offerThroughput) { + public CosmosDatabaseRequestOptions offerThroughput(Integer offerThroughput) { this.offerThroughput = offerThroughput; + return this; } @Override diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java index 741d4c5ba0fdd..bf3690aeade9c 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java @@ -40,7 +40,8 @@ public class CosmosDatabaseResponse extends CosmosResponse databaseResourceResponse; - /** * Constructor * @param id id of the database diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java index 83910dc90d68b..30a5085021ccd 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java @@ -45,9 +45,11 @@ public AccessCondition getAccessCondition() { * Sets the conditions associated with the request. * * @param accessCondition the access condition. + * @return the current request options */ - public void setAccessCondition(AccessCondition accessCondition) { + public CosmosRequestOptions accessCondition(AccessCondition accessCondition) { this.accessCondition = accessCondition; + return this; } protected RequestOptions toRequestOptions(){ diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java index 3a05f74ab16b4..6dd0b4593f36c 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java @@ -40,7 +40,8 @@ public class CosmosTriggerResponse extends CosmosResponse /** * Gets the cosmos trigger settings or null - * @return + * + * @return {@link CosmosTriggerSettings} */ public CosmosTriggerSettings getCosmosTriggerSettings() { return cosmosTriggerSettings; @@ -48,7 +49,8 @@ public CosmosTriggerSettings getCosmosTriggerSettings() { /** * Gets the cosmos trigger object or null - * @return + * + * @return {@link CosmosTrigger} */ public CosmosTrigger getCosmosTrigger() { return cosmosTrigger; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java new file mode 100644 index 0000000000000..511f1654e5626 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java @@ -0,0 +1,62 @@ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.internal.Paths; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Mono; + +public class CosmosUser extends CosmosResource { + CosmosDatabase database; + public CosmosUser(String id, CosmosDatabase database) { + super(id); + this.database = database; + } + + /** + * Reads a cosmos user + * + * @param options the request options + * @return a {@link Mono} containing the single resource response with the read user or an error. + */ + public Mono read(RequestOptions options) { + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.database.getDocClientWrapper() + .readUser(getLink(), options) + .map(response -> new CosmosUserResponse(response, database)).toSingle())); + } + + /** + * Replace a cosmos user + * + * @param userSettings the user settings to use + * @param options the request options + * @return a {@link Mono} containing the single resource response with the replaced user or an error. + */ + public Mono replace(CosmosUserSettings userSettings, RequestOptions options) { + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.database.getDocClientWrapper() + .replaceUser(userSettings.getV2User(), options) + .map(response -> new CosmosUserResponse(response, database)).toSingle())); + } + + /** + * Delete a cosmos user + * + * @param options the request options + * @return a {@link Mono} containing the single resource response with the deleted user or an error. + */ + public Mono delete(RequestOptions options) { + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.database.getDocClientWrapper() + .deleteUser(getLink(), options) + .map(response -> new CosmosUserResponse(response, database)).toSingle())); + } + + @Override + protected String getURIPathSegment() { + return Paths.USERS_PATH_SEGMENT; + } + + @Override + protected String getParentLink() { + return database.getLink() ; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java new file mode 100644 index 0000000000000..a4b170353c182 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java @@ -0,0 +1,38 @@ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.User; + +public class CosmosUserResponse extends CosmosResponse { + private CosmosUser user; + + CosmosUserResponse(ResourceResponse response, CosmosDatabase database) { + super(response); + if(response.getResource() == null){ + super.setResourceSettings(null); + }else{ + super.setResourceSettings(new CosmosUserSettings(response)); + this.user = new CosmosUser(getResourceSettings().getId(), database); + } + } + + /** + * Get cosmos user + * + * @return {@link CosmosUser} + */ + public CosmosUser getUser() { + return user; + } + + /** + * Gets the cosmos user settings + * + * @return {@link CosmosUserSettings} + */ + public CosmosUserSettings getCosmosUserSettings(){ + return getResourceSettings(); + } + + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java new file mode 100644 index 0000000000000..5459fe1751f47 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java @@ -0,0 +1,57 @@ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.User; +import com.microsoft.azure.cosmosdb.internal.Constants; + +import java.util.List; +import java.util.stream.Collectors; + +public class CosmosUserSettings extends Resource { + /** + * Initialize a user object. + */ + public CosmosUserSettings() { + super(); + } + + /** + * Initialize a user object from json string. + * + * @param jsonString the json string that represents the database user. + */ + public CosmosUserSettings(String jsonString) { + super(jsonString); + } + + CosmosUserSettings(ResourceResponse response) { + super(response.getResource().toJson()); + } + + CosmosUserSettings(User user) { + super(user.toJson()); + } + + static List getFromV2Results(List results, CosmosDatabase database) { + return results.stream().map(CosmosUserSettings::new).collect(Collectors.toList()); + } + + /** + * Gets the self-link of the permissions associated with the user. + * + * @return the permissions link. + */ + public String getPermissionsLink() { + String selfLink = this.getSelfLink(); + if (selfLink.endsWith("/")) { + return selfLink + super.getString(Constants.Properties.PERMISSIONS_LINK); + } else { + return selfLink + "/" + super.getString(Constants.Properties.PERMISSIONS_LINK); + } + } + + User getV2User() { + return new User(this.toJson()); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java index e12eb7fa1925a..3491fb571e102 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java @@ -41,11 +41,11 @@ public class CosmosContainerCrudTest extends CosmosTestSuiteBase { private final static String CONTAINER_ID2 = getDatabaseId(CosmosContainerCrudTest.class) + "_CONTAINER_2"; private CosmosClient client; - private CosmosConfiguration.Builder configBuilder; + private CosmosClientBuilder clientBuilder; @Factory(dataProvider = "clientBuilders") - public CosmosContainerCrudTest(CosmosConfiguration.Builder configBuilder) { - this.configBuilder = configBuilder; + public CosmosContainerCrudTest(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; } @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) @@ -150,7 +150,7 @@ public void testreplaceContainer() throws Exception { @BeforeClass(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = CosmosClient.create(configBuilder.build()); + client = clientBuilder.build(); createDatabase(client, PRE_EXISTING_DATABASE_ID); createContainerInDB(client, PRE_EXISTING_CONTAINER_ID, PRE_EXISTING_DATABASE_ID); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java index 4647aacb05ac7..6f648a64dd591 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java @@ -38,11 +38,11 @@ public class CosmosDatabaseCrudTest extends CosmosTestSuiteBase { private final static String DATABASE_ID2 = getDatabaseId(CosmosDatabaseCrudTest.class) + "2"; private CosmosClient client; - private CosmosConfiguration.Builder configBuilder; + private CosmosClientBuilder clientBuilder; @Factory(dataProvider = "clientBuilders") - public CosmosDatabaseCrudTest(CosmosConfiguration.Builder configBuilder) { - this.configBuilder = configBuilder; + public CosmosDatabaseCrudTest(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; } @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) @@ -120,7 +120,7 @@ public void deleteDatabase_DoesntExist() throws Exception { @BeforeClass(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = CosmosClient.create(configBuilder.build()); + client = clientBuilder.build(); } @AfterClass(groups = { "cosmosv3" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java index 3f0e7c65203ad..f3e524d31f7ca 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java @@ -38,11 +38,11 @@ public class CosmosItemCrudTest extends CosmosTestSuiteBase { private final static String CONTAINER_ID2 = getDatabaseId(CosmosItemCrudTest.class) + "_CONTAINER_2"; private CosmosClient client; - private CosmosConfiguration.Builder configBuilder; + private CosmosClientBuilder clientBuilder; @Factory(dataProvider = "clientBuilders") - public CosmosItemCrudTest(CosmosConfiguration.Builder configBuilder) { - this.configBuilder = configBuilder; + public CosmosItemCrudTest(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -123,7 +123,7 @@ public void testreplaceItem() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = CosmosClient.create(configBuilder.build()); + client = clientBuilder.build(); createDatabase(client, PRE_EXISTING_DATABASE_ID); createContainerInDB(client, PRE_EXISTING_CONTAINER_ID, PRE_EXISTING_DATABASE_ID); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java index 6dc36f1bdf77a..6f8f672407638 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java @@ -99,17 +99,17 @@ public static Object[][] clientBuilders() { return new Object[][] { { createGatewayRxCosmosClient() } }; } - static protected CosmosConfiguration.Builder createGatewayRxCosmosClient() { + static protected CosmosClientBuilder createGatewayRxCosmosClient() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); connectionPolicy.setConnectionMode(ConnectionMode.Gateway); RetryOptions options = new RetryOptions(); options.setMaxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); connectionPolicy.setRetryOptions(options); - return new CosmosConfiguration.Builder().withConnectionPolicy(connectionPolicy) - .withServiceEndpoint(TestConfigurations.HOST) - .withKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withServiceEndpoint(TestConfigurations.HOST) - .withConsistencyLevel(ConsistencyLevel.Session); + + return CosmosClient.builder().connectionPolicy(connectionPolicy) + .endpoint(TestConfigurations.HOST) + .key(TestConfigurations.MASTER_KEY) + .consistencyLevel(ConsistencyLevel.Session); } static protected CosmosDatabase safeCreateDatabase(CosmosClient client, CosmosDatabaseSettings databaseSettings) { From ed980666cb36cdd4f7cfddc6a822567bf3dd138a Mon Sep 17 00:00:00 2001 From: Milis Date: Sat, 8 Jun 2019 15:23:23 -0700 Subject: [PATCH 31/85] Implementation for Change Feed Processor (#128) * Add CFP v3 user facing interfaces and classes. * Refactoring for package and method names. * Refactoring. * Add implementation for change feed processor interfaces. Add simple sample for change feed processor. * Removes interface API's which might go away after fully merging to V3. * Update change feed processor sample to be more "async" than "sync". * Resolve merge conflicts and remove support for non-partitioned lease collections. * Address some of the PR feedback for the Change Feed Sample and the user exposed interfaces. Left to address are some of the feedback comments regarding blocking calls in the implementation. * Sample cleanup based on the PR feedback. * Throw rather then return null if we cannot create an instance of the observer which will process the feeds. * fixes from OM changes --- .../ChangeFeed/SampleChangeFeedProcessor.java | 252 +++++++++ .../ChangeFeed/SampleConfigurations.java | 56 ++ .../ChangeFeed/SampleObserverImpl.java | 57 ++ .../azure/cosmos/ChangeFeedObserver.java | 53 ++ .../cosmos/ChangeFeedObserverCloseReason.java | 58 ++ .../cosmos/ChangeFeedObserverContext.java | 57 ++ .../cosmos/ChangeFeedObserverFactory.java | 35 ++ .../azure/cosmos/ChangeFeedProcessor.java | 151 ++++++ .../cosmos/ChangeFeedProcessorOptions.java | 501 ++++++++++++++++++ .../microsoft/azure/cosmos/CosmosClient.java | 8 + .../azure/cosmos/CosmosContainer.java | 59 +++ .../azure/cosmos/CosmosItemSettings.java | 7 +- .../azure/cosmos/changefeed/Bootstrapper.java | 37 ++ .../cosmos/changefeed/CancellationToken.java | 41 ++ .../changefeed/CancellationTokenSource.java | 61 +++ .../changefeed/ChangeFeedContextClient.java | 165 ++++++ .../changefeed/CheckpointFrequency.java | 113 ++++ .../changefeed/ContainerConnectionInfo.java | 186 +++++++ .../cosmos/changefeed/HealthMonitor.java | 38 ++ .../changefeed/HealthMonitoringRecord.java | 92 ++++ .../azure/cosmos/changefeed/Lease.java | 144 +++++ .../cosmos/changefeed/LeaseCheckpointer.java | 41 ++ .../cosmos/changefeed/LeaseContainer.java | 40 ++ .../azure/cosmos/changefeed/LeaseManager.java | 86 +++ .../azure/cosmos/changefeed/LeaseRenewer.java | 43 ++ .../azure/cosmos/changefeed/LeaseStore.java | 61 +++ .../cosmos/changefeed/LeaseStoreManager.java | 153 ++++++ .../changefeed/LeaseStoreManagerSettings.java | 63 +++ .../changefeed/PartitionCheckpointer.java | 38 ++ .../changefeed/PartitionController.java | 52 ++ .../changefeed/PartitionLoadBalancer.java | 44 ++ .../PartitionLoadBalancingStrategy.java | 97 ++++ .../cosmos/changefeed/PartitionManager.java | 44 ++ .../cosmos/changefeed/PartitionProcessor.java | 51 ++ .../changefeed/PartitionProcessorFactory.java | 39 ++ .../changefeed/PartitionSupervisor.java | 43 ++ .../PartitionSupervisorFactory.java | 35 ++ .../changefeed/PartitionSynchronizer.java | 46 ++ .../cosmos/changefeed/ProcessorSettings.java | 116 ++++ .../changefeed/RemainingPartitionWork.java | 38 ++ .../changefeed/RemainingWorkEstimator.java | 46 ++ .../changefeed/RequestOptionsFactory.java | 37 ++ .../cosmos/changefeed/ServiceItemLease.java | 242 +++++++++ .../changefeed/ServiceItemLeaseUpdater.java | 37 ++ .../exceptions/LeaseLostException.java | 109 ++++ .../exceptions/ObserverException.java | 39 ++ .../exceptions/PartitionException.java | 62 +++ .../PartitionNotFoundException.java | 50 ++ .../exceptions/PartitionSplitException.java | 49 ++ .../exceptions/TaskCancelledException.java | 37 ++ .../changefeed/internal/AutoCheckpointer.java | 94 ++++ .../changefeed/internal/BootstrapperImpl.java | 96 ++++ .../internal/ChangeFeedContextClientImpl.java | 174 ++++++ .../changefeed/internal/ChangeFeedHelper.java | 209 ++++++++ .../ChangeFeedObserverContextImpl.java | 87 +++ .../ChangeFeedObserverFactoryImpl.java | 47 ++ .../ChangeFeedProcessorBuilderImpl.java | 463 ++++++++++++++++ .../internal/CheckpointerObserverFactory.java | 61 +++ .../cosmos/changefeed/internal/Constants.java | 216 ++++++++ .../internal/DocumentServiceLeaseStore.java | 192 +++++++ .../DocumentServiceLeaseUpdaterImpl.java | 152 ++++++ .../EqualPartitionsBalancingStrategy.java | 189 +++++++ .../internal/ExceptionClassifier.java | 67 +++ ...onitoringPartitionControllerDecorator.java | 72 +++ .../changefeed/internal/LeaseRenewerImpl.java | 119 +++++ .../internal/LeaseStoreManagerImpl.java | 446 ++++++++++++++++ ...onWrappingChangeFeedObserverDecorator.java | 83 +++ .../internal/PartitionCheckpointerImpl.java | 56 ++ .../internal/PartitionControllerImpl.java | 185 +++++++ .../internal/PartitionLoadBalancerImpl.java | 143 +++++ .../internal/PartitionManagerImpl.java | 59 +++ .../PartitionProcessorFactoryImpl.java | 85 +++ .../internal/PartitionProcessorImpl.java | 174 ++++++ .../PartitionSupervisorFactoryImpl.java | 77 +++ .../internal/PartitionSupervisorImpl.java | 168 ++++++ .../internal/PartitionSynchronizerImpl.java | 172 ++++++ ...edByIdCollectionRequestOptionsFactory.java | 51 ++ .../internal/RemainingPartitionWorkImpl.java | 57 ++ .../internal/RemainingWorkEstimatorImpl.java | 85 +++ .../internal/StatusCodeErrorType.java | 34 ++ .../internal/TraceHealthMonitor.java | 44 ++ .../changefeed/internal/WorkerTask.java | 50 ++ 82 files changed, 8215 insertions(+), 1 deletion(-) create mode 100644 examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java create mode 100644 examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleConfigurations.java create mode 100644 examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleObserverImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserver.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverCloseReason.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverContext.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverFactory.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessor.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessorOptions.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Bootstrapper.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationToken.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationTokenSource.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ChangeFeedContextClient.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CheckpointFrequency.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ContainerConnectionInfo.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitor.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitoringRecord.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Lease.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseCheckpointer.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseContainer.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseManager.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseRenewer.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStore.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManager.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManagerSettings.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionCheckpointer.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionController.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancer.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancingStrategy.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionManager.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessor.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessorFactory.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisor.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisorFactory.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSynchronizer.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ProcessorSettings.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingPartitionWork.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingWorkEstimator.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RequestOptionsFactory.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLease.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLeaseUpdater.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/LeaseLostException.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/ObserverException.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionException.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionNotFoundException.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionSplitException.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/TaskCancelledException.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/AutoCheckpointer.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/BootstrapperImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedHelper.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/CheckpointerObserverFactory.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/Constants.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseStore.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ExceptionClassifier.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseRenewerImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseStoreManagerImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionCheckpointerImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionControllerImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionManagerImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSynchronizerImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/StatusCodeErrorType.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/TraceHealthMonitor.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/WorkerTask.java diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java b/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java new file mode 100644 index 0000000000000..a3a8da69dc194 --- /dev/null +++ b/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java @@ -0,0 +1,252 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.examples.ChangeFeed; + +import com.microsoft.azure.cosmos.ChangeFeedProcessor; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerResponse; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmosdb.ConnectionPolicy; +import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmosdb.SerializationFormattingPolicy; +import org.apache.commons.lang3.RandomStringUtils; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +/** + * Sample class to test the implementation. + * + */ +public class SampleChangeFeedProcessor { + + public static int WAIT_FOR_WORK = 60; + public static final String DATABASE_NAME = "db_" + RandomStringUtils.randomAlphabetic(7); + public static final String COLLECTION_NAME = "coll_" + RandomStringUtils.randomAlphabetic(7); + + private static ChangeFeedProcessor changeFeedProcessorInstance; + private static boolean isWorkCompleted = false; + + public static void main (String[]args) { + System.out.println("BEGIN Sample"); + + try { + + System.out.println("-->Create DocumentClient"); + CosmosClient client = getCosmosClient(); + + System.out.println("-->Create sample's database: " + DATABASE_NAME); + CosmosDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME); + + System.out.println("-->Create container for documents: " + COLLECTION_NAME); + CosmosContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME); + + System.out.println("-->Create container for lease: " + COLLECTION_NAME + "-leases"); + CosmosContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases"); + + Mono changeFeedProcessor1 = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); + + changeFeedProcessor1.subscribe(changeFeedProcessor -> { + changeFeedProcessorInstance = changeFeedProcessor; + changeFeedProcessor.start().subscribe(aVoid -> { + createNewDocuments(feedContainer, 10, Duration.ofSeconds(3)); + isWorkCompleted = true; + }); + }); + + long remainingWork = WAIT_FOR_WORK; + while (!isWorkCompleted && remainingWork > 0) { + Thread.sleep(100); + remainingWork -= 100; + } + + if (isWorkCompleted) { + if (changeFeedProcessorInstance != null) { + changeFeedProcessorInstance.stop().wait(10000); + } + } else { + throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time"); + } + + System.out.println("-->Delete sample's database: " + DATABASE_NAME); + deleteDatabase(cosmosDatabase); + + Thread.sleep(15000); + + } catch (Exception e) { + e.printStackTrace(); + } + + System.out.println("END Sample"); + System.exit(0); + } + + public static Mono getChangeFeedProcessor(String hostName, CosmosContainer feedContainer, CosmosContainer leaseContainer) { + return ChangeFeedProcessor.Builder() + .withHostName(hostName) + .withFeedContainerClient(feedContainer) + .withLeaseContainerClient(leaseContainer) + .withChangeFeedObserver(SampleObserverImpl.class) + .build(); + } + + public static CosmosClient getCosmosClient() { + + return CosmosClient.builder() + .endpoint(SampleConfigurations.HOST) + .key(SampleConfigurations.MASTER_KEY) + .connectionPolicy(ConnectionPolicy.GetDefault()) + .consistencyLevel(ConsistencyLevel.Eventual) + .build(); + } + + public static CosmosDatabase createNewDatabase(CosmosClient client, String databaseName) { + return client.createDatabaseIfNotExists(databaseName).block().getDatabase(); + } + + public static void deleteDatabase(CosmosDatabase cosmosDatabase) { + cosmosDatabase.delete().block(); + } + + public static CosmosContainer createNewCollection(CosmosClient client, String databaseName, String collectionName) { + CosmosDatabase databaseLink = client.getDatabase(databaseName); + CosmosContainer collectionLink = databaseLink.getContainer(collectionName); + CosmosContainerResponse containerResponse = null; + + try { + containerResponse = collectionLink.read().block(); + + if (containerResponse != null) { + throw new IllegalArgumentException(String.format("Collection %s already exists in database %s.", collectionName, databaseName)); + } + } catch (RuntimeException ex) { + if (ex.getCause() instanceof DocumentClientException) { + DocumentClientException documentClientException = (DocumentClientException) ex.getCause(); + + if (documentClientException.getStatusCode() != 404) { + throw ex; + } + } else { + throw ex; + } + } + + CosmosContainerSettings containerSettings = new CosmosContainerSettings(collectionName, "/id"); + + CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); + requestOptions.offerThroughput(10000); + + containerResponse = databaseLink.createContainer(containerSettings, requestOptions).block(); + + if (containerResponse == null) { + throw new RuntimeException(String.format("Failed to create collection %s in database %s.", collectionName, databaseName)); + } + + return containerResponse.getContainer(); + } + + public static CosmosContainer createNewLeaseCollection(CosmosClient client, String databaseName, String leaseCollectionName) { + CosmosDatabase databaseLink = client.getDatabase(databaseName); + CosmosContainer leaseCollectionLink = databaseLink.getContainer(leaseCollectionName); + CosmosContainerResponse leaseContainerResponse = null; + + try { + leaseContainerResponse = leaseCollectionLink.read().block(); + + if (leaseContainerResponse != null) { + leaseCollectionLink.delete().block(); + + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + } + } catch (RuntimeException ex) { + if (ex.getCause() instanceof DocumentClientException) { + DocumentClientException documentClientException = (DocumentClientException) ex.getCause(); + + if (documentClientException.getStatusCode() != 404) { + throw ex; + } + } else { + throw ex; + } + } + + CosmosContainerSettings containerSettings = new CosmosContainerSettings(leaseCollectionName, "/id"); + CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); + requestOptions.offerThroughput(400); + + leaseContainerResponse = databaseLink.createContainer(containerSettings, requestOptions).block(); + + if (leaseContainerResponse == null) { + throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName)); + } + + return leaseContainerResponse.getContainer(); + } + + public static void createNewDocuments(CosmosContainer containerClient, int count, Duration delay) { + String suffix = RandomStringUtils.randomAlphabetic(10); + for (int i = 0; i <= count; i++) { + CosmosItemSettings document = new CosmosItemSettings(); + document.setId(String.format("0%d-%s", i, suffix)); + + containerClient.createItem(document).subscribe(doc -> { + System.out.println("---->DOCUMENT WRITE: " + doc.getCosmosItemSettings().toJson(SerializationFormattingPolicy.Indented)); + }); + + long remainingWork = delay.toMillis(); + try { + while (remainingWork > 0) { + Thread.sleep(100); + remainingWork -= 100; + } + } catch (InterruptedException iex) { + // exception caught + break; + } + } + } + + public static boolean ensureWorkIsDone(Duration delay) { + long remainingWork = delay.toMillis(); + try { + while (!isWorkCompleted && remainingWork > 0) { + Thread.sleep(100); + remainingWork -= 100; + } + } catch (InterruptedException iex) { + return false; + } + + return remainingWork > 0; + } + +} diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleConfigurations.java b/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleConfigurations.java new file mode 100644 index 0000000000000..f55b3be2cd41c --- /dev/null +++ b/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleConfigurations.java @@ -0,0 +1,56 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.examples.ChangeFeed; + +import com.google.common.base.Strings; +import org.apache.commons.lang3.StringUtils; + +/** + * Contains the configurations for tests. + *

+ * For running tests, you can pass a customized endpoint configuration in one of the following + * ways: + *

    + *
  • -DACCOUNT_KEY="[your-key]" -ACCOUNT_HOST="[your-endpoint]" as JVM + * command-line option.
  • + *
  • You can set ACCOUNT_KEY and ACCOUNT_HOST as environment variables.
  • + *
+ *

+ * If none of the above is set, emulator endpoint will be used. + */ +public final class SampleConfigurations { + // Replace MASTER_KEY and HOST with values from your Azure Cosmos DB account. + // The default values are credentials of the local emulator, which are not used in any production environment. + // + public static String MASTER_KEY = + System.getProperty("ACCOUNT_KEY", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("ACCOUNT_KEY")), + "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==")); + + public static String HOST = + System.getProperty("ACCOUNT_HOST", + StringUtils.defaultString(Strings.emptyToNull( + System.getenv().get("ACCOUNT_HOST")), + "https://localhost:8081/")); +} diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleObserverImpl.java b/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleObserverImpl.java new file mode 100644 index 0000000000000..137e07af94225 --- /dev/null +++ b/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleObserverImpl.java @@ -0,0 +1,57 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.examples.ChangeFeed; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedObserverCloseReason; +import com.microsoft.azure.cosmos.ChangeFeedObserverContext; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmosdb.SerializationFormattingPolicy; + +import java.util.List; + +/** + * Sample ChangeFeedObserver. + */ +public class SampleObserverImpl implements ChangeFeedObserver { + @Override + public void open(ChangeFeedObserverContext context) { + System.out.println("--->SampleObserverImpl::open()"); + } + + @Override + public void close(ChangeFeedObserverContext context, ChangeFeedObserverCloseReason reason) { + System.out.println("--->SampleObserverImpl::close() -> " + reason.name()); + } + + @Override + public void processChanges(ChangeFeedObserverContext context, List docs) { + System.out.println("--->SampleObserverImpl::processChanges() START"); + + for (CosmosItemSettings document : docs) { + System.out.println("---->DOCUMENT RECEIVED: " + document.toJson(SerializationFormattingPolicy.Indented)); + } + System.out.println("--->SampleObserverImpl::processChanges() END"); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserver.java b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserver.java new file mode 100644 index 0000000000000..f6ef4557cb8e3 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserver.java @@ -0,0 +1,53 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import java.util.List; + +/** + * The interface used to deliver change events to document feed observers. + */ +public interface ChangeFeedObserver { + /** + * This is called when change feed observer is opened. + * + * @param context the context specifying partition for this observer, etc. + */ + void open(ChangeFeedObserverContext context); + + /** + * This is called when change feed observer is closed. + * + * @param context the context specifying partition for this observer, etc. + * @param reason the reason the observer is closed. + */ + void close(ChangeFeedObserverContext context, ChangeFeedObserverCloseReason reason); + + /** + * This is called when document changes are available on change feed. + * + * @param context the context specifying partition for this observer, etc. + * @param docs the documents changed. + */ + void processChanges(ChangeFeedObserverContext context, List docs); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverCloseReason.java b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverCloseReason.java new file mode 100644 index 0000000000000..d46dbd63428c2 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverCloseReason.java @@ -0,0 +1,58 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +/** + * The reason for the {@link ChangeFeedObserver} to close. + */ +public enum ChangeFeedObserverCloseReason { + /** + * UNKNOWN failure. This should never be sent to observers. + */ + UNKNOWN, + + /** + * The ChangeFeedEventProcessor is shutting down. + */ + SHUTDOWN, + + /** + * The resource, such as database or collection was removed. + */ + RESOURCE_GONE, + + /** + * Lease was lost due to expiration or load-balancing. + */ + LEASE_LOST, + + /** + * ChangeFeedObserver threw an exception. + */ + OBSERVER_ERROR, + + /** + * The lease is gone. This can be due to partition split. + */ + LEASE_GONE, +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverContext.java b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverContext.java new file mode 100644 index 0000000000000..b7a146c1dfd83 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverContext.java @@ -0,0 +1,57 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.FeedResponse; +import reactor.core.publisher.Mono; + +/** + * Represents the context passed to {@link ChangeFeedObserver} events. + */ +public interface ChangeFeedObserverContext { + + /** + * Gets the id of the partition for the current event. + * + * @return the id of the partition for the current event. + */ + String getPartitionKeyRangeId(); + + /** + * Gets the response from the underlying call. + * + * @return the response from the underlying call. + */ + FeedResponse getFeedResponse(); + + /** + * Checkpoints progress of a stream. This method is valid only if manual checkpoint was configured. + *

+ * Client may accept multiple change feed batches to process in parallel. + * Once first N document processing was finished the client can call checkpoint on the last completed batches in the row. + * In case of automatic checkpointing this is method throws. + * + * @return a representation of the deferred computation of this call. + */ + Mono checkpoint(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverFactory.java b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverFactory.java new file mode 100644 index 0000000000000..5dccf15d5c69c --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverFactory.java @@ -0,0 +1,35 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +/** + * Factory class used to create instance(s) of {@link ChangeFeedObserver}. + */ +public interface ChangeFeedObserverFactory { + /** + * Creates an instance of a {@link ChangeFeedObserver}. + * + * @return an instance of a {@link ChangeFeedObserver}. + */ + ChangeFeedObserver createObserver(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessor.java b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessor.java new file mode 100644 index 0000000000000..499283928a9ce --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessor.java @@ -0,0 +1,151 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmos.changefeed.HealthMonitor; +import com.microsoft.azure.cosmos.changefeed.LeaseStoreManager; +import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancingStrategy; +import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; +import com.microsoft.azure.cosmos.changefeed.PartitionProcessorFactory; +import com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedProcessorBuilderImpl; + +import reactor.core.publisher.Mono; +import java.util.concurrent.ExecutorService; + +/** + * Simple host for distributing change feed events across observers and thus allowing these observers scale. + * It distributes the load across its instances and allows dynamic scaling: + * - Partitions in partitioned collections are distributed across instances/observers. + * - New instance takes leases from existing instances to make distribution equal. + * - If an instance dies, the leases are distributed across remaining instances. + * It's useful for scenario when partition count is high so that one host/VM is not capable of processing that many change feed events. + * Client application needs to implement {@link ChangeFeedObserver} and register processor implementation with {@link ChangeFeedProcessor}. + *

+ * It uses auxiliary document collection for managing leases for a partition. + * Every EventProcessorHost instance is performing the following two tasks: + * 1) Renew Leases: It keeps track of leases currently owned by the host and continuously keeps on renewing the leases. + * 2) Acquire Leases: Each instance continuously polls all leases to check if there are any leases it should acquire + * for the system to get into balanced state. + *

+ * {@code + * ChangeFeedProcessor changeFeedProcessor = ChangeFeedProcessor.Builder() + * .withHostName(hostName) + * .withFeedContainerClient(feedContainer) + * .withLeaseContainerClient(leaseContainer) + * .withChangeFeedObserver(SampleObserverImpl.class) + * .build(); + * } + */ +public interface ChangeFeedProcessor { + + /** + * Start listening for changes asynchronously. + * + * @return a representation of the deferred computation of this call. + */ + Mono start(); + + /** + * Stops listening for changes asynchronously. + * + * @return a representation of the deferred computation of this call. + */ + Mono stop(); + + /** + * Helper static method to build {@link ChangeFeedProcessor} instances + * as logical representation of the Azure Cosmos DB database service. + *

+ * {@code + * + * ChangeFeedProcessor.Builder() + * .withHostName("SampleHost") + * .withFeedContainerClient(feedContainer) + * .withLeaseContainerClient(leaseContainer) + * .withChangeFeedObserver(SampleObserverImpl.class) + * .build(); + * } + * + * @return a builder definition instance. + */ + static BuilderDefinition Builder() { + return new ChangeFeedProcessorBuilderImpl(); + } + + interface BuilderDefinition { + /** + * Sets the host name. + * + * @param hostName the name to be used for the host. When using multiple hosts, each host must have a unique name. + * @return current Builder. + */ + BuilderDefinition withHostName(String hostName); + + /** + * Sets and existing {@link CosmosContainer} to be used to read from the monitored collection. + * + * @param feedContainerClient the instance of {@link CosmosContainer} to be used. + * @return current Builder. + */ + BuilderDefinition withFeedContainerClient(CosmosContainer feedContainerClient); + + /** + * Sets the {@link ChangeFeedProcessorOptions} to be used. + * + * @param changeFeedProcessorOptions the change feed processor options to use. + * @return current Builder. + */ + BuilderDefinition withProcessorOptions(ChangeFeedProcessorOptions changeFeedProcessorOptions); + + /** + * Sets the {@link ChangeFeedObserverFactory} to be used to generate {@link ChangeFeedObserver} + * + * @param observerFactory The instance of {@link ChangeFeedObserverFactory} to use. + * @return current Builder. + */ + BuilderDefinition withChangeFeedObserverFactory(ChangeFeedObserverFactory observerFactory); + + /** + * Sets an existing {@link ChangeFeedObserver} type to be used by a {@link ChangeFeedObserverFactory} to process changes. + * + * @param type the type of {@link ChangeFeedObserver} to be used. + * @return current Builder. + */ + BuilderDefinition withChangeFeedObserver(Class type); + + /** + * Sets an existing {@link CosmosContainer} to be used to read from the leases collection. + * + * @param leaseCosmosClient the instance of {@link CosmosContainer} to use. + * @return current Builder. + */ + BuilderDefinition withLeaseContainerClient(CosmosContainer leaseCosmosClient); + + /** + * Builds a new instance of the {@link ChangeFeedProcessor} with the specified configuration asynchronously. + * + * @return an instance of {@link ChangeFeedProcessor}. + */ + Mono build(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessorOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessorOptions.java new file mode 100644 index 0000000000000..7d47de793d416 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessorOptions.java @@ -0,0 +1,501 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmos.changefeed.CheckpointFrequency; + +import java.time.Duration; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; +import java.util.concurrent.ExecutorService; + +public class ChangeFeedProcessorOptions { + private static final int DefaultQueryPartitionsMaxBatchSize = 100; + private static Duration DefaultRenewInterval = Duration.ofMillis(0).plusSeconds(17); + private static Duration DefaultAcquireInterval = Duration.ofMillis(0).plusSeconds(13); + private static Duration DefaultExpirationInterval = Duration.ofMillis(0).plusSeconds(60); + private static Duration DefaultFeedPollDelay = Duration.ofMillis(0).plusSeconds(5); + + private Duration leaseRenewInterval; + private Duration leaseAcquireInterval; + private Duration leaseExpirationInterval; + private Duration feedPollDelay; + private CheckpointFrequency checkpointFrequency; + + private String leasePrefix; + private int maxItemCount; + private String startContinuation; + private ZonedDateTime startTime; + private boolean startFromBeginning; + private String sessionToken; + private int minPartitionCount; + private int maxPartitionCount; + private boolean discardExistingLeases; + private int queryPartitionsMaxBatchSize; + private int degreeOfParallelism; + private ExecutorService executorService; + + public ChangeFeedProcessorOptions() { + this.maxItemCount = 100; + this.startFromBeginning = false; + this.leaseRenewInterval = DefaultRenewInterval; + this.leaseAcquireInterval = DefaultAcquireInterval; + this.leaseExpirationInterval = DefaultExpirationInterval; + this.feedPollDelay = DefaultFeedPollDelay; + this.queryPartitionsMaxBatchSize = DefaultQueryPartitionsMaxBatchSize; + this.checkpointFrequency = new CheckpointFrequency(); + this.maxPartitionCount = 0; // unlimited + this.degreeOfParallelism = 25; // default + this.executorService = null; + } + + /** + * Gets the renew interval for all leases for partitions currently held by {@link ChangeFeedProcessor} instance. + * + * @return the renew interval for all leases for partitions. + */ + public Duration getLeaseRenewInterval() { + return this.leaseRenewInterval; + } + + /** + * Sets the renew interval for all leases for partitions currently held by {@link ChangeFeedProcessor} instance. + * + * @param leaseRenewInterval the renew interval for all leases for partitions currently held by {@link ChangeFeedProcessor} instance. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withLeaseRenewInterval(Duration leaseRenewInterval) { + this.leaseRenewInterval = leaseRenewInterval; + return this; + } + + /** + * Gets the interval to kick off a task to compute if partitions are distributed evenly among known host instances. + * + * @return the interval to kick off a task to compute if partitions are distributed evenly among known host instances. + */ + public Duration getLeaseAcquireInterval() { + return this.leaseAcquireInterval; + } + + /** + * Sets he interval to kick off a task to compute if partitions are distributed evenly among known host instances. + * @param leaseAcquireInterval he interval to kick off a task to compute if partitions are distributed evenly among known host instances. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withLeaseAcquireInterval(Duration leaseAcquireInterval) { + this.leaseAcquireInterval = leaseAcquireInterval; + return this; + } + + /** + * Gets the interval for which the lease is taken on a lease representing a partition. + * + *

+ * If the lease is not renewed within this interval, it will cause it to expire and ownership of the partition will + * move to another {@link ChangeFeedProcessor} instance. + * + * @return the interval for which the lease is taken on a lease representing a partition. + */ + public Duration getLeaseExpirationInterval() { + return this.leaseExpirationInterval; + } + + /** + * Sets the interval for which the lease is taken on a lease representing a partition. + * + *

+ * If the lease is not renewed within this interval, it will cause it to expire and ownership of the partition will + * move to another {@link ChangeFeedProcessor} instance. + * + * @param leaseExpirationInterval the interval for which the lease is taken on a lease representing a partition. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withLeaseExpirationInterval(Duration leaseExpirationInterval) { + this.leaseExpirationInterval = leaseExpirationInterval; + return this; + } + + /** + * Gets the delay in between polling a partition for new changes on the feed, after all current changes are drained. + * + * @return the delay in between polling a partition for new changes on the feed. + */ + public Duration getFeedPollDelay() { + return this.feedPollDelay; + } + + /** + * Sets the delay in between polling a partition for new changes on the feed, after all current changes are drained. + * + * @param feedPollDelay the delay in between polling a partition for new changes on the feed, after all current changes are drained. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withFeedPollDelay(Duration feedPollDelay) { + this.feedPollDelay = feedPollDelay; + return this; + } + + /** + * Gets the frequency how often to checkpoint leases. + * + * @return the frequency how often to checkpoint leases. + */ + public CheckpointFrequency getCheckpointFrequency() { + return this.checkpointFrequency; + } + + /** + * Sets the frequency how often to checkpoint leases. + * + * @param checkpointFrequency the frequency how often to checkpoint leases. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withCheckpointFrequency(CheckpointFrequency checkpointFrequency) { + this.checkpointFrequency = checkpointFrequency; + return this; + } + + /** + * Gets a prefix to be used as part of the lease ID. + *

+ * This can be used to support multiple instances of {@link ChangeFeedProcessor} instances pointing at the same + * feed while using the same auxiliary collection. + * + * @return a prefix to be used as part of the lease ID. + */ + public String getLeasePrefix() { + return this.leasePrefix; + } + + /** + * Sets a prefix to be used as part of the lease ID. + * + * @param leasePrefix a prefix to be used as part of the lease ID. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withLeasePrefix(String leasePrefix) { + this.leasePrefix = leasePrefix; + return this; + } + + /** + * Gets the maximum number of items to be returned in the enumeration operation in the Azure Cosmos DB service. + * + * @return the maximum number of items to be returned in the enumeration operation in the Azure Cosmos DB service. + */ + public int getMaxItemCount() { + return this.maxItemCount; + } + + /** + * Sets the maximum number of items to be returned in the enumeration operation. + * + * @param maxItemCount the maximum number of items to be returned in the enumeration operation. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withMaxItemCount(int maxItemCount) { + this.maxItemCount = maxItemCount; + return this; + } + + /** + * Gets the start request continuation token to start looking for changes after. + *

+ * This is only used when lease store is not initialized and is ignored if a lease for partition exists and + * has continuation token. If this is specified, both StartTime and StartFromBeginning are ignored. + * + * @return the start request continuation token to start looking for changes after. + */ + public String getStartContinuation() { + return this.startContinuation; + } + + /** + * Sets the start request continuation token to start looking for changes after. + *

+ * This is only used when lease store is not initialized and is ignored if a lease for partition exists and + * has continuation token. If this is specified, both StartTime and StartFromBeginning are ignored. + * + * @param startContinuation the start request continuation token to start looking for changes after. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withStartContinuation(String startContinuation) { + this.startContinuation= startContinuation; + return this; + } + + /** + * Gets the time (exclusive) to start looking for changes after. + *

+ * This is only used when: + * (1) Lease store is not initialized and is ignored if a lease for partition exists and has continuation token. + * (2) StartContinuation is not specified. + * If this is specified, StartFromBeginning is ignored. + * + * @return the time (exclusive) to start looking for changes after. + */ + public ZonedDateTime getStartTime() { + return this.startTime; + } + + /** + * Sets the time (exclusive) to start looking for changes after (UTC time). + *

+ * This is only used when: + * (1) Lease store is not initialized and is ignored if a lease for partition exists and has continuation token. + * (2) StartContinuation is not specified. + * If this is specified, StartFromBeginning is ignored. + * + * @param startTime the time (exclusive) to start looking for changes after. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withStartTime(ZonedDateTime startTime) { + this.startTime = startTime; + return this; + } + + /** + * Sets the time (exclusive) to start looking for changes after. + *

+ * This is only used when: + * (1) Lease store is not initialized and is ignored if a lease for partition exists and has continuation token. + * (2) StartContinuation is not specified. + * If this is specified, StartFromBeginning is ignored. + * + * @param startTime the time (exclusive) to start looking for changes after. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withStartTime(Date startTime) { + this.startTime = ZonedDateTime.ofInstant(startTime.toInstant(), ZoneId.of("UTC")); + return this; + } + + /** + * Gets a value indicating whether change feed in the Azure Cosmos DB service should start from beginning (true) + * or from current (false). By default it's start from current (false). + *

+ * This is only used when: + * (1) Lease store is not initialized and is ignored if a lease for partition exists and has continuation token. + * (2) StartContinuation is not specified. + * (3) StartTime is not specified. + * + * @return a value indicating whether change feed in the Azure Cosmos DB service should start from. + */ + public boolean isStartFromBeginning() { + return this.startFromBeginning; + } + + /** + * Sets a value indicating whether change feed in the Azure Cosmos DB service should start from beginning. + *

+ * This is only used when: + * (1) Lease store is not initialized and is ignored if a lease for partition exists and has continuation token. + * (2) StartContinuation is not specified. + * (3) StartTime is not specified. + * + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withStartFromBeginning() { + this.startFromBeginning = true; + return this; + } + + /** + * Sets a value indicating whether change feed in the Azure Cosmos DB service should start from beginning. + *

+ * This is only used when: + * (1) Lease store is not initialized and is ignored if a lease for partition exists and has continuation token. + * (2) StartContinuation is not specified. + * (3) StartTime is not specified. + * + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withoutStartFromBeginning() { + this.startFromBeginning = false; + return this; + } + + /** + * Gets the session token for use with session consistency in the Azure Cosmos DB service. + * + * @return the session token for use with session consistency in the Azure Cosmos DB service. + */ + public String getSessionToken() { + return this.sessionToken; + } + + /** + * Sets the session token for use with session consistency in the Azure Cosmos DB service. + * + * @param sessionToken the session token for use with session consistency in the Azure Cosmos DB service. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withSessionToken(String sessionToken) { + this.sessionToken = sessionToken; + return this; + } + + /** + * Gets the minimum partition count for the host. + *

+ * This can be used to increase the number of partitions for the host and thus override equal distribution (which + * is the default) of leases between hosts. + * + * @return the minimum partition count for the host. + */ + public int getMinPartitionCount() { + return this.minPartitionCount; + } + + /** + * Sets the minimum partition count for the host. + *

+ * This can be used to increase the number of partitions for the host and thus override equal distribution (which + * is the default) of leases between hosts. + * + * @param minPartitionCount the minimum partition count for the host. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withMinPartitionCount(int minPartitionCount) { + this.minPartitionCount = minPartitionCount; + return this; + } + + /** + * Gets the maximum number of partitions the host can serve. + *

+ * This can be used property to limit the number of partitions for the host and thus override equal distribution + * (which is the default) of leases between hosts. Default is 0 (unlimited). + * + * @return the maximum number of partitions the host can serve. + */ + public int getMaxPartitionCount() { + return this.maxPartitionCount; + } + + /** + * Sets the maximum number of partitions the host can serve. + * + * @param maxPartitionCount the maximum number of partitions the host can serve. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withMaxPartitionCount(int maxPartitionCount) { + this.maxPartitionCount = maxPartitionCount; + return this; + } + + /** + * Gets a value indicating whether on start of the host all existing leases should be deleted and the host + * should start from scratch. + * + * @return a value indicating whether on start of the host all existing leases should be deleted and the host should start from scratch. + */ + public boolean isDiscardExistingLeases() { + return this.discardExistingLeases; + } + + /** + * Sets a value indicating whether on start of the host all existing leases should be deleted and the host + * should start from scratch. + * + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withDiscardExistingLeases() { + this.discardExistingLeases = true; + return this; + } + + /** + * Sets a value indicating whether on start of the host all existing leases should be deleted and the host + * should start from scratch. + * + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withoutDiscardExistingLeases() { + this.discardExistingLeases = false; + return this; + } + + /** + * Gets the Batch size of query partitions API. + * + * @return the Batch size of query partitions API. + */ + public int getQueryPartitionsMaxBatchSize() { + return this.queryPartitionsMaxBatchSize; + } + + /** + * Sets the Batch size of query partitions API. + * + * @param queryPartitionsMaxBatchSize the Batch size of query partitions API. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withQueryPartitionsMaxBatchSize(int queryPartitionsMaxBatchSize) { + this.queryPartitionsMaxBatchSize = queryPartitionsMaxBatchSize; + return this; + } + + /** + * Gets maximum number of tasks to use for auxiliary calls. + * + * @return maximum number of tasks to use for auxiliary calls. + */ + public int getDegreeOfParallelism() { + return this.degreeOfParallelism; + } + + /** + * Sets maximum number of tasks to use for auxiliary calls. + * + * @param defaultQueryPartitionsMaxBatchSize maximum number of tasks to use for auxiliary calls. + * @return the current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withDegreeOfParallelism(int defaultQueryPartitionsMaxBatchSize) { + this.queryPartitionsMaxBatchSize = queryPartitionsMaxBatchSize; + return this; + } + + /** + * Gets the current {@link ExecutorService} which will be used to control the thread pool. + * + * @return current ExecutorService instance. + */ + public ExecutorService getExecutorService() { + return this.executorService; + } + + /** + * Sets the {@link ExecutorService} to be used to control the thread pool. + * + * @param executorService The instance of {@link ExecutorService} to use. + * @return current ChangeFeedProcessorOptions instance. + */ + public ChangeFeedProcessorOptions withExecutorService(ExecutorService executorService) { + this.executorService = executorService; + return this; + } + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java index 50fcb1cb25846..920df75cb493c 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java @@ -70,6 +70,14 @@ public class CosmosClient { .build(); } + AsyncDocumentClient getContextClient() { + return this.asyncDocumentClient; + } + + public static AsyncDocumentClient getContextClient(CosmosClient cosmosClient) { + return cosmosClient.asyncDocumentClient; + } + /** * Instantiate the cosmos client builder to build cosmos client * @return {@link CosmosClientBuilder} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java index 1f702e19650c0..e7d31c656818d 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java @@ -23,6 +23,7 @@ package com.microsoft.azure.cosmos; import com.microsoft.azure.cosmosdb.BridgeInternal; +import com.microsoft.azure.cosmosdb.ChangeFeedOptions; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.RequestOptions; @@ -31,6 +32,7 @@ import com.microsoft.azure.cosmosdb.Trigger; import com.microsoft.azure.cosmosdb.UserDefinedFunction; import com.microsoft.azure.cosmosdb.internal.Paths; +import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; @@ -45,6 +47,42 @@ public class CosmosContainer extends CosmosResource { this.database = database; } + AsyncDocumentClient getContextClient() { + if(this.database == null || this.database.getClient() == null) { + return null; + } + + return this.database.getClient().getContextClient(); + } + + /** + * Gets the context client. + * + * @param cosmosContainer the container client. + * @return the context client. + */ + public static AsyncDocumentClient getContextClient(CosmosContainer cosmosContainer) { + if(cosmosContainer == null) { + return null; + } + + return cosmosContainer.getContextClient(); + } + + /** + * Gets the self link to the container. + * + * @param cosmosContainer the container client. + * @return the self link. + */ + public static String getSelfLink(CosmosContainer cosmosContainer) { + if(cosmosContainer == null) { + return null; + } + + return cosmosContainer.getLink(); + } + /** * Reads the document container * @@ -291,6 +329,26 @@ public Flux> queryItems(SqlQuerySpec querySpec, response.getQueryMetrics())))); } + /** + * Query for documents in a items in a container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response of the obtained items. + * In case of failure the {@link Flux} will error. + * + * @param changeFeedOptions the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. + */ + public Flux> queryChangeFeedItems(ChangeFeedOptions changeFeedOptions){ + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(getDatabase() + .getDocClientWrapper() + .queryDocumentChangeFeed(getLink(), changeFeedOptions) + .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( + CosmosItemSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders(), response.getQueryMetrics())))); + } + /** * Gets a CosmosItem object without making a service call * @@ -577,6 +635,7 @@ public CosmosTrigger getTrigger(String id){ /** * Gets the parent Database + * * @return the (@link CosmosDatabase) */ public CosmosDatabase getDatabase() { diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java index 18bb79b8233ee..9000ed4ed3ca0 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java @@ -35,6 +35,11 @@ public class CosmosItemSettings extends Resource { private static final ObjectMapper mapper = Utils.getSimpleObjectMapper(); + /** + * Initialize an empty CosmosItemSettings object. + */ + public CosmosItemSettings() {} + /** * Initialize a CosmosItemSettings object from json string. * @@ -45,7 +50,7 @@ public CosmosItemSettings(String jsonString) { } /** - * fromObject retuns Document for compatibility with V2 sdk + * fromObject returns Document for compatibility with V2 sdk * * @param cosmosItem * @return diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Bootstrapper.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Bootstrapper.java new file mode 100644 index 0000000000000..28ed213f731c9 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Bootstrapper.java @@ -0,0 +1,37 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Mono; + +/** + * Bootstrapping interface. + */ +public interface Bootstrapper { + /** + * It initializes the bootstrapping. + * + * @return a deferred computation of this call. + */ + Mono initialize(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationToken.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationToken.java new file mode 100644 index 0000000000000..7d169c8cc4dd2 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationToken.java @@ -0,0 +1,41 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +/** + * Propagates notification that operations should be canceled.. + */ +public class CancellationToken { + private final CancellationTokenSource tokenSource; + + public CancellationToken(CancellationTokenSource source) { + this.tokenSource = source; + } + + /** + * @return true if the cancellation was requested from the source. + */ + public boolean isCancellationRequested() { + return tokenSource.isCancellationRequested(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationTokenSource.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationTokenSource.java new file mode 100644 index 0000000000000..587b9fa92f576 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationTokenSource.java @@ -0,0 +1,61 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import java.io.Closeable; +import java.io.IOException; + +/** + * Signals to a {@link CancellationToken} that it should be canceled.. + */ +public class CancellationTokenSource implements Closeable { + + private volatile boolean tokenSourceClosed; + private volatile boolean cancellationRequested; + + public CancellationTokenSource() { + this.tokenSourceClosed = false; + this.cancellationRequested = false; + } + + public synchronized boolean isCancellationRequested() { + if (tokenSourceClosed) { + throw new IllegalStateException("Object already closed"); + } + + return this.cancellationRequested; + } + + public CancellationToken getToken() { + return new CancellationToken(this); + } + + public synchronized void cancel() { + this.cancellationRequested = true; + } + + @Override + public synchronized void close() throws IOException { + if (tokenSourceClosed) return; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ChangeFeedContextClient.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ChangeFeedContextClient.java new file mode 100644 index 0000000000000..6ce5e488a79f3 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ChangeFeedContextClient.java @@ -0,0 +1,165 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerResponse; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseRequestOptions; +import com.microsoft.azure.cosmos.CosmosDatabaseResponse; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemResponse; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmosdb.ChangeFeedOptions; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.SqlQuerySpec; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.net.URI; + +/** + * The interface that captures the APIs required to handle change feed processing logic. + */ +public interface ChangeFeedContextClient { + /** + * Reads the feed (sequence) of {@link PartitionKeyRange} for a database account from the Azure Cosmos DB service as an asynchronous operation. + * + * @param partitionKeyRangesOrCollectionLink the link of the resources to be read, or owner collection link, SelfLink or AltLink. E.g. /dbs/db_rid/colls/coll_rid/pkranges. + * @param feedOptions the options for the request; it can be set as null. + * @return an an {@link Flux} containing one or several feed response pages of the obtained items or an error. + */ + Flux> readPartitionKeyRangeFeed(String partitionKeyRangesOrCollectionLink, FeedOptions feedOptions); + + /** + * Method to create a change feed query for documents. + * + * @param collectionLink Specifies the collection to read documents from. + * @param feedOptions The options for processing the query results feed. + * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. + */ + Flux> createDocumentChangeFeedQuery(CosmosContainer collectionLink, ChangeFeedOptions feedOptions); + + /** + * Reads a database. + * + * @param database a reference to the database. + * @param options the {@link CosmosContainerRequestOptions} for this request; it can be set as null. + * @return an {@link Mono} containing the single cosmos database response with the read database or an error. + */ + Mono readDatabase(CosmosDatabase database, CosmosDatabaseRequestOptions options); + + /** + * Reads a {@link CosmosContainer}. + * + * @param containerLink a reference to the container. + * @param options the {@link CosmosContainerRequestOptions} for this request; it can be set as null. + * @return an {@link Mono} containing the single cosmos container response with the read container or an error. + */ + Mono readContainer(CosmosContainer containerLink, CosmosContainerRequestOptions options); + + /** + * Creates a {@link CosmosItem}. + * + * @param containerLink the reference to the parent container. + * @param document the document represented as a POJO or Document object. + * @param options the request options. + * @param disableAutomaticIdGeneration the flag for disabling automatic id generation. + * @return an {@link Mono} containing the single resource response with the created cosmos item or an error. + */ + Mono createItem(CosmosContainer containerLink, Object document, CosmosItemRequestOptions options, + boolean disableAutomaticIdGeneration); + + /** + * Delete a {@link CosmosItem}. + * + * @param itemLink the item reference. + * @param options the request options. + * @return an {@link Mono} containing the cosmos item resource response with the deleted item or an error. + */ + Mono deleteItem(CosmosItem itemLink, CosmosItemRequestOptions options); + + /** + * Replaces a {@link CosmosItem}. + * + * @param itemLink the item reference. + * @param document the document represented as a POJO or Document object. + * @param options the request options. + * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. + */ + Mono replaceItem(CosmosItem itemLink, Object document, CosmosItemRequestOptions options); + + /** + * Reads a {@link CosmosItem} + * + * @param itemLink the item reference. + * @param options the request options. + * @return an {@link Mono} containing the cosmos item resource response with the read item or an error. + */ + Mono readItem(CosmosItem itemLink, CosmosItemRequestOptions options); + + /** + * Query for items in a document container. + * + * @param containerLink the reference to the parent container. + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. + */ + Flux> queryItems(CosmosContainer containerLink, SqlQuerySpec querySpec, FeedOptions options); + + /** + * @return the Cosmos client's service endpoint. + */ + URI getServiceEndpoint(); + + /** + * Reads and returns the container settings. + * + * @param containerLink a reference to the container. + * @param options the {@link CosmosContainerRequestOptions} for this request; it can be set as null. + * @return an {@link Mono} containing the read container settings. + */ + Mono readContainerSettings(CosmosContainer containerLink, CosmosContainerRequestOptions options); + + /** + * @return the Cosmos container client. + */ + CosmosContainer getContainerClient(); + + /** + * @return the Cosmos database client. + */ + CosmosDatabase getDatabaseClient(); + + /** + * Closes the document client instance and cleans up the resources. + */ + void close(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CheckpointFrequency.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CheckpointFrequency.java new file mode 100644 index 0000000000000..d48e738bdf41e --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CheckpointFrequency.java @@ -0,0 +1,113 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import java.time.Duration; + +/** + * Specifies the frequency of lease event. The event will trigger when either of conditions is satisfied. + */ +public class CheckpointFrequency { + private boolean explicitCheckpoint; + private int processedDocumentCount; + private Duration timeInterval; + + public CheckpointFrequency() { + this.explicitCheckpoint = false; + // Default to always checkpoint after processing each feed batch. + processedDocumentCount = 0; + timeInterval = null; + } + + /** + * Gets a value indicating whether explicit check-pointing is enabled. + *

+ * By default false. Setting to true means changefeed host will never checkpoint and client code needs to explicitly + * checkpoint via {@link PartitionCheckpointer} + * + * @return a value indicating whether explicit check-pointing is enabled. + */ + public boolean isExplicitCheckpoint() { + return explicitCheckpoint; + } + + /** + * Gets the value that specifies to checkpoint every specified number of docs. + * + * @return the value that specifies to checkpoint every specified number of docs. + */ + public int getProcessedDocumentCount() { + return this.processedDocumentCount; + } + + /** + * Gets the value that specifies to checkpoint every specified time interval. + * + * @return the value that specifies to checkpoint every specified time interval. + */ + public Duration getTimeInterval() { + return this.timeInterval; + } + + /** + * Sets a value indicating explicit check-pointing is enabled. + * + * @return current {@link CheckpointFrequency}. + */ + public CheckpointFrequency withExplicitCheckpoint() { + this.explicitCheckpoint = true; + return this; + } + + /** + * Sets a value indicating explicit checkpointing is disabled. + * + * @return current {@link CheckpointFrequency}. + */ + public CheckpointFrequency withoutExplicitCheckpoint() { + this.explicitCheckpoint = false; + return this; + } + + /** + * Sets the value that specifies to checkpoint every specified number of docs. + * + * @param processedDocumentCount the value that specifies to checkpoint every specified number of docs. + * @return current {@link CheckpointFrequency}. + */ + public CheckpointFrequency withProcessedDocumentCount(int processedDocumentCount) { + this.processedDocumentCount = processedDocumentCount; + return this; + } + + /** + * Sets the value that specifies to checkpoint every specified time interval. + * + * @param timeInterval the value that specifies to checkpoint every specified time interval. + * @return current {@link CheckpointFrequency}. + */ + public CheckpointFrequency withTimeInterval(Duration timeInterval) { + this.timeInterval = timeInterval; + return this; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ContainerConnectionInfo.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ContainerConnectionInfo.java new file mode 100644 index 0000000000000..c7fd1be36b01c --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ContainerConnectionInfo.java @@ -0,0 +1,186 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmosdb.ConnectionPolicy; +import com.microsoft.azure.cosmosdb.ConsistencyLevel; + +import java.net.URI; +import java.net.URISyntaxException; + +/** + * Holds information specifying how to get the Cosmos container. + */ +public class ContainerConnectionInfo { + private ConnectionPolicy connectionPolicy; + private ConsistencyLevel consistencyLevel; + private String serviceEndpointUri; + private String keyOrResourceToken; + private String databaseName; + private String containerName; + + /** + * Initializes a new instance of the {@link ContainerConnectionInfo} class. + */ + public ContainerConnectionInfo() { + this.connectionPolicy = new ConnectionPolicy(); + this.consistencyLevel = ConsistencyLevel.Session; + } + + /** + * Initializes a new instance of the {@link ContainerConnectionInfo} class. + * + * @param containerConnectionInfo the {@link ContainerConnectionInfo} instance to copy the settings from. + */ + public ContainerConnectionInfo(ContainerConnectionInfo containerConnectionInfo) { + this.connectionPolicy = containerConnectionInfo.connectionPolicy; + this.consistencyLevel = containerConnectionInfo.consistencyLevel; + this.serviceEndpointUri = containerConnectionInfo.serviceEndpointUri; + this.keyOrResourceToken = containerConnectionInfo.keyOrResourceToken; + this.databaseName = containerConnectionInfo.databaseName; + this.containerName = containerConnectionInfo.containerName; + } + + /** + * Gets the connection policy to connect to Cosmos service. + * + * @return the connection policy to connect to Cosmos service. + */ + public ConnectionPolicy getConnectionPolicy() { + return this.connectionPolicy; + } + + /** + * Gets the consistency level; default is "Session". + * @return the consistency level. + */ + public ConsistencyLevel getConsistencyLevel() { + return this.consistencyLevel; + } + + /** + * Gets the URI of the Document service. + * + * @return the URI of the Document service. + */ + public String getServiceEndpointUri() { + return this.serviceEndpointUri; + } + + /** + * Gets the secret master key to connect to the Cosmos service. + * + * @return the secret master key to connect to the Cosmos service. + */ + public String getKeyOrResourceToken() { + return this.keyOrResourceToken; + } + + /** + * Gets the name of the database the container resides in. + * + * @return the name of the database the container resides in. + */ + public String getDatabaseName() { + return this.databaseName; + } + + /** + * Gets the name of the Cosmos container. + * + * @return the name of the Cosmos container. + */ + public String getContainerName() { + return this.containerName; + } + + /** + * Sets the connection policy to connect to Cosmos service. + * + * @param connectionPolicy the connection policy to connect to Cosmos service. + * @return current instance of {@link ContainerConnectionInfo} + */ + public ContainerConnectionInfo withConnectionPolicy(ConnectionPolicy connectionPolicy) { + this.connectionPolicy = connectionPolicy; + return this; + } + + /** + * Sets the consistency level. + * + * @param consistencyLevel the consistency level. + * @return current instance of {@link ContainerConnectionInfo} + */ + public ContainerConnectionInfo withConsistencyLevel(ConsistencyLevel consistencyLevel) { + this.consistencyLevel = consistencyLevel; + return this; + } + + /** + * Sets the URI of the Document service. + * @param serviceEndpoint the URI of the Cosmos service. + * @return current instance of {@link ContainerConnectionInfo} + */ + public ContainerConnectionInfo withServiceEndpointUri(String serviceEndpoint) { + try { + new URI(serviceEndpoint); + } catch (URISyntaxException ex) { + throw new IllegalArgumentException("serviceEndpointUri"); + } + + this.serviceEndpointUri = serviceEndpoint; + return this; + } + + /** + * Sets the secret master key to connect to the Cosmos service. + * @param keyOrResourceToken the secret master key to connect to the Cosmos service. + * @return current instance of {@link ContainerConnectionInfo} + */ + public ContainerConnectionInfo withKeyOrResourceToken(String keyOrResourceToken) { + this.keyOrResourceToken = keyOrResourceToken; + return this; + } + + /** + * Sets the name of the database the container resides in. + * + * @param databaseName the name of the database the container resides in. + * @return current instance of {@link ContainerConnectionInfo} + */ + public ContainerConnectionInfo withDatabaseName(String databaseName) { + this.databaseName = databaseName; + return this; + } + + /** + * Sets the name of the Cosmos container. + * + * @param containerName the name of the Cosmos container. + * @return current instance of {@link ContainerConnectionInfo} + */ + public ContainerConnectionInfo withContainerName(String containerName) { + this.containerName = containerName; + return this; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitor.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitor.java new file mode 100644 index 0000000000000..a3a91971529b7 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitor.java @@ -0,0 +1,38 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Mono; + +/** + * A strategy for handling the situation when the change feed processor is not able to acquire lease due to unknown reasons. + */ +public interface HealthMonitor { + /** + * A logic to handle that exceptional situation. + * + * @param record the monitoring record. + * @return a representation of the deferred computation of this call. + */ + Mono inspect(HealthMonitoringRecord record); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitoringRecord.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitoringRecord.java new file mode 100644 index 0000000000000..971ff55664541 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitoringRecord.java @@ -0,0 +1,92 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +/** + * A record used in the health monitoring. + */ +public class HealthMonitoringRecord { + public final HealthSeverity severity; + public final MonitoredOperation operation; + public final Lease lease; + public final Throwable throwable; + + /** + * Initializes a new instance of the {@link HealthMonitoringRecord} class. + * + * @param severity the health severity level. + * @param operation the operation. + * @param lease the lease. + * @param throwable the exception. + */ + public HealthMonitoringRecord(HealthSeverity severity, MonitoredOperation operation, Lease lease, Throwable throwable) { + if (lease == null) throw new IllegalArgumentException("lease"); + this.severity = severity; + this.operation = operation; + this.lease = lease; + this.throwable = throwable; + } + + /** + * @return the severity of this monitoring record. + */ + public HealthSeverity getSeverity() { + return this.severity; + } + + /** + * The health severity level. + */ + public enum HealthSeverity { + /** + * Critical level. + */ + CRITICAL(10), + + /** + * Error level. + */ + ERROR(20), + + /** + * Information level. + */ + INFORMATIONAL(30); + + public final int value; + + HealthSeverity(int value){ + this.value = value; + } + } + + /** + * The health monitoring phase. + */ + public enum MonitoredOperation { + /** + * A phase when the instance tries to acquire the lease. + */ + ACQUIRE_LEASE, + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Lease.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Lease.java new file mode 100644 index 0000000000000..1a3841915c636 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Lease.java @@ -0,0 +1,144 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.ChangeFeedProcessor; + +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; +import java.util.Map; + +/** + * Represents a lease that is persisted as a document in the lease collection. + *

+ * Leases are used to: + * Keep track of the {@link ChangeFeedProcessor} progress for a particular Partition Key Range. + * Distribute load between different instances of {@link ChangeFeedProcessor}. + * Ensure reliable recovery for cases when an instance of {@link ChangeFeedProcessor} gets disconnected, hangs or crashes. + */ +public interface Lease { + /** + * Gets the partition associated with the lease. + * + * @return the partition associated with the lease. + */ + String getLeaseToken(); + + /** + * Gets the host name owner of the lease. + * + *

+ * The Owner keeps track which {@link ChangeFeedProcessor} is currently processing that Partition Key Range. + * + * @return the host name owner of the lease. + */ + String getOwner(); + + /** + * Gets the timestamp of the lease. + * + * @return the timestamp of the lease. + */ + String getTimestamp(); + + /** + * Gets the continuation token used to determine the last processed point of the Change Feed. + * + * @return the continuation token used to determine the last processed point of the Change Feed. + */ + String getContinuationToken(); + + /** + * Sets the continuation token used to determine the last processed point of the Change Feed. + * + * + * @param continuationToken the continuation token used to determine the last processed point of the Change Feed. + */ + void setContinuationToken(String continuationToken); + + /** + * Gets the lease ID. + * + * @return the lease ID. + */ + String getId(); + + /** + * Gets the concurrency token. + * + * @return the concurrency token. + */ + String getConcurrencyToken(); + + /** + * Gets the custom lease properties which can be managed from {@link PartitionLoadBalancingStrategy}. + * + * @return the custom lease properties. + */ + Map getProperties(); + + /** + * Sets the host name owner of the lease. + * + *

+ * The Owner keeps track which {@link ChangeFeedProcessor} is currently processing that Partition Key Range. + * + * @param owner the host name owner of the lease. + */ + void setOwner(String owner); + + /** + * Sets the timestamp of the lease. + * + *

+ * The timestamp is used to determine lease expiration. + * + * @param timestamp the timestamp of the lease. + */ + void setTimestamp(ZonedDateTime timestamp); + + /** + * Sets the lease ID. + * + * + * @param id the lease ID. + */ + void setId(String id); + + /** + * Sets the concurrency token. + * + * + * @param concurrencyToken the concurrency token. + */ + void setConcurrencyToken(String concurrencyToken); + + /** + * Sets the custom lease properties which can be managed from {@link PartitionLoadBalancingStrategy}. + * + * + * @param properties the custom lease properties. + */ + void setProperties(Map properties); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseCheckpointer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseCheckpointer.java new file mode 100644 index 0000000000000..8484aa40f6b2e --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseCheckpointer.java @@ -0,0 +1,41 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Mono; + +/** + * Interface for check-pointing the lease. + */ +public interface LeaseCheckpointer { + /** + * Check-points the lease. + *

+ * Throws LeaseLostException if other host acquired the lease or lease was deleted. + * + * @param lease the lease to renew. + * @param continuationToken the continuation token. + * @return the updated renewed lease. + */ + Mono checkpoint(Lease lease, String continuationToken); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseContainer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseContainer.java new file mode 100644 index 0000000000000..62a8daa321245 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseContainer.java @@ -0,0 +1,40 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Flux; + +/** + * Represents operations to get leases from lease store.. + */ +public interface LeaseContainer { + /** + * @return all leases. + */ + Flux getAllLeases(); + + /** + * @return all leases owned by the current host. + */ + Flux getOwnedLeases(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseManager.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseManager.java new file mode 100644 index 0000000000000..b1c658b8931a8 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseManager.java @@ -0,0 +1,86 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.changefeed.exceptions.LeaseLostException; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * It defines a way to perform operations with {@link Lease}. + */ +public interface LeaseManager { + /** + * Checks whether the lease exists and creates it if it does not exist. + * + * @param leaseToken the lease token to work with. + * @param continuationToken the continuation token if it exists. + * @return the lease. + */ + Mono createLeaseIfNotExist(String leaseToken, String continuationToken); + + /** + * Deletes the lease. + * + * @param lease the lease to delete. + * @return a deferred computation of this call. + */ + Mono delete(Lease lease); + + /** + * Acquires ownership of the lease. + * It can throw {@link LeaseLostException} if other host acquired concurrently the lease. + * + * @param lease the lease to acquire. + * @return the updated lease. + */ + Mono acquire(Lease lease); + + /** + * It releases ownership of the lease. + * It can throw {@link LeaseLostException} if other host acquired the lease. + * + * @param lease the lease to acquire. + * @return a deferred computation of this call. + */ + Mono release(Lease lease); + + /** + * Renew the lease; leases are periodically renewed to prevent expiration. + * It can throw {@link LeaseLostException} if other host acquired the lease. + * + * @param lease the lease to renew. + * @return the updated lease. + */ + Mono renew(Lease lease); + + /** + * Replace properties from the specified lease. + * It can throw {@link LeaseLostException} if other host acquired the lease. + * + * @param leaseToUpdatePropertiesFrom the new properties. + * @return updated lease. + */ + Mono updateProperties(Lease leaseToUpdatePropertiesFrom); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseRenewer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseRenewer.java new file mode 100644 index 0000000000000..41b618518f417 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseRenewer.java @@ -0,0 +1,43 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Mono; + +/** + * Interface for the lease renewer. + */ +public interface LeaseRenewer { + /** + * Starts the lease renewer. + * + * @param cancellationToken the token used for canceling the workload. + * @return a deferred operation of this call. + */ + Mono run(CancellationToken cancellationToken); + + /** + * @return the inner exception if any, otherwise null. + */ + RuntimeException getResultException(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStore.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStore.java new file mode 100644 index 0000000000000..adee8dffef66f --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStore.java @@ -0,0 +1,61 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Mono; + +import java.time.Duration; + +/** + * Represents the lease store container to deal with initialization/cleanup of leases + * for particular monitoring collection and lease container prefix. + */ +public interface LeaseStore { + + /** + * @return true if the lease store is initialized. + */ + Mono isInitialized(); + + /** + * Mark the store as initialized. + * + * @return a deferred computation of this operation call. + */ + Mono markInitialized(); + + /** + * Places a lock on the lease store for initialization. Only one process may own the store for the lock time. + * + * @param lockExpirationTime the time for the lock to expire. + * @return true if the lock was acquired, false otherwise. + */ + Mono acquireInitializationLock(Duration lockExpirationTime); + + /** + * Releases the lock one the lease store for initialization. + * + * @return true if the lock was acquired and was released, false if the lock was not acquired. + */ + Mono releaseInitializationLock(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManager.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManager.java new file mode 100644 index 0000000000000..e9139961083e5 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManager.java @@ -0,0 +1,153 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.changefeed.internal.LeaseStoreManagerImpl; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +/** + * Defines an interface for operations with {@link Lease}. + */ +public interface LeaseStoreManager extends LeaseContainer, LeaseManager, LeaseStore, LeaseCheckpointer +{ + /** + * Provides flexible way to build lease manager constructor parameters. + * For the actual creation of lease manager instance, delegates to lease manager factory. + */ + interface LeaseStoreManagerBuilderDefinition { + LeaseStoreManagerBuilderDefinition withLeaseContextClient(ChangeFeedContextClient leaseContextClient); + + LeaseStoreManagerBuilderDefinition withLeasePrefix(String leasePrefix); + + LeaseStoreManagerBuilderDefinition withLeaseCollectionLink(CosmosContainer leaseCollectionLink); + + LeaseStoreManagerBuilderDefinition withRequestOptionsFactory(RequestOptionsFactory requestOptionsFactory); + + LeaseStoreManagerBuilderDefinition withHostName(String hostName); + + Mono build(); + } + + static LeaseStoreManagerBuilderDefinition Builder() { + return new LeaseStoreManagerImpl(); + } + + /** + * @return List of all leases. + */ + Flux getAllLeases(); + + /** + * @return all leases owned by the current host. + */ + Flux getOwnedLeases(); + + /** + * Checks whether the lease exists and creates it if it does not exist. + * + * @param leaseToken the partition to work on. + * @param continuationToken the continuation token if it exists. + * @return the lease. + */ + Mono createLeaseIfNotExist(String leaseToken, String continuationToken); + + /** + * Delete the lease. + * + * @param lease the lease to remove. + * @return a representation of the deferred computation of this call. + */ + Mono delete(Lease lease); + + /** + * Acquire ownership of the lease. + * + * @param lease the Lease to acquire. + * @return the updated acquired lease. + */ + Mono acquire(Lease lease); + + /** + * Release ownership of the lease. + * + * @param lease the lease to acquire. + * @return a representation of the deferred computation of this call. + */ + Mono release(Lease lease); + + /** + * Renew the lease. Leases are periodically renewed to prevent expiration. + * + * @param lease the Lease to renew. + * @return the updated renewed lease. + */ + Mono renew(Lease lease); + + /** + * Replace properties from the specified lease. + * + * @param leaseToUpdatePropertiesFrom the Lease containing new properties. + * @return the updated lease. + */ + Mono updateProperties(Lease leaseToUpdatePropertiesFrom); + + /** + * Checkpoint the lease. + * + * @param lease the Lease to renew. + * @param continuationToken the continuation token. + * @return the updated renewed lease. + */ + Mono checkpoint(Lease lease, String continuationToken); + + /** + * @return true if the lease store is initialized. + */ + Mono isInitialized(); + + /** + * Mark the store as initialized. + * + * @return true if marked as initialized. + */ + Mono markInitialized(); + + /** + * Places a lock on the lease store for initialization. Only one process may own the store for the lock time. + * + * @param lockExpirationTime the time for the lock to expire. + * @return true if the lock was acquired, false otherwise. + */ + Mono acquireInitializationLock(Duration lockExpirationTime); + + /** + * Releases the lock one the lease store for initialization. + * + * @return true if the lock was acquired and was relesed, false if the lock was not acquired. + */ + Mono releaseInitializationLock(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManagerSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManagerSettings.java new file mode 100644 index 0000000000000..6c474db4755ee --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManagerSettings.java @@ -0,0 +1,63 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.CosmosContainer; + +/** + * Captures LeaseStoreManager settings. + */ +public class LeaseStoreManagerSettings { + String containerNamePrefix; + + CosmosContainer leaseCollectionLink; + + String hostName; + + public String getContainerNamePrefix() { + return this.containerNamePrefix; + } + + public LeaseStoreManagerSettings withContainerNamePrefix(String containerNamePrefix) { + this.containerNamePrefix = containerNamePrefix; + return this; + } + + public CosmosContainer getLeaseCollectionLink() { + return this.leaseCollectionLink; + } + + public LeaseStoreManagerSettings withLeaseCollectionLink(CosmosContainer collectionLink) { + this.leaseCollectionLink = collectionLink; + return this; + } + + public String getHostName() { + return this.hostName; + } + + public LeaseStoreManagerSettings withHostName(String hostName) { + this.hostName = hostName; + return this; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionCheckpointer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionCheckpointer.java new file mode 100644 index 0000000000000..4982f8eed93da --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionCheckpointer.java @@ -0,0 +1,38 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Mono; + +/** + * Checkpoint the given partition up to the given continuation token. + */ +public interface PartitionCheckpointer { + /** + * Checkpoints the given partition up to the given continuation token. + * + * @param сontinuationToken the continuation token. + * @return a deferred operation of this call. + */ + Mono checkpointPartition(String сontinuationToken); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionController.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionController.java new file mode 100644 index 0000000000000..3b434e9830fb0 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionController.java @@ -0,0 +1,52 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Interface for the partition controller. + */ +public interface PartitionController { + /** + * Add or update lease item. + * + * @return a representation of the deferred computation of this call. + */ + Mono addOrUpdateLease(Lease lease); + + /** + * Initialize and start the partition controller thread. + * + * @return a representation of the deferred computation of this call. + */ + Mono initialize(); + + /** + * Shutdown partition controller thread. + * + * @return a representation of the deferred computation of this call. + */ + Mono shutdown(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancer.java new file mode 100644 index 0000000000000..ea467404242ae --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancer.java @@ -0,0 +1,44 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Mono; + +/** + * Interface for a partition load balancer. + */ +public interface PartitionLoadBalancer { + /** + * Starts the load balancer. + * + * @return a representation of the deferred computation of this call. + */ + Mono start(); + + /** + * Stops the load balancer. + * + * @return a representation of the deferred computation of this call. + */ + Mono stop(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancingStrategy.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancingStrategy.java new file mode 100644 index 0000000000000..6fac50cc661bd --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancingStrategy.java @@ -0,0 +1,97 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.ChangeFeedProcessorOptions; + +import java.util.List; + +/** + * A strategy defines which leases should be taken by the current host in a certain moment. + *

+ * It can set new {@link Lease} getProperties() for all returned leases if needed, including currently owned leases. + * Example + *

+ * {@code
+ *  public class CustomStrategy : PartitionLoadBalancingStrategy
+ *  {
+ *      private String hostName;
+ *      private String hostVersion;
+ *      private Duration leaseExpirationInterval;
+ *
+ *      private final String VersionPropertyKey = "version";
+ *
+ *      public List selectLeasesToTake(List allLeases)
+ *      {
+ *          var takenLeases = this.findLeasesToTake(allLeases);
+ *          foreach (var lease in takenLeases)
+ *          {
+ *              lease.Properties[VersionPropertyKey] = this.hostVersion;
+ *          }
+ *
+ *          return takenLeases;
+ *      }
+ *
+ *      private List findLeasesToTake(List allLeases)
+ *      {
+ *          List takenLeases = new List();
+ *          foreach (var lease in allLeases)
+ *          {
+ *              if (string.IsNullOrWhiteSpace(lease.Owner) || this.IsExpired(lease))
+ *              {
+ *                  takenLeases.Add(lease);
+ *              }
+ *
+ *              if (lease.Owner != this.hostName)
+ *              {
+ *                  var ownerVersion = lease.Properties[VersionPropertyKey];
+ *                  if (ownerVersion < this.hostVersion)
+ *                  {
+ *                      takenLeases.Add(lease);
+ *                  }
+ *
+ *                  // more logic for leases owned by other hosts
+ *              }
+ *          }
+ *
+ *          return takenLeases;
+ *      }
+ *
+ *      private boolean isExpired(Lease lease)
+ *      {
+ *          return lease.Timestamp.ToUniversalTime() + this.leaseExpirationInterval < DateTime.UtcNow;
+ *      }
+ *  } * }
+ * 
+ * + */ +public interface PartitionLoadBalancingStrategy { + /** + * Select leases that should be taken for processing. + * This method will be called periodically with {@link ChangeFeedProcessorOptions} getLeaseAcquireInterval(). + + * @param allLeases All leases. + * @return Leases that should be taken for processing by this host. + */ + List selectLeasesToTake(List allLeases); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionManager.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionManager.java new file mode 100644 index 0000000000000..7552e4d87d7bf --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionManager.java @@ -0,0 +1,44 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Mono; + +/** + * Interface PartitionManager. + */ +public interface PartitionManager { + /** + * starts the partition manager. + * + * @return a representation of the deferred computation of this call. + */ + Mono start(); + + /** + * Stops the partition manager. + * + * @return a representation of the deferred computation of this call. + */ + Mono stop(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessor.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessor.java new file mode 100644 index 0000000000000..6661a50359c45 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessor.java @@ -0,0 +1,51 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedObserverContext; +import reactor.core.publisher.Mono; + +/** + * Provides an API to run continious processing on a single partition of some resource. + *

+ * Created by {@link PartitionProcessorFactory}.create() after some lease is acquired by the current host. + * Processing can perform the following tasks in a loop: + * 1. Read some data from the resource partition. + * 2. Handle possible problems with the read. + * 3. Pass the obtained data to an observer by calling {@link ChangeFeedObserver}.processChangesAsync{} with the context {@link ChangeFeedObserverContext}. + */ +public interface PartitionProcessor { + /** + * Perform partition processing. + * + * @param cancellationToken the cancellation token. + * @return a representation of the deferred computation of this call. + */ + Mono run(CancellationToken cancellationToken); + + /** + * @return the inner exception if any, otherwise null. + */ + RuntimeException getResultException(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessorFactory.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessorFactory.java new file mode 100644 index 0000000000000..eca114f1e4d9a --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessorFactory.java @@ -0,0 +1,39 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; + +/** + * Factory class used to create instance(s) of {@link PartitionProcessor}. + */ +public interface PartitionProcessorFactory { + /** + * Creates an instance of a {@link PartitionProcessor}. + * + * @param lease the lease to be used for partition processing. + * @param changeFeedObserver the observer instace to be used. + * @return an instance of {@link PartitionProcessor}. + */ + PartitionProcessor create(Lease lease, ChangeFeedObserver changeFeedObserver); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisor.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisor.java new file mode 100644 index 0000000000000..863636ae7a78c --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisor.java @@ -0,0 +1,43 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Mono; + +/** + * Interface for the partition supervisor. + */ +public interface PartitionSupervisor { + /** + * Runs the task. + * + * @param cancellationToken the cancellation token. + * @return a deferred operation of this call. + */ + Mono run(CancellationToken cancellationToken); + + /** + * @return the inner exception if any, otherwise null. + */ + RuntimeException getResultException(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisorFactory.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisorFactory.java new file mode 100644 index 0000000000000..dd17035a5bcb7 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisorFactory.java @@ -0,0 +1,35 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +/** + * Interface for the partition supervisor factory. + */ +public interface PartitionSupervisorFactory { + /** + * + * @param lease the lease. + * @return an instance of {@link PartitionSupervisor}. + */ + PartitionSupervisor create(Lease lease); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSynchronizer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSynchronizer.java new file mode 100644 index 0000000000000..3dac20d777a32 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSynchronizer.java @@ -0,0 +1,46 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Read DocDB partitions and create leases if they do not exist. + */ +public interface PartitionSynchronizer { + /** + * Creates missing leases. + * + * @return a deferred computation of this operation. + */ + Mono createMissingLeases(); + + /** + * Handles partition slip. + * + * @param lease the lease. + * @return the split partition documents. + */ + Flux splitPartition(Lease lease); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ProcessorSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ProcessorSettings.java new file mode 100644 index 0000000000000..4b3dd5a009594 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ProcessorSettings.java @@ -0,0 +1,116 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.CosmosContainer; + +import java.time.Duration; +import java.time.ZonedDateTime; + +/** + * Implementation for the partition processor settings. + */ +public class ProcessorSettings { + private CosmosContainer collectionSelfLink; + private String partitionKeyRangeId; + private Integer maxItemCount; + private Duration feedPollDelay; + private String startContinuation; + private ZonedDateTime startTime; +// private String sessionToken; + + public CosmosContainer getCollectionSelfLink() { + return this.collectionSelfLink; + } + + public ProcessorSettings withCollectionLink(CosmosContainer collectionLink) { + this.collectionSelfLink = collectionLink; + return this; + } + + public String getPartitionKeyRangeId() { + return this.partitionKeyRangeId; + } + + public ProcessorSettings withPartitionKeyRangeId(String partitionKeyRangeId) { + this.partitionKeyRangeId = partitionKeyRangeId; + return this; + } + + public int getMaxItemCount() { + return this.maxItemCount; + } + + public ProcessorSettings withMaxItemCount(int maxItemCount) { + this.maxItemCount = maxItemCount; + return this; + } + + public Duration getFeedPollDelay() { + return this.feedPollDelay; + } + + public ProcessorSettings withFeedPollDelay(Duration feedPollDelay) { + this.feedPollDelay = feedPollDelay; + return this; + } + + public String getStartContinuation() { + return this.startContinuation; + } + + public ProcessorSettings withStartContinuation(String startContinuation) { + this.startContinuation = startContinuation; + return this; + } + + private boolean startFromBeginning; + + public boolean isStartFromBeginning() { + return this.startFromBeginning; + } + + public ProcessorSettings withStartFromBeginning(boolean startFromBeginning) { + this.startFromBeginning = startFromBeginning; + return this; + } + + public ZonedDateTime getStartTime() { + return this.startTime; + } + + public ProcessorSettings withStartTime(ZonedDateTime startTime) { + this.startTime = startTime; + return this; + } + + // This is not currently supported in Java implementation. +// public String getSessionToken() { +// return this.sessionToken; +// } +// +// public ProcessorSettings withSessionToken(String sessionToken) { +// this.sessionToken = sessionToken; +// return this; +// } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingPartitionWork.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingPartitionWork.java new file mode 100644 index 0000000000000..c40341a47fa1c --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingPartitionWork.java @@ -0,0 +1,38 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +/** + * Interface for remaining partition work. + */ +public interface RemainingPartitionWork { + /** + * @return the partition key range ID for which the remaining work is calculated. + */ + String getPartitionKeyRangeId(); + + /** + * @return the ammount of documents remaining to be processed. + */ + long getRemainingWork(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingWorkEstimator.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingWorkEstimator.java new file mode 100644 index 0000000000000..f5d02380ef26b --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingWorkEstimator.java @@ -0,0 +1,46 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Used to estimate the pending work remaining to be read in the Change Feed. Calculates the sum of pending work + * based on the difference between the latest status of the feed and the status of each existing lease. + */ +public interface RemainingWorkEstimator { + /** + * Calculates an estimate of the pending work remaining to be read in the Change Feed in amount of documents in the whole collection. + * + * @return an estimation of pending work in amount of documents. + */ + Mono getEstimatedRemainingWork(); + + /** + * Calculates an estimate of the pending work remaining to be read in the Change Feed in amount of documents per partition. + * + * @return an estimation of pending work in amount of documents per partitions. + */ + Flux getEstimatedRemainingWorkPerPartition(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RequestOptionsFactory.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RequestOptionsFactory.java new file mode 100644 index 0000000000000..09abe1efcc80a --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RequestOptionsFactory.java @@ -0,0 +1,37 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.RequestOptions; + +/** + * Defines request options for lease requests to use with {@link LeaseStoreManager}. + */ +public interface RequestOptionsFactory { + + CosmosItemRequestOptions createRequestOptions(Lease lease); + + FeedOptions createFeedOptions(); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLease.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLease.java new file mode 100644 index 0000000000000..5f802baed0812 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLease.java @@ -0,0 +1,242 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmos.changefeed.internal.Constants; + +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * Document service lease. + */ +public class ServiceItemLease implements Lease { + private static final ZonedDateTime UNIX_START_TIME = ZonedDateTime.parse("1970-01-01T00:00:00.0Z[UTC]"); + + // TODO: add JSON annotations and rename the properties. + private String id; + private String _etag; + private String LeaseToken; + private String Owner; + private String ContinuationToken; + + private Map properties; + private String timestamp; // ExplicitTimestamp + private String _ts; + + public ServiceItemLease() { + ZonedDateTime currentTime = ZonedDateTime.now(ZoneId.of("UTC")); + this.timestamp = currentTime.toString(); + this._ts = String.valueOf(currentTime.getSecond()); + this.properties = new HashMap<>(); + } + + public ServiceItemLease(ServiceItemLease other) + { + this.id = other.id; + this._etag = other._etag; + this.LeaseToken = other.LeaseToken; + this.Owner = other.Owner; + this.ContinuationToken = other.ContinuationToken; + this.properties = other.properties; + this.timestamp = other.timestamp; + this._ts = other._ts; + } + + @Override + public String getId() { + return this.id; + } + + public ServiceItemLease withId(String id) { + this.id = id; + return this; + } + + @JsonIgnore + public String getEtag() { + return this._etag; + } + + public ServiceItemLease withEtag(String etag) { + this._etag = etag; + return this; + } + + @JsonProperty("LeaseToken") + public String getLeaseToken() { + return this.LeaseToken; + } + + public ServiceItemLease withLeaseToken(String leaseToken) { + this.LeaseToken = leaseToken; + return this; + } + + @JsonProperty("Owner") + @Override + public String getOwner() { + return this.Owner; + } + + public ServiceItemLease withOwner(String owner) { + this.Owner = owner; + return this; + } + + @JsonProperty("ContinuationToken") + @Override + public String getContinuationToken() { + return this.ContinuationToken; + } + + @Override + public void setContinuationToken(String continuationToken) { + this.withContinuationToken(continuationToken); + } + + public ServiceItemLease withContinuationToken(String continuationToken) { + this.ContinuationToken = continuationToken; + return this; + } + + @Override + public Map getProperties() { + return this.properties; + } + + @Override + public void setOwner(String owner) { + this.withOwner(owner); + } + + @Override + public void setTimestamp(ZonedDateTime timestamp) { + this.withTimestamp(timestamp); + } + + public void setTimestamp(Date date) { + this.withTimestamp(date.toInstant().atZone(ZoneId.systemDefault())); + } + + public void setTimestamp(Date date, ZoneId zoneId) { + this.withTimestamp(date.toInstant().atZone(zoneId)); + } + + @Override + public void setId(String id) { + this.withId(id); + } + + @Override + public void setConcurrencyToken(String concurrencyToken) { + this.withEtag(concurrencyToken); + } + + public ServiceItemLease withConcurrencyToken(String concurrencyToken) { + return this.withEtag(concurrencyToken); + } + + @Override + public void setProperties(Map properties) { + this.withProperties(properties); + } + + public ServiceItemLease withProperties(Map properties) { + this.properties = properties; + return this; + } + + @JsonIgnore + public String getTs() { + return this._ts; + } + + public ServiceItemLease withTs(String ts) { + this._ts = ts; + return this; + } + + @JsonProperty("timestamp") + @Override + public String getTimestamp() { + if (this.timestamp == null) { + return UNIX_START_TIME.plusSeconds(Long.parseLong(this.getTs())).toString(); + } + return this.timestamp; + } + + public ServiceItemLease withTimestamp(ZonedDateTime timestamp) { + this.timestamp = timestamp.toString(); + return this; + } + + @JsonIgnore + public String getExplicitTimestamp() { + return this.timestamp; + } + + @JsonIgnore + @Override + public String getConcurrencyToken() { + return this.getEtag(); + } + + public static ServiceItemLease fromDocument(Document document) { + return new ServiceItemLease() + .withId(document.getId()) + .withEtag(document.getETag()) + .withTs(document.getString(Constants.Properties.LAST_MODIFIED)) + .withOwner(document.getString("Owner")) + .withLeaseToken(document.getString("LeaseToken")) + .withContinuationToken(document.getString("ContinuationToken")); + } + + public static ServiceItemLease fromDocument(CosmosItemSettings document) { + return new ServiceItemLease() + .withId(document.getId()) + .withEtag(document.getETag()) + .withTs(document.getString(Constants.Properties.LAST_MODIFIED)) + .withOwner(document.getString("Owner")) + .withLeaseToken(document.getString("LeaseToken")) + .withContinuationToken(document.getString("ContinuationToken")); + } + + @Override + public String toString() { + return String.format( + "%s Owner='%s' Continuation=%s Timestamp(local)=%s Timestamp(server)=%s", + this.getId(), + this.getOwner(), + this.getContinuationToken(), + this.getTimestamp(), + UNIX_START_TIME.plusSeconds(Long.parseLong(this.getTs()))); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLeaseUpdater.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLeaseUpdater.java new file mode 100644 index 0000000000000..32f2141193904 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLeaseUpdater.java @@ -0,0 +1,37 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed; + +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmosdb.RequestOptions; +import reactor.core.publisher.Mono; + +import java.util.function.Function; + +/** + * Interface for service lease updater. + */ +public interface ServiceItemLeaseUpdater { + Mono updateLease(Lease cachedLease, CosmosItem itemLink, CosmosItemRequestOptions requestOptions, Function updateLease); +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/LeaseLostException.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/LeaseLostException.java new file mode 100644 index 0000000000000..ff9b536605e3d --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/LeaseLostException.java @@ -0,0 +1,109 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.exceptions; + +import com.microsoft.azure.cosmos.changefeed.Lease; + +/** + * Exception occurred when lease is lost, that would typically happen when it is taken by another host. + * Other cases: communication failure, number of retries reached, lease not found. + */ +public class LeaseLostException extends RuntimeException { + private static final String DEFAULT_MESSAGE = "The lease was lost."; + + private Lease lease; + private boolean isGone; + + /** + * Initializes a new instance of the @link LeaseLostException} class. + */ + public LeaseLostException() + { + } + + /** + * Initializes a new instance of the @link LeaseLostException} class using the specified lease. + * + * @param lease an instance of a lost lease. + */ + public LeaseLostException(Lease lease) + { + super(DEFAULT_MESSAGE); + this.lease = lease; + } + + /** + * Initializes a new instance of the @link LeaseLostException} class using error message. + * + * @param message the exception error message. + */ + public LeaseLostException(String message) + { + super(message); + } + + /** + * Initializes a new instance of the @link LeaseLostException} class using error message and inner exception. + * + * @param message the exception error message. + * @param innerException the inner exception. + * + */ + public LeaseLostException(String message, Exception innerException) + { + super(message, innerException.getCause()); + } + + /** + * Initializes a new instance of the @link LeaseLostException} class using the specified lease, inner exception, + * and a flag indicating whether lease is gone.. + * + * @param lease an instance of a lost lease. + * @param innerException the inner exception. + * @param isGone true if lease doesn't exist. + */ + public LeaseLostException(Lease lease, Exception innerException, boolean isGone) + { + super(DEFAULT_MESSAGE, innerException.getCause()); + this.lease = lease; + this.isGone = isGone; + } + + /** + * Gets the lost lease. + * + * @return the lost lease. + */ + public Lease getLease() { + return this.lease; + } + + /** + * Gets a value indicating whether lease doesn't exist. + * + * @return true if lease is gone. + */ + public boolean isGone() { + return this.isGone; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/ObserverException.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/ObserverException.java new file mode 100644 index 0000000000000..c10b1cc403eb6 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/ObserverException.java @@ -0,0 +1,39 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.exceptions; + +/** + * Exception occurred when an operation in a ChangeFeedObserver is running and throws by user code. + */ +public class ObserverException extends RuntimeException { + private static final String DefaultMessage = "Exception has been thrown by the Observer."; + + /** + * Initializes a new instance of the {@link ObserverException} class using the specified internal exception. + * + * @param originalException {@link Exception} thrown by the user code. + */ + public ObserverException(Exception originalException) { + super(DefaultMessage, originalException.getCause()); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionException.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionException.java new file mode 100644 index 0000000000000..137e55e15f06e --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionException.java @@ -0,0 +1,62 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.exceptions; + +/** + * General exception occurred during partition processing. + */ +public class PartitionException extends RuntimeException { + private String lastContinuation; + + /** + * Initializes a new instance of the {@link PartitionException} class using error message and last continuation token. + * @param message the exception error message. + * @param lastContinuation the request continuation token. + */ + public PartitionException(String message, String lastContinuation) { + super(message); + this.lastContinuation = lastContinuation; + } + + /** + * Initializes a new instance of the {@link PartitionException} class using error message, the last continuation + * token and the inner exception. + * + * @param message the exception error message. + * @param lastContinuation the request continuation token. + * @param innerException the inner exception. + */ + public PartitionException(String message, String lastContinuation, Exception innerException) { + super(message, innerException.getCause()); + this.lastContinuation = lastContinuation; + } + + /** + * Gets the value of request continuation token. + * + * @return the value of request continuation token. + */ + public String getLastContinuation() { + return this.lastContinuation; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionNotFoundException.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionNotFoundException.java new file mode 100644 index 0000000000000..c0d95bc0bbad2 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionNotFoundException.java @@ -0,0 +1,50 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.exceptions; + +/** + * Exception occurred when partition wasn't found. + */ +public class PartitionNotFoundException extends PartitionException { + + /** + * Initializes a new instance of the {@link PartitionNotFoundException} class using error message and last continuation token. + * @param message the exception error message. + * @param lastContinuation the request continuation token. + */ + public PartitionNotFoundException(String message, String lastContinuation) { + super(message, lastContinuation); + } + + /** + * Initializes a new instance of the {@link PartitionNotFoundException} class using error message, the last continuation + * token and the inner exception. + * + * @param message the exception error message. + * @param lastContinuation the request continuation token. + * @param innerException the inner exception. + */ + public PartitionNotFoundException(String message, String lastContinuation, Exception innerException) { + super(message, lastContinuation, innerException); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionSplitException.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionSplitException.java new file mode 100644 index 0000000000000..6a0d29bba56bd --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionSplitException.java @@ -0,0 +1,49 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.exceptions; + +/** + * Exception occurred during partition split. + */ +public class PartitionSplitException extends PartitionException { + /** + * Initializes a new instance of the {@link PartitionSplitException} class using error message and last continuation token. + * @param message the exception error message. + * @param lastContinuation the request continuation token. + */ + public PartitionSplitException(String message, String lastContinuation) { + super(message, lastContinuation); + } + + /** + * Initializes a new instance of the {@link PartitionSplitException} class using error message, the last continuation + * token and the inner exception. + * + * @param message the exception error message. + * @param lastContinuation the request continuation token. + * @param innerException the inner exception. + */ + public PartitionSplitException(String message, String lastContinuation, Exception innerException) { + super(message, lastContinuation, innerException); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/TaskCancelledException.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/TaskCancelledException.java new file mode 100644 index 0000000000000..0bcb50636f4ad --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/TaskCancelledException.java @@ -0,0 +1,37 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.exceptions; + +/** + * Exception occurred when an operation in a ChangeFeedObserver was canceled. + */ +public class TaskCancelledException extends RuntimeException { + private static final String DefaultMessage = "Operations were canceled."; + + /** + * Initializes a new instance of the {@link TaskCancelledException} class. + */ + public TaskCancelledException() { + super(DefaultMessage); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/AutoCheckpointer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/AutoCheckpointer.java new file mode 100644 index 0000000000000..e55a18a2d62f8 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/AutoCheckpointer.java @@ -0,0 +1,94 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedObserverCloseReason; +import com.microsoft.azure.cosmos.ChangeFeedObserverContext; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.changefeed.CheckpointFrequency; + +import java.time.Duration; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.List; + +/** + * Auto check-pointer implementation for {@link ChangeFeedObserver}. + */ +public class AutoCheckpointer implements ChangeFeedObserver { + private final CheckpointFrequency checkpointFrequency; + private final ChangeFeedObserver observer; + private int processedDocCount; + private ZonedDateTime lastCheckpointTime; + + public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedObserver observer) { + if (checkpointFrequency == null) throw new IllegalArgumentException("checkpointFrequency"); + if (observer == null) throw new IllegalArgumentException("observer"); + + this.checkpointFrequency = checkpointFrequency; + this.observer = observer; + this.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); + } + + @Override + public void open(ChangeFeedObserverContext context) { + this.observer.open(context); + } + + @Override + public void close(ChangeFeedObserverContext context, ChangeFeedObserverCloseReason reason) { + this.observer.close(context, reason); + } + + @Override + public void processChanges(ChangeFeedObserverContext context, List docs) { + this.observer.processChanges(context, docs); + this.processedDocCount ++; + + if (this.isCheckpointNeeded()) { + context.checkpoint().block(); + this.processedDocCount = 0; + this.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); + } + } + + private boolean isCheckpointNeeded() { + if (this.checkpointFrequency.getProcessedDocumentCount() == 0 && this.checkpointFrequency.getTimeInterval() == null) { + return true; + } + + if (this.processedDocCount >= this.checkpointFrequency.getProcessedDocumentCount()) { + return true; + } + + Duration delta = Duration.between(this.lastCheckpointTime, ZonedDateTime.now(ZoneId.of("UTC"))); + + if (delta.compareTo(this.checkpointFrequency.getTimeInterval()) >= 0) { + return true; + } + + return false; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/BootstrapperImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/BootstrapperImpl.java new file mode 100644 index 0000000000000..cbe42f6234422 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/BootstrapperImpl.java @@ -0,0 +1,96 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.Bootstrapper; +import com.microsoft.azure.cosmos.changefeed.LeaseStore; +import com.microsoft.azure.cosmos.changefeed.PartitionSynchronizer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +/** + * Implementation for the bootstrapping interface. + */ +public class BootstrapperImpl implements Bootstrapper { + private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); + private final PartitionSynchronizer synchronizer; + private final LeaseStore leaseStore; + private final Duration lockTime; + private final Duration sleepTime; + + public BootstrapperImpl(PartitionSynchronizer synchronizer, LeaseStore leaseStore, Duration lockTime, Duration sleepTime) + { + if (synchronizer == null) throw new IllegalArgumentException("synchronizer"); + if (leaseStore == null) throw new IllegalArgumentException("leaseStore"); + if (lockTime == null || lockTime.isNegative() || lockTime.isZero()) throw new IllegalArgumentException("lockTime should be non-null and positive"); + if (sleepTime == null || sleepTime.isNegative() || sleepTime.isZero()) throw new IllegalArgumentException("sleepTime should be non-null and positive"); + + this.synchronizer = synchronizer; + this.leaseStore = leaseStore; + this.lockTime = lockTime; + this.sleepTime = sleepTime; + } + + @Override + public Mono initialize() { + BootstrapperImpl self = this; + + return Mono.fromRunnable( () -> { + while (true) { + boolean initialized = self.leaseStore.isInitialized().block(); + + if (initialized) break; + + boolean isLockAcquired = self.leaseStore.acquireInitializationLock(self.lockTime).block(); + + try { + if (!isLockAcquired) { + logger.info("Another instance is initializing the store"); + try { + Thread.sleep(self.sleepTime.toMillis()); + } catch (InterruptedException ex) { + logger.warn("Unexpected exception caught", ex); + } + continue; + } + + logger.info("Initializing the store"); + self.synchronizer.createMissingLeases().block(); + self.leaseStore.markInitialized().block(); + + } catch (RuntimeException ex) { + break; + } finally { + if (isLockAcquired) { + self.leaseStore.releaseInitializationLock().block(); + } + } + } + + logger.info("The store is initialized"); + }); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java new file mode 100644 index 0000000000000..91d57143f7248 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java @@ -0,0 +1,174 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerResponse; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseRequestOptions; +import com.microsoft.azure.cosmos.CosmosDatabaseResponse; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemResponse; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; +import com.microsoft.azure.cosmosdb.BridgeInternal; +import com.microsoft.azure.cosmosdb.ChangeFeedOptions; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import com.microsoft.azure.cosmosdb.SqlQuerySpec; +import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Scheduler; +import reactor.core.scheduler.Schedulers; + +import java.net.URI; + +/** + * Implementation for ChangeFeedDocumentClient. + */ +public class ChangeFeedContextClientImpl implements ChangeFeedContextClient { + private final AsyncDocumentClient documentClient; + private final CosmosContainer cosmosContainer; + private Scheduler rxScheduler; + + /** + * Initializes a new instance of the {@link ChangeFeedContextClient} interface. + * @param cosmosContainer existing client. + */ + public ChangeFeedContextClientImpl(CosmosContainer cosmosContainer) + { + if (cosmosContainer == null) { + throw new IllegalArgumentException("cosmosContainer"); + } + + this.cosmosContainer = cosmosContainer; + this.documentClient = CosmosContainer.getContextClient(cosmosContainer); + this.rxScheduler = Schedulers.elastic(); + } + + /** + * Initializes a new instance of the {@link ChangeFeedContextClient} interface. + * @param cosmosContainer existing client. + * @param rxScheduler the RX Java scheduler to observe on. + */ + public ChangeFeedContextClientImpl(CosmosContainer cosmosContainer, Scheduler rxScheduler) + { + if (cosmosContainer == null) { + throw new IllegalArgumentException("cosmosContainer"); + } + + this.cosmosContainer = cosmosContainer; + this.documentClient = CosmosContainer.getContextClient(cosmosContainer); + this.rxScheduler = rxScheduler; + + } + + @Override + public Flux> readPartitionKeyRangeFeed(String partitionKeyRangesOrCollectionLink, FeedOptions feedOptions) { + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable( + this.documentClient.readPartitionKeyRanges(partitionKeyRangesOrCollectionLink, feedOptions))) + .subscribeOn(this.rxScheduler); + } + + @Override + public Flux> createDocumentChangeFeedQuery(CosmosContainer collectionLink, ChangeFeedOptions feedOptions) { + return collectionLink.queryChangeFeedItems(feedOptions) + .subscribeOn(this.rxScheduler); + } + + @Override + public Mono readDatabase(CosmosDatabase database, CosmosDatabaseRequestOptions options) { + return database.read() + .subscribeOn(this.rxScheduler); + } + + @Override + public Mono readContainer(CosmosContainer containerLink, CosmosContainerRequestOptions options) { + return containerLink.read(options) + .subscribeOn(this.rxScheduler); + } + + @Override + public Mono createItem(CosmosContainer containerLink, Object document, CosmosItemRequestOptions options, boolean disableAutomaticIdGeneration) { + return containerLink.createItem(document, options) + .subscribeOn(this.rxScheduler); + } + + @Override + public Mono deleteItem(CosmosItem itemLink, CosmosItemRequestOptions options) { + return itemLink.delete(options) + .subscribeOn(this.rxScheduler); + } + + @Override + public Mono replaceItem(CosmosItem itemLink, Object document, CosmosItemRequestOptions options) { + return itemLink.replace(document, options) + .subscribeOn(this.rxScheduler); + } + + @Override + public Mono readItem(CosmosItem itemLink, CosmosItemRequestOptions options) { + return itemLink.read(options) + .subscribeOn(this.rxScheduler); + } + + @Override + public Flux> queryItems(CosmosContainer containerLink, SqlQuerySpec querySpec, FeedOptions options) { + return containerLink.queryItems(querySpec, options) + .subscribeOn(this.rxScheduler); + } + + @Override + public URI getServiceEndpoint() { + return documentClient.getServiceEndpoint(); + } + + @Override + public Mono readContainerSettings(CosmosContainer containerLink, CosmosContainerRequestOptions options) { + return null; + } + + @Override + public CosmosContainer getContainerClient() { + return this.cosmosContainer; + } + + @Override + public CosmosDatabase getDatabaseClient() { + return this.cosmosContainer.getDatabase(); + } + + @Override + public void close() { + + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedHelper.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedHelper.java new file mode 100644 index 0000000000000..4935852e667fc --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedHelper.java @@ -0,0 +1,209 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerResponse; +import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; +import com.microsoft.azure.cosmos.changefeed.ContainerConnectionInfo; +import reactor.core.publisher.Mono; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Map; + +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.Paths.COLLECTIONS_PATH_SEGMENT; +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.Paths.DATABASES_ROOT; +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.Paths.DOCUMENTS_PATH_SEGMENT; + +/** + * Implement static methods used for various simple transformations and tasks. + */ +public class ChangeFeedHelper { + private static final String DEFAULT_USER_AGENT_SUFFIX = "changefeed-2.2.6"; + + public static final int HTTP_STATUS_CODE_NOT_FOUND = 404; + public static final int HTTP_STATUS_CODE_CONFLICT = 409; + public static final int HTTP_STATUS_CODE_GONE = 410; + public static final int HTTP_STATUS_CODE_PRECONDITION_FAILED = 412; + public static final int HTTP_STATUS_CODE_TOO_MANY_REQUESTS = 429; + public static final int HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR = 500; + + public static ContainerConnectionInfo canonicalize(ContainerConnectionInfo leaseCollectionLocation) { + ContainerConnectionInfo result = leaseCollectionLocation; + + if (leaseCollectionLocation == null || leaseCollectionLocation.getConnectionPolicy() == null) { + throw new IllegalArgumentException("leaseCollectionLocation"); + } + if (leaseCollectionLocation.getConnectionPolicy().getUserAgentSuffix() == null + || leaseCollectionLocation.getConnectionPolicy().getUserAgentSuffix().isEmpty()) { + result = new ContainerConnectionInfo(leaseCollectionLocation); + result.getConnectionPolicy().setUserAgentSuffix(DEFAULT_USER_AGENT_SUFFIX); + } + + return result; + } + + public static String getDatabaseLink(String databaseName) { + return String.format("/dbs/%s", databaseName); + } + + public static String getCollectionLink(String databaseName, String collectionName) { + return String.format("/dbs/%s/colls/%s", databaseName, collectionName); + } + + public static String getCollectionSelfLink(ContainerConnectionInfo collectionInfo) + { + return UriFactory.createDocumentCollectionUri(collectionInfo.getDatabaseName(), collectionInfo.getContainerName()); + } + + public static class UriFactory { + /** + * A database link in the format of "dbs/{0}/". + * + * @param databaseId the database ID. + * @return a database link in the format of "dbs/{0}/". + */ + public static String createDatabaseUri(String databaseId) { + String path = String.format("%s/%s/", DATABASES_ROOT, databaseId); + + return getUrlPath(path); + } + + /** + * A collection link in the format of "dbs/{0}/colls/{1}/". + * + * @param databaseId the database ID. + * @param collectionId the collection ID. + * @return a collection link in the format of "dbs/{0}/colls/{1}/". + */ + public static String createDocumentCollectionUri(String databaseId, String collectionId) { + String path = String.format("%s/%s/%s/%s/",DATABASES_ROOT, databaseId, + COLLECTIONS_PATH_SEGMENT, collectionId); + + return getUrlPath(path); + } + + /** + * A document link in the format of "dbs/{0}/colls/{1}/docs/{2}/". + * + * @param databaseId the database ID. + * @param collectionId the collection ID. + * @param documentId the document ID. + * @return a document link in the format of "dbs/{0}/colls/{1}/docs/{2}/". + */ + public static String createDocumentUri(String databaseId, String collectionId, String documentId) { + String path = String.format("%s/%s/%s/%s/%s/%s/",DATABASES_ROOT, databaseId, + COLLECTIONS_PATH_SEGMENT, collectionId, DOCUMENTS_PATH_SEGMENT, documentId); + + return getUrlPath(path); + } + + public static String getUrlPath(String path) { + try { + URI uri = new URI( + "http", + "localhost", + path, + null + ); + + URL url = uri.toURL(); + + return url.getPath().substring(1); + } catch (URISyntaxException | MalformedURLException uriEx) {return null;} + } + } + + /** + * Copied from com.microsoft.azure.cosmosdb.internal.Paths. + */ + public static class Paths { + static final String ROOT = "/"; + + public static final String DATABASES_PATH_SEGMENT = "dbs"; + public static final String DATABASES_ROOT = ROOT + DATABASES_PATH_SEGMENT; + + public static final String USERS_PATH_SEGMENT = "users"; + public static final String PERMISSIONS_PATH_SEGMENT = "permissions"; + public static final String COLLECTIONS_PATH_SEGMENT = "colls"; + public static final String STORED_PROCEDURES_PATH_SEGMENT = "sprocs"; + public static final String TRIGGERS_PATH_SEGMENT = "triggers"; + public static final String USER_DEFINED_FUNCTIONS_PATH_SEGMENT = "udfs"; + public static final String CONFLICTS_PATH_SEGMENT = "conflicts"; + public static final String DOCUMENTS_PATH_SEGMENT = "docs"; + public static final String ATTACHMENTS_PATH_SEGMENT = "attachments"; + + // /offers + public static final String OFFERS_PATH_SEGMENT = "offers"; + public static final String OFFERS_ROOT = ROOT + OFFERS_PATH_SEGMENT + "/"; + + public static final String ADDRESS_PATH_SEGMENT = "addresses"; + public static final String PARTITIONS_PATH_SEGMENT = "partitions"; + public static final String DATABASE_ACCOUNT_PATH_SEGMENT = "databaseaccount"; + public static final String TOPOLOGY_PATH_SEGMENT = "topology"; + public static final String MEDIA_PATH_SEGMENT = "media"; + public static final String MEDIA_ROOT = ROOT + MEDIA_PATH_SEGMENT; + public static final String SCHEMAS_PATH_SEGMENT = "schemas"; + public static final String PARTITION_KEY_RANGES_PATH_SEGMENT = "pkranges"; + + public static final String USER_DEFINED_TYPES_PATH_SEGMENT = "udts"; + + public static final String RID_RANGE_PATH_SEGMENT = "ridranges"; + } + + public static class KeyValuePair implements Map.Entry + { + private K key; + private V value; + + public KeyValuePair(K key, V value) + { + this.key = key; + this.value = value; + } + + public K getKey() + { + return this.key; + } + + public V getValue() + { + return this.value; + } + + public K setKey(K key) + { + return this.key = key; + } + + public V setValue(V value) + { + return this.value = value; + } + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java new file mode 100644 index 0000000000000..1dac68a5df7fb --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java @@ -0,0 +1,87 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + + +import com.microsoft.azure.cosmos.ChangeFeedObserverContext; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.changefeed.PartitionCheckpointer; +import com.microsoft.azure.cosmosdb.FeedResponse; +import reactor.core.publisher.Mono; + +/** + * Implementation for ChangeFeedObserverContext. + */ +public class ChangeFeedObserverContextImpl implements ChangeFeedObserverContext { + private final PartitionCheckpointer checkpointer; + private final String partitionKeyRangeId; + private final FeedResponse feedResponse; + private String responseContinuation; + + public ChangeFeedObserverContextImpl(String leaseToken) { + this.partitionKeyRangeId = leaseToken; + this.checkpointer = null; + this.feedResponse = null; + } + + public ChangeFeedObserverContextImpl(String leaseToken, FeedResponse feedResponse, PartitionCheckpointer checkpointer) + { + this.partitionKeyRangeId = leaseToken; + this.feedResponse = feedResponse; + this.checkpointer = checkpointer; + } + + /** + * Checkpoints progress of a stream. This method is valid only if manual checkpoint was configured. + *

+ * Client may accept multiple change feed batches to process in parallel. + * Once first N document processing was finished the client can call checkpoint on the last completed batches in the row. + * In case of automatic checkpointing this is method throws. + * + * @return a deferred computation of this call. + */ + @Override + public Mono checkpoint() { + this.responseContinuation = this.feedResponse.getResponseContinuation(); + + return this.checkpointer.checkpointPartition(this.responseContinuation); + } + + /** + * @return the id of the partition for the current event. + */ + @Override + public String getPartitionKeyRangeId() { + return this.partitionKeyRangeId; + } + + /** + * @return the response from the underlying call. + */ + @Override + public FeedResponse getFeedResponse() { + return this.feedResponse; + } + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java new file mode 100644 index 0000000000000..d7ec55ec27705 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java @@ -0,0 +1,47 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedObserverFactory; +import com.microsoft.azure.cosmos.changefeed.exceptions.ObserverException; + +/** + * Default implementation for {@link ChangeFeedObserverFactory}. + */ +public class ChangeFeedObserverFactoryImpl implements ChangeFeedObserverFactory { + private final Class observerType; + + public ChangeFeedObserverFactoryImpl(Class observerType) { + this.observerType = observerType; + } + + @Override + public ChangeFeedObserver createObserver() { + try { + return (ChangeFeedObserver) observerType.newInstance(); + } catch (IllegalAccessException | InstantiationException ex) { + throw new ObserverException(ex); + } + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java new file mode 100644 index 0000000000000..3b445ae3bf42e --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java @@ -0,0 +1,463 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedObserverFactory; +import com.microsoft.azure.cosmos.ChangeFeedProcessor; +import com.microsoft.azure.cosmos.ChangeFeedProcessorOptions; +import com.microsoft.azure.cosmos.changefeed.Bootstrapper; +import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; +import com.microsoft.azure.cosmos.changefeed.HealthMonitor; +import com.microsoft.azure.cosmos.changefeed.LeaseStoreManager; +import com.microsoft.azure.cosmos.changefeed.PartitionController; +import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancer; +import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancingStrategy; +import com.microsoft.azure.cosmos.changefeed.PartitionManager; +import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; +import com.microsoft.azure.cosmos.changefeed.PartitionProcessorFactory; +import com.microsoft.azure.cosmos.changefeed.PartitionSupervisorFactory; +import com.microsoft.azure.cosmos.changefeed.RequestOptionsFactory; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +import java.net.URI; +import java.time.Duration; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Helper class to build {@link ChangeFeedProcessor} instances + * as logical representation of the Azure Cosmos DB database service. + * + *

+ * {@code
+ *  ChangeFeedProcessor.Builder()
+ *     .withHostName(hostName)
+ *     .withFeedContainerClient(feedContainer)
+ *     .withLeaseContainerClient(leaseContainer)
+ *     .withChangeFeedObserver(SampleObserverImpl.class)
+ *     .build();
+ * }
+ * 
+ */ +public class ChangeFeedProcessorBuilderImpl implements ChangeFeedProcessor.BuilderDefinition, ChangeFeedProcessor, AutoCloseable { + private static final long DefaultUnhealthinessDuration = Duration.ofMinutes(15).toMillis(); + private final Duration sleepTime = Duration.ofSeconds(15); + private final Duration lockTime = Duration.ofSeconds(30); + + private String hostName; + private ChangeFeedContextClient feedContextClient; + private ChangeFeedProcessorOptions changeFeedProcessorOptions; + private ChangeFeedObserverFactory observerFactory; + private String databaseResourceId; + private String collectionResourceId; + private ChangeFeedContextClient leaseContextClient; + private PartitionLoadBalancingStrategy loadBalancingStrategy; + private PartitionProcessorFactory partitionProcessorFactory; + private LeaseStoreManager leaseStoreManager; + private HealthMonitor healthMonitor; + private PartitionManager partitionManager; + + private ExecutorService executorService; + + /** + * Start listening for changes asynchronously. + * + * @return a representation of the deferred computation of this call. + */ + @Override + public Mono start() { + return partitionManager.start(); + } + + /** + * Stops listening for changes asynchronously. + * + * @return a representation of the deferred computation of this call. + */ + @Override + public Mono stop() { + return partitionManager.stop(); + } + + /** + * Sets the host name. + * + * @param hostName the name to be used for the host. When using multiple hosts, each host must have a unique name. + * @return current Builder. + */ + @Override + public ChangeFeedProcessorBuilderImpl withHostName(String hostName) { + this.hostName = hostName; + return this; + } + + /** + * Sets and existing {@link CosmosContainer} to be used to read from the monitored collection. + * + * @param feedDocumentClient the instance of {@link CosmosContainer} to be used. + * @return current Builder. + */ + @Override + public ChangeFeedProcessorBuilderImpl withFeedContainerClient(CosmosContainer feedDocumentClient) { + if (feedDocumentClient == null) { + throw new IllegalArgumentException("feedContextClient"); + } + + this.feedContextClient = new ChangeFeedContextClientImpl(feedDocumentClient); + return this; + } + + /** + * Sets the {@link ChangeFeedProcessorOptions} to be used. + * + * @param changeFeedProcessorOptions the change feed processor options to use. + * @return current Builder. + */ + @Override + public ChangeFeedProcessorBuilderImpl withProcessorOptions(ChangeFeedProcessorOptions changeFeedProcessorOptions) { + if (changeFeedProcessorOptions == null) { + throw new IllegalArgumentException("changeFeedProcessorOptions"); + } + + this.changeFeedProcessorOptions = changeFeedProcessorOptions; + this.executorService = changeFeedProcessorOptions.getExecutorService(); + + return this; + } + + /** + * Sets the {@link ChangeFeedObserverFactory} to be used to generate {@link ChangeFeedObserver} + * + * @param observerFactory The instance of {@link ChangeFeedObserverFactory} to use. + * @return current Builder. + */ + @Override + public ChangeFeedProcessorBuilderImpl withChangeFeedObserverFactory(ChangeFeedObserverFactory observerFactory) { + if (observerFactory == null) { + throw new IllegalArgumentException("observerFactory"); + } + + this.observerFactory = observerFactory; + return this; + } + + /** + * Sets an existing {@link ChangeFeedObserver} type to be used by a {@link ChangeFeedObserverFactory} to process changes. + * @param type the type of {@link ChangeFeedObserver} to be used. + * @return current Builder. + */ + @Override + public ChangeFeedProcessorBuilderImpl withChangeFeedObserver(Class type) { + if (type == null) { + throw new IllegalArgumentException("type"); + } + + this.observerFactory = new ChangeFeedObserverFactoryImpl(type); + + return this; + } + + /** + * Sets the database resource ID of the monitored collection. + * + * @param databaseResourceId the database resource ID of the monitored collection. + * @return current Builder. + */ + public ChangeFeedProcessorBuilderImpl withDatabaseResourceId(String databaseResourceId) { + this.databaseResourceId = databaseResourceId; + return this; + } + + /** + * Sets the collection resource ID of the monitored collection. + * @param collectionResourceId the collection resource ID of the monitored collection. + * @return current Builder. + */ + public ChangeFeedProcessorBuilderImpl withCollectionResourceId(String collectionResourceId) { + this.collectionResourceId = collectionResourceId; + return this; + } + + /** + * Sets an existing {@link CosmosContainer} to be used to read from the leases collection. + * + * @param leaseDocumentClient the instance of {@link CosmosContainer} to use. + * @return current Builder. + */ + @Override + public ChangeFeedProcessorBuilderImpl withLeaseContainerClient(CosmosContainer leaseDocumentClient) { + if (leaseDocumentClient == null) { + throw new IllegalArgumentException("leaseContextClient"); + } + + this.leaseContextClient = new ChangeFeedContextClientImpl(leaseDocumentClient); + return this; + } + + /** + * Sets the {@link PartitionLoadBalancingStrategy} to be used for partition load balancing. + * + * @param loadBalancingStrategy the {@link PartitionLoadBalancingStrategy} to be used for partition load balancing. + * @return current Builder. + */ + public ChangeFeedProcessorBuilderImpl withPartitionLoadBalancingStrategy(PartitionLoadBalancingStrategy loadBalancingStrategy) { + if (loadBalancingStrategy == null) { + throw new IllegalArgumentException("loadBalancingStrategy"); + } + + this.loadBalancingStrategy = loadBalancingStrategy; + return this; + } + + /** + * Sets the {@link PartitionProcessorFactory} to be used to create {@link PartitionProcessor} for partition processing. + * + * @param partitionProcessorFactory the instance of {@link PartitionProcessorFactory} to use. + * @return current Builder. + */ + public ChangeFeedProcessorBuilderImpl withPartitionProcessorFactory(PartitionProcessorFactory partitionProcessorFactory) { + if (partitionProcessorFactory == null) { + throw new IllegalArgumentException("partitionProcessorFactory"); + } + + this.partitionProcessorFactory = partitionProcessorFactory; + return this; + } + + /** + * Sets the {@link LeaseStoreManager} to be used to manage leases. + * + * @param leaseStoreManager the instance of {@link LeaseStoreManager} to use. + * @return current Builder. + */ + public ChangeFeedProcessorBuilderImpl withLeaseStoreManager(LeaseStoreManager leaseStoreManager) { + if (leaseStoreManager == null) { + throw new IllegalArgumentException("leaseStoreManager"); + } + + this.leaseStoreManager = leaseStoreManager; + return this; + } + + /** + * Sets the {@link HealthMonitor} to be used to monitor unhealthiness situation. + * + * @param healthMonitor The instance of {@link HealthMonitor} to use. + * @return current Builder. + */ + public ChangeFeedProcessorBuilderImpl withHealthMonitor(HealthMonitor healthMonitor) { + if (healthMonitor == null) { + throw new IllegalArgumentException("healthMonitor"); + } + + this.healthMonitor = healthMonitor; + return this; + } + + /** + * Builds a new instance of the {@link ChangeFeedProcessor} with the specified configuration asynchronously. + * + * @return an instance of {@link ChangeFeedProcessor}. + */ + @Override + public Mono build() { + ChangeFeedProcessorBuilderImpl self = this; + + if (this.hostName == null) + { + throw new IllegalArgumentException("Host name was not specified"); + } + + if (this.observerFactory == null) + { + throw new IllegalArgumentException("Observer was not specified"); + } + + if (this.executorService == null) { + this.executorService = Executors.newCachedThreadPool(); + } + + this.initializeCollectionPropertiesForBuild().block(); + LeaseStoreManager leaseStoreManager = this.getLeaseStoreManager().block(); + this.partitionManager = this.buildPartitionManager(leaseStoreManager).block(); + + return Mono.just(this); + } + + public ChangeFeedProcessorBuilderImpl() { + } + + public ChangeFeedProcessorBuilderImpl(PartitionManager partitionManager) { + this.partitionManager = partitionManager; + } + + private Mono initializeCollectionPropertiesForBuild() { + ChangeFeedProcessorBuilderImpl self = this; + + if (this.changeFeedProcessorOptions == null) { + this.changeFeedProcessorOptions = new ChangeFeedProcessorOptions(); + } + + if (this.databaseResourceId == null) { + this.feedContextClient + .readDatabase(this.feedContextClient.getDatabaseClient(), null) + .map( databaseResourceResponse -> { + self.databaseResourceId = databaseResourceResponse.getDatabase().getId(); + return self.databaseResourceId; + }) + .subscribeOn(Schedulers.elastic()) + .then() + .block(); + } + + if (this.collectionResourceId == null) { + self.feedContextClient + .readContainer(self.feedContextClient.getContainerClient(), null) + .map(documentCollectionResourceResponse -> { + self.collectionResourceId = documentCollectionResourceResponse.getContainer().getId(); + return self.collectionResourceId; + }) + .subscribeOn(Schedulers.elastic()) + .then() + .block(); + } + + return Mono.empty(); + } + + private Mono getLeaseStoreManager() { + ChangeFeedProcessorBuilderImpl self = this; + + if (this.leaseStoreManager == null) { + + return this.leaseContextClient.readContainerSettings(this.leaseContextClient.getContainerClient(), null) + .map( collectionSettings -> { + boolean isPartitioned = + collectionSettings.getPartitionKey() != null && + collectionSettings.getPartitionKey().getPaths() != null && + collectionSettings.getPartitionKey().getPaths().size() > 0; + if (!isPartitioned || (collectionSettings.getPartitionKey().getPaths().size() != 1 || !collectionSettings.getPartitionKey().getPaths().get(0).equals("/id"))) { +// throw new IllegalArgumentException("The lease collection, if partitioned, must have partition key equal to id."); + Mono.error(new IllegalArgumentException("The lease collection must have partition key equal to id.")); + } + + RequestOptionsFactory requestOptionsFactory = new PartitionedByIdCollectionRequestOptionsFactory(); + + String leasePrefix = self.getLeasePrefix(); + + self.leaseStoreManager = LeaseStoreManager.Builder() + .withLeasePrefix(leasePrefix) + .withLeaseContextClient(self.leaseContextClient) + .withRequestOptionsFactory(requestOptionsFactory) + .withHostName(self.hostName) + .build() + .block(); + + return self.leaseStoreManager; + }); + } + + return Mono.just(this.leaseStoreManager); + } + + private String getLeasePrefix() { + String optionsPrefix = this.changeFeedProcessorOptions.getLeasePrefix(); + + if (optionsPrefix == null) { + optionsPrefix = ""; + } + + URI uri = this.feedContextClient.getServiceEndpoint(); + + return String.format( + "%s%s_%s_%s", + optionsPrefix, + uri.getHost(), + this.databaseResourceId, + this.collectionResourceId); + } + + private Mono buildPartitionManager(LeaseStoreManager leaseStoreManager) { + ChangeFeedProcessorBuilderImpl self = this; + + CheckpointerObserverFactory factory = new CheckpointerObserverFactory(this.observerFactory, this.changeFeedProcessorOptions.getCheckpointFrequency()); + + PartitionSynchronizerImpl synchronizer = new PartitionSynchronizerImpl( + this.feedContextClient, + this.feedContextClient.getContainerClient(), + leaseStoreManager, + leaseStoreManager, + this.changeFeedProcessorOptions.getDegreeOfParallelism(), + this.changeFeedProcessorOptions.getQueryPartitionsMaxBatchSize() + ); + + Bootstrapper bootstrapper = new BootstrapperImpl(synchronizer, leaseStoreManager, this.lockTime, this.sleepTime); + PartitionSupervisorFactory partitionSupervisorFactory = new PartitionSupervisorFactoryImpl( + factory, + leaseStoreManager, + this.partitionProcessorFactory != null ? this.partitionProcessorFactory : new PartitionProcessorFactoryImpl( + this.feedContextClient, + this.changeFeedProcessorOptions, + leaseStoreManager, + this.feedContextClient.getContainerClient()), + this.changeFeedProcessorOptions, + executorService + ); + + if (this.loadBalancingStrategy == null) { + this.loadBalancingStrategy = new EqualPartitionsBalancingStrategy( + this.hostName, + this.changeFeedProcessorOptions.getMinPartitionCount(), + this.changeFeedProcessorOptions.getMaxPartitionCount(), + this.changeFeedProcessorOptions.getLeaseExpirationInterval()); + } + + PartitionController partitionController = new PartitionControllerImpl(leaseStoreManager, leaseStoreManager, partitionSupervisorFactory, synchronizer, executorService); + + if (this.healthMonitor == null) { + this.healthMonitor = new TraceHealthMonitor(); + } + + PartitionController partitionController2 = new HealthMonitoringPartitionControllerDecorator(partitionController, this.healthMonitor); + + PartitionLoadBalancer partitionLoadBalancer = new PartitionLoadBalancerImpl( + partitionController2, + leaseStoreManager, + this.loadBalancingStrategy, + this.changeFeedProcessorOptions.getLeaseAcquireInterval(), + this.executorService + ); + + PartitionManager partitionManager = new PartitionManagerImpl(bootstrapper, partitionController, partitionLoadBalancer); + + return Mono.just(partitionManager); + } + + @Override + public void close() { + this.stop().subscribeOn(Schedulers.elastic()).subscribe(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/CheckpointerObserverFactory.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/CheckpointerObserverFactory.java new file mode 100644 index 0000000000000..8a4714caf8e31 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/CheckpointerObserverFactory.java @@ -0,0 +1,61 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedObserverFactory; +import com.microsoft.azure.cosmos.changefeed.CheckpointFrequency; + +/** + * Factory class used to create instance(s) of {@link ChangeFeedObserver}. + */ +public class CheckpointerObserverFactory implements ChangeFeedObserverFactory { + private final ChangeFeedObserverFactory observerFactory; + private final CheckpointFrequency checkpointFrequency; + + /** + * Initializes a new instance of the {@link CheckpointerObserverFactory} class. + * + * @param observerFactory the instance of observer factory. + * @param checkpointFrequency the the frequency of lease event. + */ + public CheckpointerObserverFactory(ChangeFeedObserverFactory observerFactory, CheckpointFrequency checkpointFrequency) + { + if (observerFactory == null) throw new IllegalArgumentException("observerFactory"); + if (checkpointFrequency == null) throw new IllegalArgumentException("checkpointFrequency"); + + this.observerFactory = observerFactory; + this.checkpointFrequency = checkpointFrequency; + } + + /** + * @return a new instance of {@link ChangeFeedObserver}. + */ + @Override + public ChangeFeedObserver createObserver() { + ChangeFeedObserver observer = new ObserverExceptionWrappingChangeFeedObserverDecorator(this.observerFactory.createObserver()); + if (this.checkpointFrequency.isExplicitCheckpoint()) return observer; + + return new AutoCheckpointer(this.checkpointFrequency, observer); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/Constants.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/Constants.java new file mode 100644 index 0000000000000..f8c9aff7192fe --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/Constants.java @@ -0,0 +1,216 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + + +/** + * Used internally. Constants in the Azure Cosmos DB database service Java SDK. + */ +public final class Constants { + + public static final class Quota { + // Quota Strings + public static final String DATABASE = "databases"; + public static final String COLLECTION = "collections"; + public static final String USER = "users"; + public static final String PERMISSION = "permissions"; + public static final String COLLECTION_SIZE = "collectionSize"; + public static final String DOCUMENTS_SIZE = "documentsSize"; + public static final String STORED_PROCEDURE = "storedProcedures"; + public static final String TRIGGER = "triggers"; + public static final String USER_DEFINED_FUNCTION = "functions"; + public static final String DELIMITER_CHARS = "=|;"; + public static final String DOCUMENTS_COUNT = "documentsCount"; + } + + public static final class Properties { + public static final String ID = "id"; + public static final String R_ID = "_rid"; + public static final String SELF_LINK = "_self"; + public static final String LAST_MODIFIED = "_ts"; + public static final String COUNT = "_count"; + public static final String E_TAG = "_etag"; + public static final String AGGREGATE = "_aggregate"; + + public static final String CONSISTENCY_POLICY = "consistencyPolicy"; + public static final String DEFAULT_CONSISTENCY_LEVEL = "defaultConsistencyLevel"; + public static final String MAX_STALENESS_PREFIX = "maxStalenessPrefix"; + public static final String MAX_STALENESS_INTERVAL_IN_SECONDS = "maxIntervalInSeconds"; + public static final String PARENTS = "parents"; + + public static final String DATABASES_LINK = "_dbs"; + public static final String COLLECTIONS_LINK = "_colls"; + public static final String USERS_LINK = "_users"; + public static final String PERMISSIONS_LINK = "_permissions"; + public static final String ATTACHMENTS_LINK = "_attachments"; + public static final String STORED_PROCEDURES_LINK = "_sprocs"; + public static final String TRIGGERS_LINK = "_triggers"; + public static final String USER_DEFINED_FUNCTIONS_LINK = "_udfs"; + public static final String CONFLICTS_LINK = "_conflicts"; + public static final String DOCUMENTS_LINK = "_docs"; + public static final String RESOURCE_LINK = "resource"; + public static final String MEDIA_LINK = "media"; + + public static final String PERMISSION_MODE = "permissionMode"; + public static final String RESOURCE_KEY = "key"; + public static final String TOKEN = "_token"; + public static final String SQL_API_TYPE = "0x10"; + + // Scripting + public static final String BODY = "body"; + public static final String TRIGGER_TYPE = "triggerType"; + public static final String TRIGGER_OPERATION = "triggerOperation"; + + public static final String MAX_SIZE = "maxSize"; + public static final String CURRENT_USAGE = "currentUsage"; + + public static final String CONTENT = "content"; + + public static final String CONTENT_TYPE = "contentType"; + + // ErrorResource. + public static final String CODE = "code"; + public static final String MESSAGE = "message"; + public static final String ERROR_DETAILS = "errorDetails"; + public static final String ADDITIONAL_ERROR_INFO = "additionalErrorInfo"; + + // PartitionInfo. + public static final String RESOURCE_TYPE = "resourceType"; + public static final String SERVICE_INDEX = "serviceIndex"; + public static final String PARTITION_INDEX = "partitionIndex"; + + public static final String ADDRESS_LINK = "addresses"; + public static final String USER_REPLICATION_POLICY = "userReplicationPolicy"; + public static final String USER_CONSISTENCY_POLICY = "userConsistencyPolicy"; + public static final String SYSTEM_REPLICATION_POLICY = "systemReplicationPolicy"; + public static final String READ_POLICY = "readPolicy"; + public static final String QUERY_ENGINE_CONFIGURATION = "queryEngineConfiguration"; + + //ReplicationPolicy + public static final String REPLICATION_POLICY = "replicationPolicy"; + public static final String ASYNC_REPLICATION = "asyncReplication"; + public static final String MAX_REPLICA_SET_SIZE = "maxReplicasetSize"; + public static final String MIN_REPLICA_SET_SIZE = "minReplicaSetSize"; + + //Indexing Policy. + public static final String INDEXING_POLICY = "indexingPolicy"; + public static final String AUTOMATIC = "automatic"; + public static final String STRING_PRECISION = "StringPrecision"; + public static final String NUMERIC_PRECISION = "NumericPrecision"; + public static final String MAX_PATH_DEPTH = "maxPathDepth"; + public static final String INDEXING_MODE = "indexingMode"; + public static final String INDEX_TYPE = "IndexType"; + public static final String INDEX_KIND = "kind"; + public static final String DATA_TYPE = "dataType"; + public static final String PRECISION = "precision"; + + public static final String PATHS = "paths"; + public static final String PATH = "path"; + public static final String INCLUDED_PATHS = "includedPaths"; + public static final String EXCLUDED_PATHS = "excludedPaths"; + public static final String INDEXES = "indexes"; + public static final String COMPOSITE_INDEXES = "compositeIndexes"; + public static final String ORDER = "order"; + public static final String SPATIAL_INDEXES = "spatialIndexes"; + public static final String TYPES = "types"; + + // Unique index. + public static final String UNIQUE_KEY_POLICY = "uniqueKeyPolicy"; + public static final String UNIQUE_KEYS = "uniqueKeys"; + + // Conflict. + public static final String CONFLICT = "conflict"; + public static final String OPERATION_TYPE = "operationType"; + public static final String SOURCE_RESOURCE_ID = "resourceId"; + + // Offer resource + public static final String OFFER_TYPE = "offerType"; + public static final String OFFER_VERSION = "offerVersion"; + public static final String OFFER_CONTENT = "content"; + public static final String OFFER_THROUGHPUT = "offerThroughput"; + public static final String OFFER_VERSION_V1 = "V1"; + public static final String OFFER_VERSION_V2 = "V2"; + public static final String OFFER_RESOURCE_ID = "offerResourceId"; + + // PartitionKey + public static final String PARTITION_KEY = "partitionKey"; + public static final String PARTITION_KEY_PATHS = "paths"; + public static final String PARTITION_KIND = "kind"; + public static final String PARTITION_KEY_DEFINITION_VERSION = "version"; + + public static final String RESOURCE_PARTITION_KEY = "resourcePartitionKey"; + public static final String PARTITION_KEY_RANGE_ID = "partitionKeyRangeId"; + public static final String MIN_INCLUSIVE_EFFECTIVE_PARTITION_KEY = "minInclusiveEffectivePartitionKey"; + public static final String MAX_EXCLUSIVE_EFFECTIVE_PARTITION_KEY = "maxExclusiveEffectivePartitionKey"; + + // AddressResource + public static final String IS_PRIMARY = "isPrimary"; + public static final String PROTOCOL = "protocol"; + public static final String LOGICAL_URI = "logicalUri"; + public static final String PHYISCAL_URI = "physcialUri"; + + // Time-to-Live + public static final String TTL = "ttl"; + public static final String DEFAULT_TTL = "defaultTtl"; + + // Global DB account properties + public static final String Name = "name"; + public static final String WRITABLE_LOCATIONS = "writableLocations"; + public static final String READABLE_LOCATIONS = "readableLocations"; + public static final String DATABASE_ACCOUNT_ENDPOINT = "databaseAccountEndpoint"; + + //Authorization + public static final String MASTER_TOKEN = "master"; + public static final String RESOURCE_TOKEN = "resource"; + public static final String TOKEN_VERSION = "1.0"; + public static final String AUTH_SCHEMA_TYPE = "type"; + public static final String AUTH_VERSION = "ver"; + public static final String AUTH_SIGNATURE = "sig"; + public static final String READ_PERMISSION_MODE = "read"; + public static final String ALL_PERMISSION_MODE = "all"; + public static final String PATH_SEPARATOR = "/"; + + public static final int DEFAULT_MAX_PAGE_SIZE = 100; + public static final String ENABLE_MULTIPLE_WRITE_LOCATIONS = "enableMultipleWriteLocations"; + + // Conflict resolution policy + public static final String CONFLICT_RESOLUTION_POLICY = "conflictResolutionPolicy"; + public static final String MODE = "mode"; + public static final String CONFLICT_RESOLUTION_PATH = "conflictResolutionPath"; + public static final String CONFLICT_RESOLUTION_PROCEDURE = "conflictResolutionProcedure"; + + //Handler names for RXNetty httpClient + public static final String SSL_HANDLER_NAME = "ssl-handler"; + public static final String SSL_COMPLETION_HANDLER_NAME = "ssl-completion-handler"; + public static final String HTTP_PROXY_HANDLER_NAME = "http-proxy-handler"; + public static final String LOGGING_HANDLER_NAME = "logging-handler"; + } + + public static final class PartitionedQueryExecutionInfo { + public static final int VERSION_1 = 1; + } + + public static final class QueryExecutionContext { + public static final String INCREMENTAL_FEED_HEADER_VALUE = "Incremental feed"; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseStore.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseStore.java new file mode 100644 index 0000000000000..ea74e8ba9f150 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseStore.java @@ -0,0 +1,192 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; +import com.microsoft.azure.cosmos.changefeed.LeaseStore; +import com.microsoft.azure.cosmos.changefeed.RequestOptionsFactory; +import com.microsoft.azure.cosmos.changefeed.ServiceItemLease; +import com.microsoft.azure.cosmosdb.AccessCondition; +import com.microsoft.azure.cosmosdb.AccessConditionType; +import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT; +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; + +/** + * Implementation for LeaseStore. + */ +public class DocumentServiceLeaseStore implements LeaseStore { + private ChangeFeedContextClient client; + private String containerNamePrefix; + private CosmosContainer leaseCollectionLink; + private RequestOptionsFactory requestOptionsFactory; + private String lockETag; + + // TODO: rename to LeaseStoreImpl + public DocumentServiceLeaseStore( + ChangeFeedContextClient client, + String containerNamePrefix, + CosmosContainer leaseCollectionLink, + RequestOptionsFactory requestOptionsFactory) { + + this.client = client; + this.containerNamePrefix = containerNamePrefix; + this.leaseCollectionLink = leaseCollectionLink; + this.requestOptionsFactory = requestOptionsFactory; + } + + @Override + public Mono isInitialized() { + String markerDocId = this.getStoreMarkerName(); + + CosmosItemSettings doc = new CosmosItemSettings(); + doc.setId(markerDocId); + + CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createRequestOptions( + ServiceItemLease.fromDocument(doc)); + + CosmosItem docItem = this.client.getContainerClient().getItem(markerDocId, "/id"); + return this.client.readItem(docItem, requestOptions) + .flatMap(documentResourceResponse -> Mono.just(documentResourceResponse.getItem() != null)) + .onErrorResume(throwable -> { + if (throwable instanceof DocumentClientException) { + DocumentClientException e = (DocumentClientException) throwable; + if (e.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + return Mono.just(false); + } + } + Mono.error(throwable); + return Mono.empty(); + }); + } + + @Override + public Mono markInitialized() { + String markerDocId = this.getStoreMarkerName(); + CosmosItemSettings containerDocument = new CosmosItemSettings(); + containerDocument.setId(markerDocId); + + return this.client.createItem(this.leaseCollectionLink, containerDocument, null, false) + .map( item -> true) + .onErrorResume(throwable -> { + if (throwable instanceof DocumentClientException) { + DocumentClientException e = (DocumentClientException) throwable; + if (e.getStatusCode() == HTTP_STATUS_CODE_CONFLICT) { + return Mono.just(true); + } + } + return Mono.just(false); + }); + } + + @Override + public Mono acquireInitializationLock(Duration lockExpirationTime) { + String lockId = this.getStoreLockName(); + Document containerDocument = new Document(); + containerDocument.setId(lockId); + containerDocument.setTimeToLive(Long.valueOf(lockExpirationTime.getSeconds()).intValue()); + DocumentServiceLeaseStore self = this; + + return this.client.createItem(this.leaseCollectionLink, containerDocument, null, false) + .map(documentResourceResponse -> { + if (documentResourceResponse.getItem() != null) { + self.lockETag = documentResourceResponse.getCosmosItemSettings().getETag(); + return true; + } else { + return false; + } + }) + .onErrorResume(throwable -> { + if (throwable instanceof DocumentClientException) { + DocumentClientException e = (DocumentClientException) throwable; + if (e.getStatusCode() == HTTP_STATUS_CODE_CONFLICT) { + return Mono.just(false); + } + } + Mono.error(throwable); + return Mono.empty(); + }); + } + + @Override + public Mono releaseInitializationLock() { + String lockId = this.getStoreLockName(); + CosmosItemSettings doc = new CosmosItemSettings(); + doc.setId(lockId); + + CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createRequestOptions( + ServiceItemLease.fromDocument(doc)); + + if (requestOptions == null) { + requestOptions = new CosmosItemRequestOptions(); + } + + AccessCondition accessCondition = new AccessCondition(); + accessCondition.setType(AccessConditionType.IfMatch); + accessCondition.setCondition(this.lockETag); + requestOptions.accessCondition(accessCondition); + DocumentServiceLeaseStore self = this; + + CosmosItem docItem = this.client.getContainerClient().getItem(lockId, "/id"); + return this.client.deleteItem(docItem, requestOptions) + .map(documentResourceResponse -> { + if (documentResourceResponse.getItem() != null) { + self.lockETag = null; + return true; + } else { + return false; + } + }) + .onErrorResume(throwable -> { + if (throwable instanceof DocumentClientException) { + DocumentClientException e = (DocumentClientException) throwable; + if (e.getStatusCode() == HTTP_STATUS_CODE_CONFLICT) { + return Mono.just(false); + } + } + + Mono.error(throwable); + return Mono.empty(); + }); + } + + private String getStoreMarkerName() + { + return this.containerNamePrefix + ".info"; + } + + private String getStoreLockName() + { + return this.containerNamePrefix + ".lock"; + } + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java new file mode 100644 index 0000000000000..9d0ca6d13a08d --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java @@ -0,0 +1,152 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemResponse; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.ServiceItemLease; +import com.microsoft.azure.cosmos.changefeed.ServiceItemLeaseUpdater; +import com.microsoft.azure.cosmos.changefeed.exceptions.LeaseLostException; +import com.microsoft.azure.cosmosdb.AccessCondition; +import com.microsoft.azure.cosmosdb.AccessConditionType; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; + +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.function.Function; + +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT; +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_PRECONDITION_FAILED; + +/** + * Implementation for service lease updater interface. + */ +public class DocumentServiceLeaseUpdaterImpl implements ServiceItemLeaseUpdater { + private final Logger logger = LoggerFactory.getLogger(TraceHealthMonitor.class); + private final int RETRY_COUNT_ON_CONFLICT = 5; + private final ChangeFeedContextClient client; + + public DocumentServiceLeaseUpdaterImpl(ChangeFeedContextClient client) { + if (client == null) { + throw new IllegalArgumentException("client"); + } + + this.client = client; + } + + @Override + public Mono updateLease(Lease cachedLease, CosmosItem itemLink, CosmosItemRequestOptions requestOptions, Function updateLease) { + Lease lease = cachedLease; + + for (int retryCount = RETRY_COUNT_ON_CONFLICT; retryCount > 0; retryCount--) { + lease = updateLease.apply(lease); + + if (lease == null) { + return null; + } + + lease.setTimestamp(ZonedDateTime.now(ZoneId.of("UTC"))); + CosmosItemSettings leaseDocument = this.tryReplaceLease(lease, itemLink); + + if (leaseDocument != null) { + return Mono.just(ServiceItemLease.fromDocument(leaseDocument)); + } + + // Partition lease update conflict. Reading the current version of lease. + CosmosItemSettings document = null; + try { + CosmosItemResponse response = this.client.readItem(itemLink, requestOptions) + .block(); + document = response.getCosmosItemSettings(); + } catch (RuntimeException re) { + if (re.getCause() instanceof DocumentClientException) { + DocumentClientException ex = (DocumentClientException) re.getCause(); + if (ex.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + // Partition lease no longer exists + throw new LeaseLostException(lease); + } + } + throw re; + } + + ServiceItemLease serverLease = ServiceItemLease.fromDocument(document); +// Logger.InfoFormat( +// "Partition {0} update failed because the lease with token '{1}' was updated by host '{2}' with token '{3}'. Will retry, {4} retry(s) left.", +// lease.LeaseToken, +// lease.ConcurrencyToken, +// serverLease.Owner, +// serverLease.ConcurrencyToken, +// retryCount); + + lease = serverLease; + } + + throw new LeaseLostException(lease); + } + + private CosmosItemSettings tryReplaceLease(Lease lease, CosmosItem itemLink) throws LeaseLostException { + try { + CosmosItemResponse response = this.client.replaceItem(itemLink, lease, this.getCreateIfMatchOptions(lease)) + .block(); + return response.getCosmosItemSettings(); + } catch (RuntimeException re) { + if (re.getCause() instanceof DocumentClientException) { + DocumentClientException ex = (DocumentClientException) re.getCause(); + switch (ex.getStatusCode()) { + case HTTP_STATUS_CODE_PRECONDITION_FAILED: { + return null; + } + case HTTP_STATUS_CODE_CONFLICT: { + throw new LeaseLostException(lease, ex, false); + } + case HTTP_STATUS_CODE_NOT_FOUND: { + throw new LeaseLostException(lease, ex, true); + } + default: { + throw re; + } + } + } + throw re; + } + } + + private CosmosItemRequestOptions getCreateIfMatchOptions(Lease lease) { + AccessCondition ifMatchCondition = new AccessCondition(); + ifMatchCondition.setType(AccessConditionType.IfMatch); + ifMatchCondition.setCondition(lease.getConcurrencyToken()); + + CosmosItemRequestOptions createIfMatchOptions = new CosmosItemRequestOptions(); + createIfMatchOptions.accessCondition(ifMatchCondition); + + return createIfMatchOptions; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java new file mode 100644 index 0000000000000..c8875801b066e --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java @@ -0,0 +1,189 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancingStrategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.time.Duration; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Implementation for {@link PartitionLoadBalancingStrategy}. + */ +public class EqualPartitionsBalancingStrategy implements PartitionLoadBalancingStrategy { + private final Logger logger = LoggerFactory.getLogger(EqualPartitionsBalancingStrategy.class); + private final String hostName; + private final int minPartitionCount; + private final int maxPartitionCount; + private final Duration leaseExpirationInterval; + + public EqualPartitionsBalancingStrategy(String hostName, int minPartitionCount, int maxPartitionCount, Duration leaseExpirationInterval) { + if (hostName == null) throw new IllegalArgumentException("hostName"); + this.hostName = hostName; + this.minPartitionCount = minPartitionCount; + this.maxPartitionCount = maxPartitionCount; + this.leaseExpirationInterval = leaseExpirationInterval; + } + + @Override + public List selectLeasesToTake(List allLeases) { + Map workerToPartitionCount = new HashMap<>(); + List expiredLeases = new ArrayList<>(); + Map allPartitions = new HashMap<>(); + + this.categorizeLeases(allLeases, allPartitions, expiredLeases, workerToPartitionCount); + + int partitionCount = allPartitions.size(); + int workerCount = workerToPartitionCount.size(); + if (partitionCount <= 0) + return new ArrayList(); + + int target = this.calculateTargetPartitionCount(partitionCount, workerCount); + int myCount = workerToPartitionCount.get(this.hostName); + int partitionsNeededForMe = target - myCount; + + /* + Logger.InfoFormat( + "Host '{0}' {1} partitions, {2} hosts, {3} available leases, target = {4}, min = {5}, max = {6}, mine = {7}, will try to take {8} lease(s) for myself'.", + this.hostName, + partitionCount, + workerCount, + expiredLeases.Count, + target, + this.minPartitionCount, + this.maxPartitionCount, + myCount, + Math.Max(partitionsNeededForMe, 0)); + */ + + if (partitionsNeededForMe <= 0) + return new ArrayList(); + + if (expiredLeases.size() > 0) { + return expiredLeases.subList(0, partitionsNeededForMe); + } + + Lease stolenLease = getLeaseToSteal(workerToPartitionCount, target, partitionsNeededForMe, allPartitions); + List stolenLeases = new ArrayList<>(); + + if (stolenLease == null) { + stolenLeases.add(stolenLease); + } + + return stolenLeases; + } + + private static Lease getLeaseToSteal( + Map workerToPartitionCount, + int target, + int partitionsNeededForMe, + Map allPartitions) { + + Map.Entry workerToStealFrom = findWorkerWithMostPartitions(workerToPartitionCount); + + if (workerToStealFrom.getValue() > target - (partitionsNeededForMe > 1 ? 1 : 0)) { + for (Map.Entry entry : allPartitions.entrySet()) { + if (entry.getValue().getOwner().equalsIgnoreCase(workerToStealFrom.getKey())) { + return entry.getValue(); + } + } + } + + return null; + } + + private static Map.Entry findWorkerWithMostPartitions(Map workerToPartitionCount) { + Map.Entry workerToStealFrom = new ChangeFeedHelper.KeyValuePair<>("", 0); + for (Map.Entry entry : workerToPartitionCount.entrySet()) { + if (workerToStealFrom.getValue() <= entry.getValue()) { + workerToStealFrom = entry; + } + } + + return workerToStealFrom; + } + + private int calculateTargetPartitionCount(int partitionCount, int workerCount) { + int target = 1; + if (partitionCount > workerCount) { + target = (int)Math.ceil((double)partitionCount / workerCount); + } + + if (this.maxPartitionCount > 0 && target > this.maxPartitionCount) { + target = this.maxPartitionCount; + } + + if (this.minPartitionCount > 0 && target < this.minPartitionCount) { + target = this.minPartitionCount; + } + + return target; + } + + private void categorizeLeases( + List allLeases, + Map allPartitions, + List expiredLeases, + Map workerToPartitionCount) { + + for (Lease lease : allLeases) { + // Debug.Assert(lease.LeaseToken != null, "TakeLeasesAsync: lease.LeaseToken cannot be null."); + + allPartitions.put(lease.getLeaseToken(), lease); + + if (lease.getOwner() == null || lease.getOwner().isEmpty() || this.isExpired(lease)) { + // Logger.DebugFormat("Found unused or expired lease: {0}", lease); + expiredLeases.add(lease); + } else { + String assignedTo = lease.getOwner(); + Integer count = workerToPartitionCount.get(assignedTo); + + if (count != null) { + workerToPartitionCount.replace(assignedTo, count + 1); + } else { + workerToPartitionCount.put(assignedTo, 1); + } + } + } + + if (!workerToPartitionCount.containsKey(this.hostName)) { + workerToPartitionCount.put(this.hostName, 0); + } + } + + private boolean isExpired(Lease lease) { + if (lease.getOwner() == null || lease.getOwner().isEmpty() || lease.getTimestamp() == null) { + return true; + } + ZonedDateTime time = ZonedDateTime.parse(lease.getTimestamp()); + return time.plus(this.leaseExpirationInterval).isBefore(ZonedDateTime.now(ZoneId.of("UTC"))); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ExceptionClassifier.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ExceptionClassifier.java new file mode 100644 index 0000000000000..7b6119aef93bb --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ExceptionClassifier.java @@ -0,0 +1,67 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmosdb.DocumentClientException; + +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_GONE; +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR; +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_TOO_MANY_REQUESTS; + +/** + * Classifies exceptions based on the status codes. + */ +public class ExceptionClassifier { + public static final int SubStatusCode_Undefined = -1; + + // 410: partition key range is gone. + public static final int SubStatusCode_PartitionKeyRangeGone = 1002; + + // 410: partition splitting. + public static final int SubStatusCode_Splitting = 1007; + + // 404: LSN in session token is higher. + public static final int SubStatusCode_ReadSessionNotAvailable = 1002; + + + public static StatusCodeErrorType classifyClientException(DocumentClientException clientException) { + Integer subStatusCode = clientException.getSubStatusCode(); + + if (clientException.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND && subStatusCode != SubStatusCode_ReadSessionNotAvailable) + return StatusCodeErrorType.PARTITION_NOT_FOUND; + + if (clientException.getStatusCode() == HTTP_STATUS_CODE_GONE && (subStatusCode == SubStatusCode_PartitionKeyRangeGone || subStatusCode == SubStatusCode_Splitting)) + return StatusCodeErrorType.PARTITION_SPLIT; + + if (clientException.getStatusCode() == HTTP_STATUS_CODE_TOO_MANY_REQUESTS || clientException.getStatusCode() >= HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR) + return StatusCodeErrorType.TRANSIENT_ERROR; + + // Temporary workaround to compare exception message, until server provides better way of handling this case. + if (clientException.getMessage().contains("Reduce page size and try again.")) + return StatusCodeErrorType.MAX_ITEM_COUNT_TOO_LARGE; + + return StatusCodeErrorType.UNDEFINED; + + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java new file mode 100644 index 0000000000000..9247c11859f9f --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java @@ -0,0 +1,72 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.HealthMonitor; +import com.microsoft.azure.cosmos.changefeed.HealthMonitoringRecord; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.PartitionController; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import reactor.core.publisher.Mono; + +/** + * Monitors partition controller health. + */ +public class HealthMonitoringPartitionControllerDecorator implements PartitionController { + private final PartitionController inner; + private final HealthMonitor monitor; + + public HealthMonitoringPartitionControllerDecorator(PartitionController inner, HealthMonitor monitor) { + if (inner == null) throw new IllegalArgumentException("inner"); + if (monitor == null) throw new IllegalArgumentException("monitor"); + + this.inner = inner; + this.monitor = monitor; + } + + @Override + public Mono addOrUpdateLease(Lease lease) { + return this.inner.addOrUpdateLease(lease) + .onErrorResume(throwable -> { + if (throwable instanceof DocumentClientException) { + // do nothing. + } else { + monitor.inspect(new HealthMonitoringRecord( + HealthMonitoringRecord.HealthSeverity.INFORMATIONAL, + HealthMonitoringRecord.MonitoredOperation.ACQUIRE_LEASE, + lease, throwable)); + } + return Mono.empty(); + }); + } + + @Override + public Mono initialize() { + return this.inner.initialize(); + } + + @Override + public Mono shutdown() { + return this.inner.shutdown(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseRenewerImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseRenewerImpl.java new file mode 100644 index 0000000000000..dda2c7378899f --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseRenewerImpl.java @@ -0,0 +1,119 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.CancellationToken; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.LeaseManager; +import com.microsoft.azure.cosmos.changefeed.LeaseRenewer; +import com.microsoft.azure.cosmos.changefeed.exceptions.LeaseLostException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +/** + * Implementation for the {@link LeaseRenewer}. + */ +public class LeaseRenewerImpl implements LeaseRenewer { + private final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); + private final LeaseManager leaseManager; + private final Duration leaseRenewInterval; + private Lease lease; + private RuntimeException resultException; + + public LeaseRenewerImpl(Lease lease, LeaseManager leaseManager, Duration leaseRenewInterval) + { + this.lease = lease; + this.leaseManager = leaseManager; + this.leaseRenewInterval = leaseRenewInterval; + } + + @Override + public Mono run(CancellationToken cancellationToken) { + LeaseRenewerImpl self = this; + + return Mono.fromRunnable( () -> { + try { + logger.info(String.format("Partition %s: renewer task started.", self.lease.getLeaseToken())); + long remainingWork = this.leaseRenewInterval.toMillis() / 2; + + try { + while (!cancellationToken.isCancellationRequested() && remainingWork > 0) { + Thread.sleep(100); + remainingWork -= 100; + } + } catch (InterruptedException ex) { + // exception caught + logger.info(String.format("Partition %s: renewer task stopped.", self.lease.getLeaseToken())); + } + + while (!cancellationToken.isCancellationRequested()) { + self.renew().block(); + + remainingWork = this.leaseRenewInterval.toMillis(); + + try { + while (!cancellationToken.isCancellationRequested() && remainingWork > 0) { + Thread.sleep(100); + remainingWork -= 100; + } + } catch (InterruptedException ex) { + // exception caught + logger.info(String.format("Partition %s: renewer task stopped.", self.lease.getLeaseToken())); + break; + } + } + } catch (RuntimeException ex) { + logger.error(String.format("Partition %s: renew lease loop failed.", self.lease.getLeaseToken()), ex); + self.resultException = ex; + } + }); + } + + @Override + public RuntimeException getResultException() { + return this.resultException; + } + + private Mono renew() { + LeaseRenewerImpl self = this; + + return Mono.fromRunnable( () -> { + try { + Lease renewedLease = self.leaseManager.renew(this.lease).block(); + if (renewedLease != null) this.lease = renewedLease; + + logger.info(String.format("Partition %s: renewed lease with result %s", self.lease.getLeaseToken(), renewedLease != null)); + } catch (LeaseLostException leaseLostException) { + logger.error(String.format("Partition %s: lost lease on renew.", self.lease.getLeaseToken()), leaseLostException); + self.resultException = leaseLostException; + throw leaseLostException; + } catch (Exception ex) { + logger.error(String.format("Partition %s: failed to renew lease.", self.lease.getLeaseToken()), ex); + } + }); + } + +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseStoreManagerImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseStoreManagerImpl.java new file mode 100644 index 0000000000000..8672304b8565b --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseStoreManagerImpl.java @@ -0,0 +1,446 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.LeaseStore; +import com.microsoft.azure.cosmos.changefeed.LeaseStoreManager; +import com.microsoft.azure.cosmos.changefeed.LeaseStoreManagerSettings; +import com.microsoft.azure.cosmos.changefeed.RequestOptionsFactory; +import com.microsoft.azure.cosmos.changefeed.ServiceItemLease; +import com.microsoft.azure.cosmos.changefeed.ServiceItemLeaseUpdater; +import com.microsoft.azure.cosmos.changefeed.exceptions.LeaseLostException; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.SqlParameter; +import com.microsoft.azure.cosmosdb.SqlParameterCollection; +import com.microsoft.azure.cosmosdb.SqlQuerySpec; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT; +import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; + +/** + * Provides flexible way to build lease manager constructor parameters. + * For the actual creation of lease manager instance, delegates to lease manager factory. + */ +public class LeaseStoreManagerImpl implements LeaseStoreManager, LeaseStoreManager.LeaseStoreManagerBuilderDefinition { + + private final Logger logger = LoggerFactory.getLogger(LeaseStoreManagerImpl.class); + private LeaseStoreManagerSettings settings; + private ChangeFeedContextClient leaseDocumentClient; + private RequestOptionsFactory requestOptionsFactory; + private ServiceItemLeaseUpdater leaseUpdater; + private LeaseStore leaseStore; + + + public static LeaseStoreManagerBuilderDefinition Builder() { + return new LeaseStoreManagerImpl(); + } + + public LeaseStoreManagerImpl() { + this.settings = new LeaseStoreManagerSettings(); + } + + @Override + public LeaseStoreManagerBuilderDefinition withLeaseContextClient(ChangeFeedContextClient leaseContextClient) { + if (leaseDocumentClient == null) { + throw new IllegalArgumentException("leaseDocumentClient"); + } + + this.leaseDocumentClient = leaseContextClient; + return this; + } + + @Override + public LeaseStoreManagerBuilderDefinition withLeasePrefix(String leasePrefix) { + if (leasePrefix == null) { + throw new IllegalArgumentException("leasePrefix"); + } + + this.settings.withContainerNamePrefix(leasePrefix); + return this; + } + + @Override + public LeaseStoreManagerBuilderDefinition withLeaseCollectionLink(CosmosContainer leaseCollectionLink) { + if (leaseCollectionLink == null) { + throw new IllegalArgumentException("leaseCollectionLink"); + } + + this.settings.withLeaseCollectionLink(leaseCollectionLink); + return this; + } + + @Override + public LeaseStoreManagerBuilderDefinition withRequestOptionsFactory(RequestOptionsFactory requestOptionsFactory) { + if (requestOptionsFactory == null) { + throw new IllegalArgumentException("requestOptionsFactory"); + } + + this.requestOptionsFactory = requestOptionsFactory; + return this; + } + + @Override + public LeaseStoreManagerBuilderDefinition withHostName(String hostName) { + if (hostName == null) { + throw new IllegalArgumentException("hostName"); + } + + this.settings.withHostName(hostName); + return this; + } + + @Override + public Mono build() { + if (this.settings == null) throw new IllegalArgumentException("settings"); + if (this.settings.getContainerNamePrefix() == null) throw new IllegalArgumentException("settings.containerNamePrefix"); + if (this.settings.getLeaseCollectionLink() == null) throw new IllegalArgumentException("settings.leaseCollectionLink"); + if (this.settings.getHostName() == null || this.settings.getHostName().isEmpty()) throw new IllegalArgumentException("settings.hostName"); + if (this.leaseDocumentClient == null) throw new IllegalArgumentException("leaseDocumentClient"); + if (this.requestOptionsFactory == null) throw new IllegalArgumentException("requestOptionsFactory"); + if (this.leaseUpdater == null) { + this.leaseUpdater = new DocumentServiceLeaseUpdaterImpl(leaseDocumentClient); + } + + this.leaseStore = new DocumentServiceLeaseStore( + this.leaseDocumentClient, + this.settings.getContainerNamePrefix(), + this.settings.getLeaseCollectionLink(), + this.requestOptionsFactory); + + LeaseStoreManagerImpl self = this; + if (this.settings.getLeaseCollectionLink() == null) + throw new IllegalArgumentException("leaseCollectionLink was not specified"); + if (this.requestOptionsFactory == null) + throw new IllegalArgumentException("requestOptionsFactory was not specified"); + + return Mono.just(self); + } + + @Override + public Flux getAllLeases() { + return this.listDocuments(this.getPartitionLeasePrefix()) + .map(documentServiceLease -> documentServiceLease); + } + + @Override + public Flux getOwnedLeases() { + LeaseStoreManagerImpl self = this; + return this.getAllLeases() + .filter(lease -> lease.getOwner() != null && lease.getOwner().equalsIgnoreCase(self.settings.getHostName())); + } + + @Override + public Mono createLeaseIfNotExist(String leaseToken, String continuationToken) { + if (leaseToken == null) throw new IllegalArgumentException("leaseToken"); + + String leaseDocId = this.getDocumentId(leaseToken); + ServiceItemLease documentServiceLease = new ServiceItemLease() + .withId(leaseDocId) + .withLeaseToken(leaseToken) + .withContinuationToken(continuationToken); + + return this.leaseDocumentClient.createItem(this.settings.getLeaseCollectionLink(), documentServiceLease, null, false) + .onErrorResume( ex -> { + if (ex instanceof DocumentClientException) { + DocumentClientException e = (DocumentClientException) ex; + if (e.getStatusCode() == HTTP_STATUS_CODE_CONFLICT) { + //Logger.InfoFormat("Some other host created lease for {0}.", leaseToken); + return Mono.empty(); + } + } + + Mono.error(ex); + return Mono.empty(); + }) + .map(documentResourceResponse -> { + if (documentResourceResponse == null) return null; + + CosmosItemSettings document = documentResourceResponse.getCosmosItemSettings(); + return documentServiceLease + .withId(document.getId()) + .withEtag(document.getETag()) + .withTs(document.getString(Constants.Properties.LAST_MODIFIED)); + }); + //Logger.InfoFormat("Created lease for partition {0}.", leaseToken); + } + + @Override + public Mono delete(Lease lease) { + if (lease == null || lease.getId() == null) throw new IllegalArgumentException("lease"); + + CosmosItem itemForLease = this.createItemForLease(lease.getId()); + + return this.leaseDocumentClient + .deleteItem(itemForLease, this.requestOptionsFactory.createRequestOptions(lease)) + .onErrorResume( ex -> { + if (ex instanceof DocumentClientException) { + DocumentClientException e = (DocumentClientException) ex; + if (e.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + // Ignore - document was already deleted. + return Mono.empty(); + } + } + + Mono.error(ex); + return Mono.empty(); + }) + // return some add-hoc value since we don't actually care about the result. + .map( documentResourceResponse -> true) + .then(); + } + + @Override + public Mono acquire(Lease lease) { + if (lease == null) throw new IllegalArgumentException("lease"); + + String oldOwner = lease.getOwner(); + + return this.leaseUpdater.updateLease( + lease, + this.createItemForLease(lease.getId()), + this.requestOptionsFactory.createRequestOptions(lease), + serverLease -> { + if (serverLease.getOwner() != null && !serverLease.getOwner().equalsIgnoreCase(oldOwner)) { + // Logger.InfoFormat("Partition {0} lease was taken over by owner '{1}'", lease.LeaseToken, serverLease.Owner); + Mono.error(new LeaseLostException(lease)); + } + serverLease.setOwner(this.settings.getHostName()); + serverLease.setProperties(lease.getProperties()); + + return serverLease; + }); + } + + @Override + public Mono release(Lease lease) { + if (lease == null) throw new IllegalArgumentException("lease"); + + CosmosItem itemForLease = this.createItemForLease(lease.getId()); + LeaseStoreManagerImpl self = this; + + return this.leaseDocumentClient.readItem(itemForLease, this.requestOptionsFactory.createRequestOptions(lease)) + .onErrorResume( ex -> { + if (ex instanceof DocumentClientException) { + DocumentClientException e = (DocumentClientException) ex; + if (e.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + // Logger.InfoFormat("Partition {0} failed to renew lease. The lease is gone already.", lease.LeaseToken); + Mono.error(new LeaseLostException(lease)); + } + } + + Mono.error(ex); + return Mono.empty(); + }) + .map( documentResourceResponse -> ServiceItemLease.fromDocument(documentResourceResponse.getCosmosItemSettings())) + .flatMap( refreshedLease -> self.leaseUpdater.updateLease( + refreshedLease, + self.createItemForLease(refreshedLease.getId()), + self.requestOptionsFactory.createRequestOptions(lease), + serverLease -> + { + if (!serverLease.getOwner().equalsIgnoreCase(lease.getOwner())) { + //Logger.InfoFormat("Partition {0} no need to release lease. The lease was already taken by another host '{1}'.", lease.LeaseToken, serverLease.Owner); + Mono.error(new LeaseLostException(lease)); + } + + serverLease.setOwner(null); + + return serverLease; + }) + ).then(); + } + + @Override + public Mono renew(Lease lease) { + if (lease == null) throw new IllegalArgumentException("lease"); + + // Get fresh lease. The assumption here is that check-pointing is done with higher frequency than lease renewal so almost + // certainly the lease was updated in between. + CosmosItem itemForLease = this.createItemForLease(lease.getId()); + LeaseStoreManagerImpl self = this; + + return this.leaseDocumentClient.readItem(itemForLease, this.requestOptionsFactory.createRequestOptions(lease)) + .onErrorResume( ex -> { + if (ex instanceof DocumentClientException) { + DocumentClientException e = (DocumentClientException) ex; + if (e.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + // Logger.InfoFormat("Partition {0} failed to renew lease. The lease is gone already.", lease.LeaseToken); + Mono.error(new LeaseLostException(lease)); + } + } + + Mono.error(ex); + return Mono.empty(); + }) + .map( documentResourceResponse -> ServiceItemLease.fromDocument(documentResourceResponse.getCosmosItemSettings())) + .flatMap( refreshedLease -> self.leaseUpdater.updateLease( + refreshedLease, + self.createItemForLease(refreshedLease.getId()), + self.requestOptionsFactory.createRequestOptions(lease), + serverLease -> + { + if (!serverLease.getOwner().equalsIgnoreCase(lease.getOwner())) { + // Logger.InfoFormat("Partition {0} lease was taken over by owner '{1}'", lease.LeaseToken, serverLease.Owner); + Mono.error(new LeaseLostException(lease)); + } + + return serverLease; + }) + ); + } + + @Override + public Mono updateProperties(Lease lease) { + if (lease == null) throw new IllegalArgumentException("lease"); + + if (!lease.getOwner().equalsIgnoreCase(this.settings.getHostName())) + { + // Logger.InfoFormat("Partition '{0}' lease was taken over by owner '{1}' before lease properties update", lease.LeaseToken, lease.Owner); + Mono.error(new LeaseLostException(lease)); + } + + return this.leaseUpdater.updateLease( + lease, + this.createItemForLease(lease.getId()), + this.requestOptionsFactory.createRequestOptions(lease), + serverLease -> { + if (!serverLease.getOwner().equalsIgnoreCase(lease.getOwner())) { + // Logger.InfoFormat("Partition '{0}' lease was taken over by owner '{1}'", lease.LeaseToken, serverLease.Owner); + Mono.error(new LeaseLostException(lease)); + } + serverLease.setProperties(lease.getProperties()); + return serverLease; + }); + } + + @Override + public Mono checkpoint(Lease lease, String continuationToken) { + if (lease == null) throw new IllegalArgumentException("lease"); + + if (continuationToken == null || continuationToken.isEmpty()) { + throw new IllegalArgumentException("continuationToken must be a non-empty string"); + } + + return this.leaseUpdater.updateLease( + lease, + this.createItemForLease(lease.getId()), + this.requestOptionsFactory.createRequestOptions(lease), + serverLease -> { + if (serverLease.getOwner() != null && !serverLease.getOwner().equalsIgnoreCase(lease.getOwner())) { + //Logger.InfoFormat("Partition {0} lease was taken over by owner '{1}'", lease.LeaseToken, serverLease.Owner); + Mono.error(new LeaseLostException(lease)); + } + serverLease.setContinuationToken(continuationToken); + + return serverLease; + }); + } + + @Override + public Mono isInitialized() { + return this.leaseStore.isInitialized(); + } + + @Override + public Mono markInitialized() { + return this.leaseStore.markInitialized(); + } + + @Override + public Mono acquireInitializationLock(Duration lockExpirationTime) { + return this.leaseStore.acquireInitializationLock(lockExpirationTime); + } + + @Override + public Mono releaseInitializationLock() { + return this.leaseStore.releaseInitializationLock(); + } + + private Mono tryGetLease(Lease lease) { + CosmosItem itemForLease = this.createItemForLease(lease.getId()); + + return this.leaseDocumentClient.readItem(itemForLease, this.requestOptionsFactory.createRequestOptions(lease)) + .onErrorResume( ex -> { + if (ex instanceof DocumentClientException) { + DocumentClientException e = (DocumentClientException) ex; + if (e.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + return Mono.empty(); + } + } + + Mono.error(ex); + return Mono.empty(); + }) + .map( documentResourceResponse -> { + if (documentResourceResponse == null) return null; + return ServiceItemLease.fromDocument(documentResourceResponse.getCosmosItemSettings()); + }); + } + + private Flux listDocuments(String prefix) { + if (prefix == null || prefix.isEmpty()) { + throw new IllegalArgumentException("prefix"); + } + + SqlParameter param = new SqlParameter(); + param.setName("@PartitionLeasePrefix"); + param.setValue(prefix); + SqlQuerySpec querySpec = new SqlQuerySpec( + "SELECT * FROM c WHERE STARTSWITH(c.id, @PartitionLeasePrefix)", + new SqlParameterCollection(param)); + + Flux> query = this.leaseDocumentClient.queryItems( + this.settings.getLeaseCollectionLink(), + querySpec, + this.requestOptionsFactory.createFeedOptions()); + + return query.flatMap( documentFeedResponse -> Flux.fromIterable(documentFeedResponse.getResults())) + .map( ServiceItemLease::fromDocument); + } + + private String getDocumentId(String leaseToken) + { + return this.getPartitionLeasePrefix() + leaseToken; + } + + private String getPartitionLeasePrefix() + { + return this.settings.getContainerNamePrefix() + ".."; + } + + private CosmosItem createItemForLease(String leaseId) { + return this.leaseDocumentClient.getContainerClient().getItem(leaseId, "/id"); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java new file mode 100644 index 0000000000000..e31e9d32a8bc2 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java @@ -0,0 +1,83 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedObserverCloseReason; +import com.microsoft.azure.cosmos.ChangeFeedObserverContext; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.changefeed.exceptions.ObserverException; + +import java.util.List; + +/** + * Exception wrapping decorator implementation for {@link ChangeFeedObserver}. + */ +public class ObserverExceptionWrappingChangeFeedObserverDecorator implements ChangeFeedObserver { + private ChangeFeedObserver changeFeedObserver; + + public ObserverExceptionWrappingChangeFeedObserverDecorator(ChangeFeedObserver changeFeedObserver) + { + this.changeFeedObserver = changeFeedObserver; + } + + @Override + public void open(ChangeFeedObserverContext context) { + try + { + this.changeFeedObserver.open(context); + } + catch (RuntimeException userException) + { + // Logger.WarnException("Exception happened on Observer.OpenAsync", userException); + throw new ObserverException(userException); + } + } + + @Override + public void close(ChangeFeedObserverContext context, ChangeFeedObserverCloseReason reason) { + try + { + this.changeFeedObserver.close(context, reason); + } + catch (RuntimeException userException) + { + // Logger.WarnException("Exception happened on Observer.CloseAsync", userException); + throw new ObserverException(userException); + } + } + + @Override + public void processChanges(ChangeFeedObserverContext context, List docs) { + try + { + this.changeFeedObserver.processChanges(context, docs); + } + catch (Exception userException) + { + // Logger.WarnException("Exception happened on Observer.OpenAsync", userException); + throw new ObserverException(userException); + } + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionCheckpointerImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionCheckpointerImpl.java new file mode 100644 index 0000000000000..bda13fdfaeba8 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionCheckpointerImpl.java @@ -0,0 +1,56 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.LeaseCheckpointer; +import com.microsoft.azure.cosmos.changefeed.PartitionCheckpointer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; + +/** + * Checkpoint the given partition up to the given continuation token. + */ +public class PartitionCheckpointerImpl implements PartitionCheckpointer { + private final Logger logger = LoggerFactory.getLogger(PartitionCheckpointerImpl.class); + private final LeaseCheckpointer leaseCheckpointer; + private Lease lease; + + public PartitionCheckpointerImpl(LeaseCheckpointer leaseCheckpointer, Lease lease) { + this.leaseCheckpointer = leaseCheckpointer; + this.lease = lease; + } + + @Override + public Mono checkpointPartition(String сontinuationToken) { + PartitionCheckpointerImpl self = this; + return this.leaseCheckpointer.checkpoint(this.lease, сontinuationToken) + .map(lease1 -> { + self.lease = lease1; + logger.info(String.format("Checkpoint: partition %s, new continuation %s", self.lease.getLeaseToken(), self.lease.getContinuationToken())); + return lease1; + }) + .then(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionControllerImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionControllerImpl.java new file mode 100644 index 0000000000000..ac6d9d56ddea8 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionControllerImpl.java @@ -0,0 +1,185 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.CancellationToken; +import com.microsoft.azure.cosmos.changefeed.CancellationTokenSource; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.LeaseContainer; +import com.microsoft.azure.cosmos.changefeed.LeaseManager; +import com.microsoft.azure.cosmos.changefeed.PartitionController; +import com.microsoft.azure.cosmos.changefeed.PartitionSupervisor; +import com.microsoft.azure.cosmos.changefeed.PartitionSupervisorFactory; +import com.microsoft.azure.cosmos.changefeed.PartitionSynchronizer; +import com.microsoft.azure.cosmos.changefeed.exceptions.PartitionSplitException; +import com.microsoft.azure.cosmos.changefeed.exceptions.TaskCancelledException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; + +/** + * Implementation for {@link PartitionController}. + */ +public class PartitionControllerImpl implements PartitionController { + private final Logger logger = LoggerFactory.getLogger(PartitionControllerImpl.class); + // private final Map currentlyOwnedPartitions = new ConcurrentHashMap(); + private final Map currentlyOwnedPartitions = new ConcurrentHashMap<>(); + + private final LeaseContainer leaseContainer; + private final LeaseManager leaseManager; + private final PartitionSupervisorFactory partitionSupervisorFactory; + private final PartitionSynchronizer synchronizer; + private CancellationTokenSource shutdownCts; + + private final ExecutorService executorService; + + public PartitionControllerImpl( + LeaseContainer leaseContainer, + LeaseManager leaseManager, + PartitionSupervisorFactory partitionSupervisorFactory, + PartitionSynchronizer synchronizer, + ExecutorService executorService) { + + this.leaseContainer = leaseContainer; + this.leaseManager = leaseManager; + this.partitionSupervisorFactory = partitionSupervisorFactory; + this.synchronizer = synchronizer; + this.executorService = executorService; + } + + @Override + public Mono initialize() { + this.shutdownCts = new CancellationTokenSource(); + return this.loadLeases(); + } + + @Override + public synchronized Mono addOrUpdateLease(Lease lease) { + WorkerTask workerTask = this.currentlyOwnedPartitions.get(lease.getLeaseToken()); + if ( workerTask != null && workerTask.isRunning()) { + Lease updatedLease = this.leaseManager.updateProperties(lease).block(); + logger.debug(String.format("Partition %s: updated.", lease.getLeaseToken())); + return Mono.just(updatedLease); + } + + try { + Lease updatedLease = this.leaseManager.acquire(lease).block(); + if (updatedLease != null) lease = updatedLease; + + logger.info(String.format("Partition %s: acquired.", lease.getLeaseToken())); + } catch (RuntimeException ex) { + this.removeLease(lease).block(); + throw ex; + } + + PartitionSupervisor supervisor = this.partitionSupervisorFactory.create(lease); + this.currentlyOwnedPartitions.put(lease.getLeaseToken(), this.processPartition(supervisor, lease)); + + return Mono.just(lease); + } + + @Override + public Mono shutdown() { + // TODO: wait for the threads to finish. + this.shutdownCts.cancel(); +// this.currentlyOwnedPartitions.clear(); + + return Mono.empty(); + } + + private Mono loadLeases() { + PartitionControllerImpl self = this; + logger.debug("Starting renew leases assigned to this host on initialize."); + + return this.leaseContainer.getOwnedLeases() + .flatMap( lease -> { + logger.info(String.format("Acquired lease for PartitionId '%s' on startup.", lease.getLeaseToken())); + return self.addOrUpdateLease(lease); + }).then(); + } + + private Mono removeLease(Lease lease) { + return Mono.fromRunnable(() -> { + if (this.currentlyOwnedPartitions.get(lease.getLeaseToken()) != null) { + WorkerTask workerTask = this.currentlyOwnedPartitions.remove(lease.getLeaseToken()); + + if (workerTask.isRunning()) { + workerTask.interrupt(); + } + + logger.info(String.format("Partition %s: released.", lease.getLeaseToken())); + + try { + this.leaseManager.release(lease).block(); + } catch (Exception e) { + logger.warn(String.format("Partition %s: failed to remove lease.", lease.getLeaseToken()), e); + } finally { + // TODO: Stop the corresponding threads. + } + } + }); + } + + private WorkerTask processPartition(PartitionSupervisor partitionSupervisor, Lease lease) { + PartitionControllerImpl self = this; + + CancellationToken cancellationToken = this.shutdownCts.getToken(); + + WorkerTask partitionSupervisorTask = new WorkerTask(Mono.fromRunnable( () -> { + try { + partitionSupervisor.run(cancellationToken).block(); + } catch (PartitionSplitException ex) { + self.handleSplit(lease, ex.getLastContinuation()).block(); + } catch (TaskCancelledException tcex) { + logger.debug(String.format("Partition %s: processing canceled.", lease.getLeaseToken())); + } catch (Exception e) { + logger.warn(String.format("Partition %s: processing failed.", lease.getLeaseToken()), e); + } + + self.removeLease(lease).block(); + })); + + this.executorService.execute(partitionSupervisorTask); + + return partitionSupervisorTask; + } + + private Mono handleSplit(Lease lease, String lastContinuationToken) { + PartitionControllerImpl self = this; + + lease.setContinuationToken(lastContinuationToken); + return this.synchronizer.splitPartition(lease) + .flatMap(l -> { + l.setProperties(lease.getProperties()); + return self.addOrUpdateLease(l); + }).then(self.leaseManager.delete(lease)) + .onErrorResume(throwable -> { + logger.warn(String.format("partition %s: failed to split", lease.getLeaseToken()), throwable); + return Mono.empty(); + }); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java new file mode 100644 index 0000000000000..f8ec5febcd2bd --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java @@ -0,0 +1,143 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.CancellationToken; +import com.microsoft.azure.cosmos.changefeed.CancellationTokenSource; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.LeaseContainer; +import com.microsoft.azure.cosmos.changefeed.PartitionController; +import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancer; +import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancingStrategy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.ExecutorService; + +/** + * Implementation for {@link PartitionLoadBalancer}. + */ +public class PartitionLoadBalancerImpl implements PartitionLoadBalancer { + private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); + private final PartitionController partitionController; + private final LeaseContainer leaseContainer; + private final PartitionLoadBalancingStrategy partitionLoadBalancingStrategy; + private final Duration leaseAcquireInterval; + private final ExecutorService executorService; + + private CancellationTokenSource cancellationTokenSource; + + private volatile boolean started; + + private final Object lock; + + public PartitionLoadBalancerImpl( + PartitionController partitionController, + LeaseContainer leaseContainer, + PartitionLoadBalancingStrategy partitionLoadBalancingStrategy, + Duration leaseAcquireInterval, + ExecutorService executorService) { + + if (partitionController == null) throw new IllegalArgumentException("partitionController"); + if (leaseContainer == null) throw new IllegalArgumentException("leaseContainer"); + if (partitionLoadBalancingStrategy == null) throw new IllegalArgumentException("partitionLoadBalancingStrategy"); + if (executorService == null) throw new IllegalArgumentException("executorService"); + + this.partitionController = partitionController; + this.leaseContainer = leaseContainer; + this.partitionLoadBalancingStrategy = partitionLoadBalancingStrategy; + this.leaseAcquireInterval = leaseAcquireInterval; + this.executorService = executorService; + + this.started = false; + this.lock = new Object(); + } + + @Override + public Mono start() { + PartitionLoadBalancerImpl self = this; + + return Mono.fromRunnable( () -> { + synchronized (lock) { + if (this.started) { + throw new IllegalStateException("Partition load balancer already started"); + } + + this.started = true; + this.cancellationTokenSource = new CancellationTokenSource(); + } + + CancellationToken cancellationToken = this.cancellationTokenSource.getToken(); + + this.executorService.execute(() -> self.run(cancellationToken).block()); + }); + } + + @Override + public Mono stop() { + return Mono.fromRunnable( () -> { + synchronized (lock) { + this.started = false; + + this.cancellationTokenSource.cancel(); + this.partitionController.shutdown().block(); + this.cancellationTokenSource = null; + } + }); + } + + private Mono run(CancellationToken cancellationToken) { + PartitionLoadBalancerImpl self = this; + + return Mono.fromRunnable( () -> { + try { + while (!cancellationToken.isCancellationRequested()) { + List allLeases = self.leaseContainer.getAllLeases().collectList().block(); + List leasesToTake = self.partitionLoadBalancingStrategy.selectLeasesToTake(allLeases); + for (Lease lease : leasesToTake) { + self.partitionController.addOrUpdateLease(lease).block(); + } + + long remainingWork = this.leaseAcquireInterval.toMillis(); + + try { + while (!cancellationToken.isCancellationRequested() && remainingWork > 0) { + Thread.sleep(100); + remainingWork -= 100; + } + } catch (InterruptedException ex) { + // exception caught + logger.warn("Partition load balancer caught an interrupted exception", ex); + } + } + } catch (Exception ex) { + // We should not get here. + logger.info("Partition load balancer task stopped."); + this.stop(); + } + }); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionManagerImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionManagerImpl.java new file mode 100644 index 0000000000000..933b7d745aab1 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionManagerImpl.java @@ -0,0 +1,59 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.Bootstrapper; +import com.microsoft.azure.cosmos.changefeed.PartitionController; +import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancer; +import com.microsoft.azure.cosmos.changefeed.PartitionManager; +import reactor.core.publisher.Mono; + +/** + * Implementation for {@link PartitionManager}. + */ +public class PartitionManagerImpl implements PartitionManager { + private final Bootstrapper bootstrapper; + private final PartitionController partitionController; + private final PartitionLoadBalancer partitionLoadBalancer; + + public PartitionManagerImpl(Bootstrapper bootstrapper, PartitionController partitionController, PartitionLoadBalancer partitionLoadBalancer) { + this.bootstrapper = bootstrapper; + this.partitionController = partitionController; + this.partitionLoadBalancer = partitionLoadBalancer; + } + + @Override + public Mono start() { + PartitionManagerImpl self = this; + + return this.bootstrapper.initialize() + .then(this.partitionController.initialize()) + .then(Mono.fromRunnable(self.partitionLoadBalancer::start)); + } + + @Override + public Mono stop() { + PartitionManagerImpl self = this; + return Mono.fromRunnable(self.partitionLoadBalancer::stop); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java new file mode 100644 index 0000000000000..29199374604e0 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java @@ -0,0 +1,85 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedProcessorOptions; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.LeaseCheckpointer; +import com.microsoft.azure.cosmos.changefeed.PartitionCheckpointer; +import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; +import com.microsoft.azure.cosmos.changefeed.PartitionProcessorFactory; +import com.microsoft.azure.cosmos.changefeed.ProcessorSettings; + +/** + * Implementation for {@link PartitionProcessorFactory}. + */ +public class PartitionProcessorFactoryImpl implements PartitionProcessorFactory { + private final ChangeFeedContextClient documentClient; + private final ChangeFeedProcessorOptions changeFeedProcessorOptions; + private final LeaseCheckpointer leaseCheckpointer; + private final CosmosContainer collectionSelfLink; + + public PartitionProcessorFactoryImpl( + ChangeFeedContextClient documentClient, + ChangeFeedProcessorOptions changeFeedProcessorOptions, + LeaseCheckpointer leaseCheckpointer, + CosmosContainer collectionSelfLink) { + + if (documentClient == null) throw new IllegalArgumentException("documentClient"); + if (changeFeedProcessorOptions == null) throw new IllegalArgumentException("changeFeedProcessorOptions"); + if (leaseCheckpointer == null) throw new IllegalArgumentException("leaseCheckpointer"); + if (collectionSelfLink == null) throw new IllegalArgumentException("collectionSelfLink"); + + this.documentClient = documentClient; + this.changeFeedProcessorOptions = changeFeedProcessorOptions; + this.leaseCheckpointer = leaseCheckpointer; + this.collectionSelfLink = collectionSelfLink; + } + + @Override + public PartitionProcessor create(Lease lease, ChangeFeedObserver observer) { + if (observer == null) throw new IllegalArgumentException("observer"); + if (lease == null) throw new IllegalArgumentException("lease"); + + String startContinuation = lease.getContinuationToken(); + + if (startContinuation == null || startContinuation.isEmpty()) { + startContinuation = this.changeFeedProcessorOptions.getStartContinuation(); + } + + ProcessorSettings settings = new ProcessorSettings() + .withCollectionLink(this.collectionSelfLink) + .withStartContinuation(startContinuation) + .withPartitionKeyRangeId(lease.getLeaseToken()) + .withFeedPollDelay(this.changeFeedProcessorOptions.getFeedPollDelay()) + .withMaxItemCount(this.changeFeedProcessorOptions.getMaxItemCount()) + .withStartFromBeginning(this.changeFeedProcessorOptions.isStartFromBeginning()) + .withStartTime(this.changeFeedProcessorOptions.getStartTime()); // .withSessionToken(this.changeFeedProcessorOptions.getSessionToken()); + + PartitionCheckpointer checkpointer = new PartitionCheckpointerImpl(this.leaseCheckpointer, lease); + return new PartitionProcessorImpl(observer, this.documentClient, settings, checkpointer); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorImpl.java new file mode 100644 index 0000000000000..f9db2d7dfd507 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorImpl.java @@ -0,0 +1,174 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedObserverContext; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.changefeed.CancellationToken; +import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; +import com.microsoft.azure.cosmos.changefeed.PartitionCheckpointer; +import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; +import com.microsoft.azure.cosmos.changefeed.ProcessorSettings; +import com.microsoft.azure.cosmos.changefeed.exceptions.PartitionNotFoundException; +import com.microsoft.azure.cosmos.changefeed.exceptions.PartitionSplitException; +import com.microsoft.azure.cosmos.changefeed.exceptions.TaskCancelledException; +import com.microsoft.azure.cosmosdb.ChangeFeedOptions; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmosdb.FeedResponse; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.util.List; + +/** + * Implementation for {@link PartitionProcessor}. + */ +public class PartitionProcessorImpl implements PartitionProcessor { + private static final int DefaultMaxItemCount = 100; + // private final Observable> query; + private final ProcessorSettings settings; + private final PartitionCheckpointer checkpointer; + private final ChangeFeedObserver observer; + private final ChangeFeedOptions options; + private final ChangeFeedContextClient documentClient; + private RuntimeException resultException; + + private String lastContinuation; + + public PartitionProcessorImpl(ChangeFeedObserver observer, ChangeFeedContextClient documentClient, ProcessorSettings settings, PartitionCheckpointer checkpointer) { + this.observer = observer; + this.documentClient = documentClient; + this.settings = settings; + this.checkpointer = checkpointer; + + this.options = new ChangeFeedOptions(); + this.options.setMaxItemCount(settings.getMaxItemCount()); + this.options.setPartitionKeyRangeId(settings.getPartitionKeyRangeId()); + // this.options.setSessionToken(settings.getSessionToken()); + this.options.setStartFromBeginning(settings.isStartFromBeginning()); + this.options.setRequestContinuation(settings.getStartContinuation()); + this.options.setStartDateTime(settings.getStartTime()); + + //this.query = documentClient.createDocumentChangeFeedQuery(self.settings.getCollectionSelfLink(), this.options); + } + + @Override + public Mono run(CancellationToken cancellationToken) { + PartitionProcessorImpl self = this; + this.lastContinuation = this.settings.getStartContinuation(); + + return Mono.fromRunnable( () -> { + while (!cancellationToken.isCancellationRequested()) { + Duration delay = self.settings.getFeedPollDelay(); + + try { + self.options.setRequestContinuation(self.lastContinuation); + List> documentFeedResponseList = self.documentClient.createDocumentChangeFeedQuery(self.settings.getCollectionSelfLink(), self.options) + .collectList() + .block(); + + for (FeedResponse documentFeedResponse : documentFeedResponseList) { + self.lastContinuation = documentFeedResponse.getResponseContinuation(); + if (documentFeedResponse.getResults() != null && documentFeedResponse.getResults().size() > 0) { + self.dispatchChanges(documentFeedResponse); + } + + self.options.setRequestContinuation(self.lastContinuation); + + if (cancellationToken.isCancellationRequested()) { + // Observation was cancelled. + throw new TaskCancelledException(); + } + } + + if (this.options.getMaxItemCount().compareTo(this.settings.getMaxItemCount()) == 0) { + this.options.setMaxItemCount(this.settings.getMaxItemCount()); // Reset after successful execution. + } + } catch (RuntimeException ex) { + if (ex.getCause() instanceof DocumentClientException) { + + DocumentClientException clientException = (DocumentClientException) ex.getCause(); + // this.logger.WarnException("exception: partition '{0}'", clientException, this.settings.PartitionKeyRangeId); + StatusCodeErrorType docDbError = ExceptionClassifier.classifyClientException(clientException); + + switch (docDbError) { + case PARTITION_NOT_FOUND: { + self.resultException = new PartitionNotFoundException("Partition not found.", self.lastContinuation); + } + case PARTITION_SPLIT: { + self.resultException = new PartitionSplitException("Partition split.", self.lastContinuation); + } + case UNDEFINED: { + self.resultException = ex; + } + case MAX_ITEM_COUNT_TOO_LARGE: { + if (this.options.getMaxItemCount() == null) { + this.options.setMaxItemCount(DefaultMaxItemCount); + } else if (this.options.getMaxItemCount() <= 1) { + // this.logger.ErrorFormat("Cannot reduce maxItemCount further as it's already at {0}.", this.options.MaxItemCount); + throw ex; + } + + this.options.setMaxItemCount(this.options.getMaxItemCount() / 2); + // this.logger.WarnFormat("Reducing maxItemCount, new value: {0}.", this.options.MaxItemCount); + break; + } + default: { + // this.logger.Fatal($"Unrecognized DocDbError enum value {docDbError}"); + // Debug.Fail($"Unrecognized DocDbError enum value {docDbError}"); + self.resultException = ex; + } + } + } else if (ex instanceof TaskCancelledException) { + // this.logger.WarnException("exception: partition '{0}'", canceledException, this.settings.PartitionKeyRangeId); + self.resultException = ex; + } + } + + long remainingWork = delay.toMillis(); + + try { + while (!cancellationToken.isCancellationRequested() && remainingWork > 0) { + Thread.sleep(100); + remainingWork -= 100; + } + } catch (InterruptedException iex) { + // exception caught + } + } + }); + } + + @Override + public RuntimeException getResultException() { + return this.resultException; + } + + private void dispatchChanges(FeedResponse response) { + ChangeFeedObserverContext context = new ChangeFeedObserverContextImpl(this.settings.getPartitionKeyRangeId(), response, this.checkpointer); + + this.observer.processChanges(context, response.getResults()); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java new file mode 100644 index 0000000000000..282a0dbe0ca12 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java @@ -0,0 +1,77 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedObserverFactory; +import com.microsoft.azure.cosmos.ChangeFeedProcessorOptions; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.LeaseManager; +import com.microsoft.azure.cosmos.changefeed.LeaseRenewer; +import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; +import com.microsoft.azure.cosmos.changefeed.PartitionProcessorFactory; +import com.microsoft.azure.cosmos.changefeed.PartitionSupervisor; +import com.microsoft.azure.cosmos.changefeed.PartitionSupervisorFactory; + +import java.util.concurrent.ExecutorService; + +/** + * Implementation for the partition supervisor factory. + */ +public class PartitionSupervisorFactoryImpl implements PartitionSupervisorFactory { + private final ChangeFeedObserverFactory observerFactory; + private final LeaseManager leaseManager; + private final ChangeFeedProcessorOptions changeFeedProcessorOptions; + private final PartitionProcessorFactory partitionProcessorFactory; + private final ExecutorService executorService; + + + public PartitionSupervisorFactoryImpl( + ChangeFeedObserverFactory observerFactory, + LeaseManager leaseManager, + PartitionProcessorFactory partitionProcessorFactory, + ChangeFeedProcessorOptions options, + ExecutorService executorService) { + if (observerFactory == null) throw new IllegalArgumentException("observerFactory"); + if (leaseManager == null) throw new IllegalArgumentException("leaseManager"); + if (options == null) throw new IllegalArgumentException("options"); + if (partitionProcessorFactory == null) throw new IllegalArgumentException("partitionProcessorFactory"); + + this.observerFactory = observerFactory; + this.leaseManager = leaseManager; + this.changeFeedProcessorOptions = options; + this.partitionProcessorFactory = partitionProcessorFactory; + this.executorService = executorService; + } + + @Override + public PartitionSupervisor create(Lease lease) { + if (lease == null) throw new IllegalArgumentException("lease"); + + ChangeFeedObserver changeFeedObserver = this.observerFactory.createObserver(); + PartitionProcessor processor = this.partitionProcessorFactory.create(lease, changeFeedObserver); + LeaseRenewer renewer = new LeaseRenewerImpl(lease, this.leaseManager, this.changeFeedProcessorOptions.getLeaseRenewInterval()); + + return new PartitionSupervisorImpl(lease, changeFeedObserver, processor, renewer, this.executorService); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorImpl.java new file mode 100644 index 0000000000000..3ba263e148e40 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorImpl.java @@ -0,0 +1,168 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.microsoft.azure.cosmos.ChangeFeedObserverCloseReason; +import com.microsoft.azure.cosmos.ChangeFeedObserverContext; +import com.microsoft.azure.cosmos.changefeed.CancellationToken; +import com.microsoft.azure.cosmos.changefeed.CancellationTokenSource; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.LeaseRenewer; +import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; +import com.microsoft.azure.cosmos.changefeed.PartitionSupervisor; +import com.microsoft.azure.cosmos.changefeed.exceptions.LeaseLostException; +import com.microsoft.azure.cosmos.changefeed.exceptions.ObserverException; +import com.microsoft.azure.cosmos.changefeed.exceptions.PartitionSplitException; +import com.microsoft.azure.cosmos.changefeed.exceptions.TaskCancelledException; +import reactor.core.publisher.Mono; + +import java.io.Closeable; +import java.io.IOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Implementation for {@link PartitionSupervisor}. + */ +public class PartitionSupervisorImpl implements PartitionSupervisor, Closeable { + private final Lease lease; + private final ChangeFeedObserver observer; + private final PartitionProcessor processor; + private final LeaseRenewer renewer; + private CancellationTokenSource renewerCancellation; + private CancellationTokenSource processorCancellation; + + private RuntimeException resultException; + + private ExecutorService executorService; + + public PartitionSupervisorImpl(Lease lease, ChangeFeedObserver observer, PartitionProcessor processor, LeaseRenewer renewer, ExecutorService executorService) { + this.lease = lease; + this.observer = observer; + this.processor = processor; + this.renewer = renewer; + this.executorService = executorService; + + if (executorService == null) { + this.executorService = Executors.newFixedThreadPool(3); + } + } + + @Override + public Mono run(CancellationToken shutdownToken) { + PartitionSupervisorImpl self = this; + this.resultException = null; + + return Mono.fromRunnable(() -> { + + ChangeFeedObserverContext context = new ChangeFeedObserverContextImpl(self.lease.getLeaseToken()); + + self.observer.open(context); + + ChangeFeedObserverCloseReason closeReason = ChangeFeedObserverCloseReason.UNKNOWN; + + try { + self.processorCancellation = new CancellationTokenSource(); + + Thread processorThread = new Thread(new Runnable() { + @Override + public void run() { + self.processor.run(self.processorCancellation.getToken()).block(); + } + }); + + self.renewerCancellation = new CancellationTokenSource(); + + Thread renewerThread = new Thread(new Runnable() { + @Override + public void run() { + self.renewer.run(self.renewerCancellation.getToken()).block(); + } + }); + + self.executorService.execute(processorThread); + self.executorService.execute(renewerThread); + + while (!shutdownToken.isCancellationRequested() && self.processor.getResultException() == null && self.renewer.getResultException() == null) { + try { + Thread.sleep(100); + } catch (InterruptedException iex) { + break; + } + } + + this.processorCancellation.cancel(); + this.renewerCancellation.cancel(); + executorService.shutdown(); + + if (self.processor.getResultException() != null) { + throw self.processor.getResultException(); + } + + if (self.renewer.getResultException() != null) { + throw self.renewer.getResultException(); + } + + closeReason = shutdownToken.isCancellationRequested() ? + ChangeFeedObserverCloseReason.SHUTDOWN : + ChangeFeedObserverCloseReason.UNKNOWN; + + } catch (LeaseLostException llex) { + closeReason = ChangeFeedObserverCloseReason.LEASE_LOST; + self.resultException = llex; + } catch (PartitionSplitException pex) { + closeReason = ChangeFeedObserverCloseReason.LEASE_GONE; + self.resultException = pex; + } catch (TaskCancelledException tcex) { + closeReason = ChangeFeedObserverCloseReason.SHUTDOWN; + self.resultException = null; + } catch (ObserverException oex) { + closeReason = ChangeFeedObserverCloseReason.OBSERVER_ERROR; + self.resultException = oex; + } catch (Exception ex) { + closeReason = ChangeFeedObserverCloseReason.UNKNOWN; + } finally { + self.observer.close(context, closeReason); + + if (self.resultException != null) { + Mono.error(self.resultException); + } + } + }); + } + + @Override + public RuntimeException getResultException() { + return this.resultException; + } + + @Override + public void close() throws IOException { + if (this.processorCancellation != null) { + this.processorCancellation.close(); + } + + this.renewerCancellation.close(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSynchronizerImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSynchronizerImpl.java new file mode 100644 index 0000000000000..5577c6253d4d5 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSynchronizerImpl.java @@ -0,0 +1,172 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.LeaseContainer; +import com.microsoft.azure.cosmos.changefeed.LeaseManager; +import com.microsoft.azure.cosmos.changefeed.PartitionSynchronizer; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.HashSet; +import java.util.Set; + +/** + * Implementation for the partition synchronizer. + */ +public class PartitionSynchronizerImpl implements PartitionSynchronizer { + private final Logger logger = LoggerFactory.getLogger(PartitionSynchronizerImpl.class); + private final ChangeFeedContextClient documentClient; + private final CosmosContainer collectionSelfLink; + private final LeaseContainer leaseContainer; + private final LeaseManager leaseManager; + private final int degreeOfParallelism; + private final int maxBatchSize; + + public PartitionSynchronizerImpl( + ChangeFeedContextClient documentClient, + CosmosContainer collectionSelfLink, + LeaseContainer leaseContainer, + LeaseManager leaseManager, + int degreeOfParallelism, + int maxBatchSize) + { + this.documentClient = documentClient; + this.collectionSelfLink = collectionSelfLink; + this.leaseContainer = leaseContainer; + this.leaseManager = leaseManager; + this.degreeOfParallelism = degreeOfParallelism; + this.maxBatchSize = maxBatchSize; + } + + @Override + public Mono createMissingLeases() { + PartitionSynchronizerImpl self = this; + + return this.enumPartitionKeyRanges() + .map(partitionKeyRange -> { + // TODO: log the partition key ID found. + return partitionKeyRange.getId(); + }) + .collectList() + .flatMap( partitionKeyRangeIds -> { + Set leaseTokens = new HashSet<>(partitionKeyRangeIds); + return self.createLeases(leaseTokens).then(); + }) + .onErrorResume( throwable -> { + // TODO: log the exception. + return Mono.empty(); + }); + } + + @Override + public Flux splitPartition(Lease lease) { + if (lease == null) throw new IllegalArgumentException("lease"); + + PartitionSynchronizerImpl self = this; + String leaseToken = lease.getLeaseToken(); + String lastContinuationToken = lease.getContinuationToken(); + + logger.info(String.format("Partition %s is gone due to split.", leaseToken)); + + // After a split, the children are either all or none available + return this.enumPartitionKeyRanges() + .filter(range -> range != null && range.getParents() != null && range.getParents().contains(leaseToken)) + .map(PartitionKeyRange::getId) + .collectList() + .flatMapMany(addedLeaseTokens -> { + if (addedLeaseTokens.size() == 0) { + logger.error(String.format("Partition %s had split but we failed to find at least one child partition", leaseToken)); + throw new RuntimeException(String.format("Partition %s had split but we failed to find at least one child partition", leaseToken)); + } + return Flux.fromIterable(addedLeaseTokens); + }) + .flatMap(addedRangeId -> { + // Creating new lease. + return self.leaseManager.createLeaseIfNotExist(addedRangeId, lastContinuationToken); + }, self.degreeOfParallelism) + .map(newLease -> { + logger.info(String.format("Partition %s split into new partition with lease token %s.", leaseToken, newLease.getLeaseToken())); + return newLease; + }); + } + + private Flux enumPartitionKeyRanges() { + // String partitionKeyRangesPath = String.format("%spkranges", this.collectionSelfLink); + String partitionKeyRangesPath = CosmosContainer.getSelfLink(this.collectionSelfLink); + FeedOptions feedOptions = new FeedOptions(); + feedOptions.setMaxItemCount(this.maxBatchSize); + feedOptions.setRequestContinuation(null); + + return this.documentClient.readPartitionKeyRangeFeed(partitionKeyRangesPath, feedOptions) + .map(partitionKeyRangeFeedResponse -> partitionKeyRangeFeedResponse.getResults()) + .flatMap(partitionKeyRangeList -> Flux.fromIterable(partitionKeyRangeList)) + .onErrorResume(throwable -> { + // TODO: Log the exception. + return Flux.empty(); + }); + } + + /** + * Creates leases if they do not exist. This might happen on initial start or if some lease was unexpectedly lost. + *

+ * Leases are created without the continuation token. It means partitions will be read according to + * 'From Beginning' or 'From current time'. + * Same applies also to split partitions. We do not search for parent lease and take continuation token since this + * might end up of reprocessing all the events since the split. + * + * @param leaseTokens a hash set of all the lease tokens. + * @return a deferred computation of this call. + */ + private Flux createLeases(Set leaseTokens) + { + PartitionSynchronizerImpl self = this; + Set addedLeaseTokens = new HashSet<>(leaseTokens); + + return this.leaseContainer.getAllLeases() + .map(lease -> { + if (lease != null) { + // Get leases after getting ranges, to make sure that no other hosts checked in continuation for + // split partition after we got leases. + addedLeaseTokens.remove(lease.getLeaseToken()); + } + + return lease; + }) + .thenMany(Flux.fromIterable(addedLeaseTokens) + .flatMap( addedRangeId -> + self.leaseManager.createLeaseIfNotExist(addedRangeId, null), self.degreeOfParallelism) + .map( lease -> { + // TODO: log the lease info that was added. + return lease; + }) + ); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java new file mode 100644 index 0000000000000..4fd7e7601259f --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java @@ -0,0 +1,51 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.changefeed.Lease; +import com.microsoft.azure.cosmos.changefeed.RequestOptionsFactory; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.RequestOptions; + +/** + * Used to create request options for partitioned lease collections, when partition key is defined as /id. + */ +public class PartitionedByIdCollectionRequestOptionsFactory implements RequestOptionsFactory { + @Override + public CosmosItemRequestOptions createRequestOptions(Lease lease) { + CosmosItemRequestOptions requestOptions = new CosmosItemRequestOptions(); + requestOptions.setPartitionKey(new PartitionKey(lease.getId())); + + return requestOptions; + } + + @Override + public FeedOptions createFeedOptions() { + FeedOptions feedOptions = new FeedOptions(); + feedOptions.setEnableCrossPartitionQuery(true); + + return feedOptions; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java new file mode 100644 index 0000000000000..b39a546ea0ba6 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java @@ -0,0 +1,57 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.RemainingPartitionWork; + +/** + * Implements the {@link RemainingPartitionWork} interface. + */ +public class RemainingPartitionWorkImpl implements RemainingPartitionWork { + private final String partitionKeyRangeId; + private final long remainingWork; + + /** + * Initializes a new instance of the {@link RemainingPartitionWork} object. + * + * @param partitionKeyRangeId the partition key range ID for which the remaining work is calculated. + * @param remainingWork the amount of documents remaining to be processed. + */ + public RemainingPartitionWorkImpl(String partitionKeyRangeId, long remainingWork) { + if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) throw new IllegalArgumentException("partitionKeyRangeId"); + + this.partitionKeyRangeId = partitionKeyRangeId; + this.remainingWork = remainingWork; + } + + + @Override + public String getPartitionKeyRangeId() { + return this.partitionKeyRangeId; + } + + @Override + public long getRemainingWork() { + return this.remainingWork; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java new file mode 100644 index 0000000000000..119d535af2f6b --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java @@ -0,0 +1,85 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; +import com.microsoft.azure.cosmos.changefeed.LeaseContainer; +import com.microsoft.azure.cosmos.changefeed.RemainingPartitionWork; +import com.microsoft.azure.cosmos.changefeed.RemainingWorkEstimator; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Implementation for {@link RemainingWorkEstimator}. + */ +public class RemainingWorkEstimatorImpl implements RemainingWorkEstimator { + private final char PKRangeIdSeparator = ':'; + private final char SegmentSeparator = '#'; + private final String LSNPropertyName = "_lsn"; + private final ChangeFeedContextClient feedDocumentClient; + private final LeaseContainer leaseContainer; + private final String collectionSelfLink; + private final int degreeOfParallelism; + + public RemainingWorkEstimatorImpl( + LeaseContainer leaseContainer, + ChangeFeedContextClient feedDocumentClient, + String collectionSelfLink, + int degreeOfParallelism) { + + if (leaseContainer == null) throw new IllegalArgumentException("leaseContainer"); + if (collectionSelfLink == null || collectionSelfLink.isEmpty()) throw new IllegalArgumentException("collectionSelfLink"); + if (feedDocumentClient == null) throw new IllegalArgumentException("feedDocumentClient"); + if (degreeOfParallelism < 1) throw new IllegalArgumentException("degreeOfParallelism - Degree of parallelism is out of range"); + + this.leaseContainer = leaseContainer; + this.collectionSelfLink = collectionSelfLink; + this.feedDocumentClient = feedDocumentClient; + this.degreeOfParallelism = degreeOfParallelism; + } + + @Override + public Mono getEstimatedRemainingWork() { + return this.getEstimatedRemainingWorkPerPartition() + .map(RemainingPartitionWork::getRemainingWork) + .collectList() + .map(list -> { + long sum; + if (list.size() == 0) { + sum = 1; + } else { + sum = 0; + for (long value : list) { + sum += value; + } + } + + return sum; + }); + } + + @Override + public Flux getEstimatedRemainingWorkPerPartition() { + return null; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/StatusCodeErrorType.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/StatusCodeErrorType.java new file mode 100644 index 0000000000000..c4cbec2c1d793 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/StatusCodeErrorType.java @@ -0,0 +1,34 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +/** + * Groups types of status code errors returned while processing the change feeds. + */ +public enum StatusCodeErrorType { + UNDEFINED, + PARTITION_NOT_FOUND, + PARTITION_SPLIT, + TRANSIENT_ERROR, + MAX_ITEM_COUNT_TOO_LARGE +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/TraceHealthMonitor.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/TraceHealthMonitor.java new file mode 100644 index 0000000000000..0b71a28d42bdd --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/TraceHealthMonitor.java @@ -0,0 +1,44 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import com.microsoft.azure.cosmos.changefeed.HealthMonitor; +import com.microsoft.azure.cosmos.changefeed.HealthMonitoringRecord; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; + +/** + * Implementation for trace health monitor. + */ +public class TraceHealthMonitor implements HealthMonitor { + private final Logger logger = LoggerFactory.getLogger(TraceHealthMonitor.class); + @Override + public Mono inspect(HealthMonitoringRecord record) { + return Mono.fromRunnable(() -> { + if (record.getSeverity() == HealthMonitoringRecord.HealthSeverity.ERROR) { + logger.error(String.format("Unhealthiness detected in the operation %s for %s.", record.operation.name(), record.lease.getId()), record.throwable); + } + }); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/WorkerTask.java b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/WorkerTask.java new file mode 100644 index 0000000000000..5ceb41c7b7763 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/WorkerTask.java @@ -0,0 +1,50 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos.changefeed.internal; + +import reactor.core.publisher.Mono; + +/** + * Worker task that executes in a separate thread. + */ +public class WorkerTask extends Thread { + private boolean done = false; + private Mono job; + + WorkerTask(Mono job) { + this.job = job; + } + + @Override + public void run() { + try { + job.block(); + } finally { + this.done = true; + } + } + + public boolean isRunning() { + return !this.done; + } +} From cdd68cf5906282f786e2ac718f931accddab417c Mon Sep 17 00:00:00 2001 From: Srinath Narayanan Date: Sat, 8 Jun 2019 19:50:46 -0700 Subject: [PATCH 32/85] Added support for accessing non partitioned collections using V3 SDK (#107) * NP->P changes --- .gitignore | 3 + commons-test-utils/pom.xml | 4 + .../rx/FeedResponseListValidator.java | 36 +- commons/pom.xml | 25 + .../cosmos/CosmosContainerRequestOptions.java | 2 +- .../azure/cosmos/CosmosContainerSettings.java | 25 + .../cosmos/CosmosDatabaseRequestOptions.java | 2 +- .../azure/cosmos/CosmosDatabaseSettings.java | 2 +- .../azure/cosmos/CosmosFeedResponse.java | 0 .../cosmos/CosmosItemRequestOptions.java | 2 +- .../azure/cosmos/CosmosItemSettings.java | 11 + .../azure/cosmos/CosmosRequestOptions.java | 2 +- .../azure/cosmos/CosmosResource.java | 0 .../azure/cosmos/CosmosResponse.java | 22 +- .../CosmosStoredProcedureRequestOptions.java | 0 .../cosmos/CosmosStoredProcedureSettings.java | 0 .../azure/cosmos/CosmosTriggerSettings.java | 0 .../CosmosUserDefinedFunctionSettings.java | 0 .../azure/cosmos/CosmosUserSettings.java | 59 + .../azure/cosmosdb/BridgeInternal.java | 9 + .../azure/cosmosdb/PartitionKey.java | 2 + .../cosmosdb/PartitionKeyDefinition.java | 27 + .../azure/cosmosdb/internal/Constants.java | 1 + .../cosmosdb/internal/HttpConstants.java | 2 +- .../routing/PartitionKeyInternal.java | 18 + .../directconnectivity/AddressResolver.java | 2 +- .../routing/PartitionKeyInternalHelper.java | 4 + .../examples/CollectionCRUDAsyncAPITest.java | 5 + .../cosmosdb/rx/examples/ConflictAPITest.java | 7 + .../rx/examples/DocumentCRUDAsyncAPITest.java | 4 +- .../examples/DocumentQueryAsyncAPITest.java | 14 +- .../rx/examples/InMemoryGroupbyTest.java | 10 +- .../rx/examples/TokenResolverTest.java | 9 + .../rx/examples/UniqueIndexAsyncAPITest.java | 7 + .../DocumentQueryExecutionContextFactory.java | 28 +- .../microsoft/azure/cosmos/CosmosClient.java | 32 +- .../azure/cosmos/CosmosClientBuilder.java | 36 +- .../azure/cosmos/CosmosContainer.java | 70 +- .../azure/cosmos/CosmosDatabase.java | 30 +- .../microsoft/azure/cosmos/CosmosItem.java | 325 +++-- .../azure/cosmos/CosmosItemResponse.java | 122 +- .../azure/cosmos/CosmosTriggerResponse.java | 1 + .../microsoft/azure/cosmos/CosmosUser.java | 11 +- .../CosmosUserDefinedFunctionResponse.java | 113 +- .../azure/cosmos/CosmosUserResponse.java | 2 +- .../rx/internal/RxDocumentClientImpl.java | 16 +- .../rx => cosmos}/ClientUnderTestBuilder.java | 43 +- .../azure/cosmos/CosmosBridgeInternal.java | 34 + .../azure/cosmos/CosmosDatabaseForTest.java | 137 +++ .../azure/cosmos/CosmosPartitionKeyTests.java | 331 ++++++ .../azure/cosmos/CosmosResponseValidator.java | 378 ++++-- .../DCDocumentCrudTest.java | 13 +- .../GatewayAddressCacheTest.java | 4 +- ...GatewayServiceConfigurationReaderTest.java | 4 +- .../cosmosdb/rx/AggregateQueryTests.java | 60 +- .../azure/cosmosdb/rx/AttachmentCrudTest.java | 235 ---- .../cosmosdb/rx/AttachmentQueryTest.java | 199 ---- .../rx/BackPressureCrossPartitionTest.java | 118 +- .../azure/cosmosdb/rx/BackPressureTest.java | 130 +- .../azure/cosmosdb/rx/ChangeFeedTest.java | 6 +- .../azure/cosmosdb/rx/CollectionCrudTest.java | 669 ++++++----- .../cosmosdb/rx/CollectionQueryTest.java | 67 +- .../azure/cosmosdb/rx/DatabaseCrudTest.java | 67 +- .../azure/cosmosdb/rx/DatabaseQueryTest.java | 58 +- .../rx/DocumentClientResourceLeakTest.java | 37 +- .../azure/cosmosdb/rx/DocumentCrudTest.java | 830 +++++++------ .../azure/cosmosdb/rx/LogLevelTest.java | 94 +- .../rx/MultiMasterConflictResolutionTest.java | 429 +++---- .../cosmosdb/rx/MultiOrderByQueryTests.java | 89 +- .../azure/cosmosdb/rx/OfferQueryTest.java | 12 +- .../cosmosdb/rx/OfferReadReplaceTest.java | 7 +- .../cosmosdb/rx/OrderbyDocumentQueryTest.java | 187 ++- .../rx/ParallelDocumentQueryTest.java | 136 +-- .../azure/cosmosdb/rx/PermissionCrudTest.java | 2 + .../cosmosdb/rx/PermissionQueryTest.java | 4 +- .../azure/cosmosdb/rx/ProxyHostTest.java | 74 +- .../cosmosdb/rx/ReadFeedAttachmentsTest.java | 242 ---- .../cosmosdb/rx/ReadFeedCollectionsTest.java | 53 +- .../cosmosdb/rx/ReadFeedDatabasesTest.java | 41 +- .../cosmosdb/rx/ReadFeedDocumentsTest.java | 43 +- .../rx/ReadFeedExceptionHandlingTest.java | 77 +- .../azure/cosmosdb/rx/ReadFeedOffersTest.java | 12 +- .../cosmosdb/rx/ReadFeedPermissionsTest.java | 10 +- .../azure/cosmosdb/rx/ReadFeedPkrTests.java | 27 +- .../rx/ReadFeedStoredProceduresTest.java | 55 +- .../cosmosdb/rx/ReadFeedTriggersTest.java | 58 +- .../azure/cosmosdb/rx/ReadFeedUdfsTest.java | 41 +- .../azure/cosmosdb/rx/ReadFeedUsersTest.java | 48 +- .../azure/cosmosdb/rx/ResourceTokenTest.java | 33 +- .../cosmosdb/rx/SimpleSerializationTest.java | 44 +- .../rx/SinglePartitionDocumentQueryTest.java | 150 ++- .../SinglePartitionReadFeedDocumentsTest.java | 53 +- .../cosmosdb/rx/StoredProcedureCrudTest.java | 56 +- .../cosmosdb/rx/StoredProcedureQueryTest.java | 83 +- .../rx/StoredProcedureUpsertReplaceTest.java | 105 +- .../azure/cosmosdb/rx/TestSuiteBase.java | 630 +++++----- .../azure/cosmosdb/rx/TokenResolverTest.java | 4 +- .../azure/cosmosdb/rx/TopQueryTests.java | 75 +- .../azure/cosmosdb/rx/TriggerCrudTest.java | 59 +- .../azure/cosmosdb/rx/TriggerQueryTest.java | 70 +- .../cosmosdb/rx/TriggerUpsertReplaceTest.java | 85 +- .../azure/cosmosdb/rx/UniqueIndexTest.java | 133 ++- .../azure/cosmosdb/rx/UserCrudTest.java | 119 +- .../rx/UserDefinedFunctionCrudTest.java | 56 +- .../rx/UserDefinedFunctionQueryTest.java | 67 +- .../UserDefinedFunctionUpsertReplaceTest.java | 98 +- .../azure/cosmosdb/rx/UserQueryTest.java | 56 +- .../rx/VeryLargeDocumentQueryTest.java | 42 +- .../rx/internal/ConsistencyTests1.java | 2 +- .../rx/internal/ConsistencyTestsBase.java | 3 +- .../DocumentQuerySpyWireContentTest.java | 8 +- .../rx/internal/NetworkFailureTest.java | 4 +- .../rx/internal/RetryCreateDocumentTest.java | 3 +- .../rx/internal/RetryThrottleTest.java | 9 +- .../internal/RxDocumentClientUnderTest.java | 3 +- .../cosmosdb/rx/internal/SessionTest.java | 23 +- .../rx/internal/StoreHeaderTests.java | 3 +- .../cosmosdb/rx/internal/TestSuiteBase.java | 1045 +++++++++++++++++ .../directconnectivity/ReflectionUtils.java | 10 + 119 files changed, 5298 insertions(+), 4096 deletions(-) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java (99%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java (87%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java (99%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java (99%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java (100%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java (99%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java (89%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java (99%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java (100%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java (84%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java (100%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java (100%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java (100%) rename {sdk => commons}/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java (100%) create mode 100644 commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java rename sdk/src/test/java/com/microsoft/azure/{cosmosdb/rx => cosmos}/ClientUnderTestBuilder.java (50%) create mode 100644 sdk/src/test/java/com/microsoft/azure/cosmos/CosmosBridgeInternal.java create mode 100644 sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseForTest.java create mode 100644 sdk/src/test/java/com/microsoft/azure/cosmos/CosmosPartitionKeyTests.java rename sdk/src/test/java/com/microsoft/azure/cosmosdb/{rx => internal/directconnectivity}/DCDocumentCrudTest.java (96%) delete mode 100644 sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AttachmentCrudTest.java delete mode 100644 sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AttachmentQueryTest.java delete mode 100644 sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedAttachmentsTest.java create mode 100644 sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java diff --git a/.gitignore b/.gitignore index bdb262af0bac6..19547d6a1616a 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,6 @@ hs_err_pid* doc docs +target +bin +test-output diff --git a/commons-test-utils/pom.xml b/commons-test-utils/pom.xml index 977a5a5822a00..857a9edeb3d54 100644 --- a/commons-test-utils/pom.xml +++ b/commons-test-utils/pom.xml @@ -126,6 +126,10 @@ SOFTWARE. log4j ${log4j.version} + + io.projectreactor + reactor-core + com.google.guava guava diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FeedResponseListValidator.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FeedResponseListValidator.java index 6356f1363fff9..ccf6bdd3df98e 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FeedResponseListValidator.java +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FeedResponseListValidator.java @@ -32,6 +32,7 @@ import java.util.Map; import java.util.stream.Collectors; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.BridgeInternal; import com.fasterxml.jackson.databind.node.ArrayNode; import com.microsoft.azure.cosmosdb.CompositePath; @@ -72,7 +73,7 @@ public void validate(List> feedList) { return this; } - public Builder containsExactly(List expectedIds) { + public Builder containsExactly(List expectedRids) { validators.add(new FeedResponseListValidator() { @Override public void validate(List> feedList) { @@ -83,6 +84,23 @@ public void validate(List> feedList) { .collect(Collectors.toList()); assertThat(actualIds) .describedAs("Resource IDs of results") + .containsExactlyElementsOf(expectedRids); + } + }); + return this; + } + + public Builder containsExactlyIds(List expectedIds) { + validators.add(new FeedResponseListValidator() { + @Override + public void validate(List> feedList) { + List actualIds = feedList + .stream() + .flatMap(f -> f.getResults().stream()) + .map(r -> r.getId()) + .collect(Collectors.toList()); + assertThat(actualIds) + .describedAs("IDs of results") .containsExactlyElementsOf(expectedIds); } }); @@ -186,11 +204,11 @@ public void validate(List> feedList) { } public Builder withAggregateValue(Object value) { - validators.add(new FeedResponseListValidator() { + validators.add(new FeedResponseListValidator() { @Override - public void validate(List> feedList) { - List list = feedList.get(0).getResults(); - Document result = list.size() > 0 ? list.get(0) : null; + public void validate(List> feedList) { + List list = feedList.get(0).getResults(); + CosmosItemSettings result = list.size() > 0 ? list.get(0) : null; if (result != null) { if (value instanceof Double) { @@ -223,13 +241,13 @@ public void validate(List> feedList) { return this; } - public Builder withOrderedResults(ArrayList expectedOrderedList, + public Builder withOrderedResults(ArrayList expectedOrderedList, ArrayList compositeIndex) { - validators.add(new FeedResponseListValidator() { + validators.add(new FeedResponseListValidator() { @Override - public void validate(List> feedList) { + public void validate(List> feedList) { - List resultOrderedList = feedList.stream() + List resultOrderedList = feedList.stream() .flatMap(f -> f.getResults().stream()) .collect(Collectors.toList()); assertThat(expectedOrderedList.size()).isEqualTo(resultOrderedList.size()); diff --git a/commons/pom.xml b/commons/pom.xml index 2db549d7278de..293faef19f94d 100644 --- a/commons/pom.xml +++ b/commons/pom.xml @@ -194,6 +194,31 @@ SOFTWARE. ${log4j.version} test + + io.projectreactor + reactor-core + + + io.projectreactor.addons + reactor-adapter + ${reactor-addons.version} + test + + + io.projectreactor + reactor-test + test + + + com.github.akarnokd + rxjava2-interop + ${rxjava2interop.verison} + + + io.reactivex.rxjava2 + rxjava + ${rxjava2.version} + com.google.guava guava diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java similarity index 99% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java index 1ba2413c293bd..cbed66e3bc830 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java +++ b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java @@ -127,4 +127,4 @@ protected RequestOptions toRequestOptions() { requestOptions.setConsistencyLevel(consistencyLevel); return requestOptions; } -} +} \ No newline at end of file diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java similarity index 87% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java index 62989947a4f91..b5256f1915b71 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java +++ b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java @@ -22,6 +22,7 @@ */ package com.microsoft.azure.cosmos; +import com.microsoft.azure.cosmosdb.ConflictResolutionPolicy; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.IndexingPolicy; import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; @@ -179,6 +180,30 @@ public void setPartitionKey(PartitionKeyDefinition partitionKeyDefinition) { this.partitionKeyDefinition = partitionKeyDefinition; } + /** + * Gets the conflictResolutionPolicy that is used for resolving conflicting writes + * on documents in different regions, in a collection in the Azure Cosmos DB service. + * + * @return ConflictResolutionPolicy + */ + public ConflictResolutionPolicy getConflictResolutionPolicy() { + return super.getObject(Constants.Properties.CONFLICT_RESOLUTION_POLICY, ConflictResolutionPolicy.class); + } + + /** + * Sets the conflictResolutionPolicy that is used for resolving conflicting writes + * on documents in different regions, in a collection in the Azure Cosmos DB service. + * + * @param value ConflictResolutionPolicy to be used. + */ + public void setConflictResolutionPolicy(ConflictResolutionPolicy value) { + if (value == null) { + throw new IllegalArgumentException("CONFLICT_RESOLUTION_POLICY cannot be null."); + } + + super.set(Constants.Properties.CONFLICT_RESOLUTION_POLICY, value); + } + DocumentCollection getV2Collection(){ DocumentCollection collection = new DocumentCollection(this.toJson()); collection.setPartitionKey(this.getPartitionKey()); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java similarity index 99% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java index 77a60f70d98f0..8047375213272 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java +++ b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java @@ -56,4 +56,4 @@ protected RequestOptions toRequestOptions() { requestOptions.setOfferThroughput(offerThroughput); return requestOptions; } -} +} \ No newline at end of file diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java similarity index 99% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java index c53a386f7601c..6415bd16753b2 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java +++ b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java @@ -59,4 +59,4 @@ public CosmosDatabaseSettings(String id) { static List getFromV2Results(List results){ return results.stream().map(CosmosDatabaseSettings::new).collect(Collectors.toList()); } -} +} \ No newline at end of file diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java similarity index 100% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java similarity index 99% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java index 62f017ab337dc..bce7b56e5fcff 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java +++ b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java @@ -179,4 +179,4 @@ protected RequestOptions toRequestOptions() { requestOptions.setPartitionKey(partitionKey); return requestOptions; } -} +} \ No newline at end of file diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java similarity index 89% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java index 9000ed4ed3ca0..6bee41456d56e 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java +++ b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java @@ -49,6 +49,17 @@ public CosmosItemSettings(String jsonString) { super(jsonString); } + + /** + * Initialize an CosmosItemSettings object from json string. + * + * @param jsonString the json string that represents the item object. + * @param objectMapper the custom object mapper + */ + public CosmosItemSettings(String jsonString, ObjectMapper objectMapper) { + super(jsonString, objectMapper); + } + /** * fromObject returns Document for compatibility with V2 sdk * diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java similarity index 99% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java index 30a5085021ccd..fb9df401c432f 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java +++ b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java @@ -56,4 +56,4 @@ protected RequestOptions toRequestOptions(){ requestOptions.setAccessCondition(accessCondition); return requestOptions; } -} +} \ No newline at end of file diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java similarity index 100% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java similarity index 84% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java index 4154283e16584..8a74e286daacd 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java +++ b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java @@ -22,12 +22,16 @@ */ package com.microsoft.azure.cosmos; +import com.microsoft.azure.cosmosdb.ClientSideRequestStatistics; import com.microsoft.azure.cosmosdb.Resource; import com.microsoft.azure.cosmosdb.ResourceResponse; import com.microsoft.azure.cosmosdb.StoredProcedureResponse; +import java.time.Duration; import java.util.Map; +import org.apache.commons.lang3.StringUtils; + public class CosmosResponse { private T resourceSettings; protected ResourceResponse resourceResponseWrapper; @@ -134,5 +138,21 @@ public Map getResponseHeaders() { return resourceResponseWrapper.getResponseHeaders(); } - + /** + * Gets the diagnostics information for the current request to Azure Cosmos DB service. + * + * @return diagnostics information for the current request to Azure Cosmos DB service. + */ + public String getRequestDiagnosticsString() { + return resourceResponseWrapper.getRequestDiagnosticsString(); + } + + /** + * Gets the end-to-end request latency for the current request to Azure Cosmos DB service. + * + * @return end-to-end request latency for the current request to Azure Cosmos DB service. + */ + public Duration getRequestLatency() { + return resourceResponseWrapper.getRequestLatency(); + } } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java similarity index 100% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java similarity index 100% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java similarity index 100% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java similarity index 100% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java rename to commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java new file mode 100644 index 0000000000000..cc81ad0d96e6d --- /dev/null +++ b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java @@ -0,0 +1,59 @@ +package com.microsoft.azure.cosmos; + +import java.util.List; +import java.util.stream.Collectors; + +import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.User; +import com.microsoft.azure.cosmosdb.internal.Constants; + +public class CosmosUserSettings extends Resource { + /** + * Initialize a user object. + */ + public CosmosUserSettings() { + super(); + } + + /** + * Initialize a user object from json string. + * + * @param jsonString the json string that represents the database user. + */ + public CosmosUserSettings(String jsonString) { + super(jsonString); + } + + CosmosUserSettings(ResourceResponse response) { + super(response.getResource().toJson()); + } + + // Converting document collection to CosmosContainerSettings + CosmosUserSettings(User user){ + super(user.toJson()); + } + + /** + * Gets the self-link of the permissions associated with the user. + * + * @return the permissions link. + */ + public String getPermissionsLink() { + String selfLink = this.getSelfLink(); + if (selfLink.endsWith("/")) { + return selfLink + super.getString(Constants.Properties.PERMISSIONS_LINK); + } else { + return selfLink + "/" + super.getString(Constants.Properties.PERMISSIONS_LINK); + } + } + + public User getV2User() { + return new User(this.toJson()); + } + + static List getFromV2Results(List results) { + return results.stream().map(CosmosUserSettings::new).collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/BridgeInternal.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/BridgeInternal.java index e0bc791440772..f7c90034da6c1 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/BridgeInternal.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/BridgeInternal.java @@ -27,6 +27,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.microsoft.azure.cosmosdb.internal.HttpConstants; import com.microsoft.azure.cosmosdb.internal.query.metrics.ClientSideMetrics; +import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; import com.microsoft.azure.cosmosdb.rx.internal.Strings; @@ -282,4 +283,12 @@ public static String getInnerErrorMessage(DocumentClientException documentClient } return documentClientException.getInnerErrorMessage(); } + + public static PartitionKeyInternal getNonePartitionKey(PartitionKeyDefinition partitionKeyDefinition) { + return partitionKeyDefinition.getNonePartitionKeyValue(); + } + + public static PartitionKey getPartitionKey(PartitionKeyInternal partitionKeyInternal) { + return new PartitionKey(partitionKeyInternal); + } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKey.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKey.java index 8defae8237b43..2f25785475d25 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKey.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKey.java @@ -58,6 +58,8 @@ public static PartitionKey FromJsonString(String jsonString) { return new PartitionKey(PartitionKeyInternal.fromJsonString(jsonString)); } + public static PartitionKey None = new PartitionKey(PartitionKeyInternal.None); + /** * Serialize the PartitionKey object to a JSON string. * diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java index e9f71e9928b0a..bc6fda9090410 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java @@ -24,6 +24,7 @@ package com.microsoft.azure.cosmosdb; import com.microsoft.azure.cosmosdb.internal.Constants; +import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; import com.microsoft.azure.cosmosdb.rx.internal.Strings; import java.util.ArrayList; @@ -40,6 +41,7 @@ public final class PartitionKeyDefinition extends JsonSerializable { private List paths; private PartitionKind kind; private PartitionKeyDefinitionVersion version; + private Boolean systemKey; /** * Constructor. Creates a new instance of the PartitionKeyDefinition object. @@ -134,6 +136,31 @@ public void setPaths(List paths) { this.paths = paths; } + /** + * Indicates if the partition key is generated by the system. + * + * @return the boolean indicating is it is a system key. + */ + Boolean isSystemKey() { + if (this.systemKey == null) { + if (super.has(Constants.Properties.SYSTEM_KEY)) { + this.systemKey = super.getBoolean(Constants.Properties.SYSTEM_KEY); + } else { + this.systemKey = false; + } + } + + return this.systemKey; + } + + PartitionKeyInternal getNonePartitionKeyValue() { + if (this.getPaths().size() == 0 || this.isSystemKey()) { + return PartitionKeyInternal.Empty; + } else { + return PartitionKeyInternal.UndefinedPartitionKey; + } + } + @Override void populatePropertyBag() { if (this.kind != null) { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Constants.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Constants.java index 6ae4ca51597a2..c3d11aa753d36 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Constants.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Constants.java @@ -157,6 +157,7 @@ public static final class Properties { public static final String PARTITION_KEY_PATHS = "paths"; public static final String PARTITION_KIND = "kind"; public static final String PARTITION_KEY_DEFINITION_VERSION = "version"; + public static final String SYSTEM_KEY = "systemKey"; public static final String RESOURCE_PARTITION_KEY = "resourcePartitionKey"; public static final String PARTITION_KEY_RANGE_ID = "partitionKeyRangeId"; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java index 2a90ef59c029c..78c0bf4e23ffa 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java @@ -265,7 +265,7 @@ public static class A_IMHeaderValues { } public static class Versions { - public static final String CURRENT_VERSION = "2018-09-17"; + public static final String CURRENT_VERSION = "2018-12-31"; // TODO: FIXME we can use maven plugin for generating a version file // @see https://stackoverflow.com/questions/2469922/generate-a-version-java-file-in-maven diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternal.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternal.java index 1051193584ae6..35bcc575ec2bb 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternal.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternal.java @@ -62,6 +62,9 @@ public class PartitionKeyInternal implements Comparable { private static final String MAX_STRING = "MaxString"; private static final String INFINITY = "Infinity"; + public static final PartitionKeyInternal NonePartitionKey = + new PartitionKeyInternal(); + public static final PartitionKeyInternal EmptyPartitionKey = new PartitionKeyInternal(new ArrayList<>()); @@ -71,9 +74,16 @@ public class PartitionKeyInternal implements Comparable { add(new InfinityPartitionKeyComponent()); }}); + @SuppressWarnings("serial") + public static final PartitionKeyInternal UndefinedPartitionKey = + new PartitionKeyInternal(new ArrayList() {{ + add(new UndefinedPartitionKeyComponent()); + }}); + public static final PartitionKeyInternal InclusiveMinimum = PartitionKeyInternal.EmptyPartitionKey; public static final PartitionKeyInternal ExclusiveMaximum = PartitionKeyInternal.InfinityPartitionKey; public static final PartitionKeyInternal Empty = PartitionKeyInternal.EmptyPartitionKey; + public static final PartitionKeyInternal None = PartitionKeyInternal.NonePartitionKey; final List components; @@ -85,6 +95,10 @@ public PartitionKeyInternal(List values) { this.components = values; } + public PartitionKeyInternal() { + this.components = null; + } + public static PartitionKeyInternal fromJsonString(String partitionKey) { if (Strings.isNullOrEmpty(partitionKey)) { throw new IllegalArgumentException(String.format(RMResources.UnableToDeserializePartitionKeyValue, partitionKey)); @@ -178,6 +192,10 @@ public boolean equals(Object obj) { public int compareTo(PartitionKeyInternal other) { if (other == null) { throw new IllegalArgumentException("other"); + } else if (other.components == null || this.components == null) { + int otherComponentsCount = other.components == null ? 0 : other.components.size(); + int thisComponentsCount = this.components == null ? 0 : this.components.size(); + return (int) Math.signum(thisComponentsCount - otherComponentsCount); } for (int i = 0; i < Math.min(this.components.size(), other.components.size()); i++) { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressResolver.java b/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressResolver.java index db65feef97d5d..37527ab7d9ca0 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressResolver.java +++ b/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressResolver.java @@ -655,7 +655,7 @@ private PartitionKeyRange tryResolveServerPartitionByPartitionKey( throw new InternalServerErrorException(String.format("partition key is null '%s'", partitionKeyString)); } - if (partitionKey.getComponents().size() == collection.getPartitionKey().getPaths().size()) { + if (partitionKey.equals(PartitionKeyInternal.Empty) || partitionKey.getComponents().size() == collection.getPartitionKey().getPaths().size()) { // Although we can compute effective partition key here, in general case this Gateway can have outdated // partition key definition cached - like if collection with same name but with Range partitioning is created. // In this case server will not pass x-ms-documentdb-collection-rid check and will return back InvalidPartitionException. diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternalHelper.java b/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternalHelper.java index 316f6e87dc353..d0c81ddf8c194 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternalHelper.java +++ b/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternalHelper.java @@ -140,6 +140,10 @@ public static String getEffectivePartitionKeyString(PartitionKeyInternal partiti } public static String getEffectivePartitionKeyString(PartitionKeyInternal partitionKeyInternal, PartitionKeyDefinition partitionKeyDefinition, boolean strict) { + if (partitionKeyInternal.components == null) { + throw new IllegalArgumentException(RMResources.TooFewPartitionKeyComponents); + } + if (partitionKeyInternal.equals(PartitionKeyInternal.EmptyPartitionKey)) { return MinimumInclusiveEffectivePartitionKey; } diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/CollectionCRUDAsyncAPITest.java b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/CollectionCRUDAsyncAPITest.java index e9d0c4d336042..4ed8e550f35ed 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/CollectionCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/CollectionCRUDAsyncAPITest.java @@ -106,6 +106,11 @@ public void setUp() { public void before() { collectionDefinition = new DocumentCollection(); collectionDefinition.setId(UUID.randomUUID().toString()); + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + collectionDefinition.setPartitionKey(partitionKeyDef); } @AfterClass(groups = "samples", timeOut = TIMEOUT) diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/ConflictAPITest.java b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/ConflictAPITest.java index 8aad1f45b8e93..d82c4aa07b9dd 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/ConflictAPITest.java +++ b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/ConflictAPITest.java @@ -32,6 +32,7 @@ import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; import com.microsoft.azure.cosmosdb.internal.HttpConstants; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import org.testng.annotations.AfterClass; @@ -40,6 +41,7 @@ import rx.Observable; import rx.observable.ListenableFutureObservable; +import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.UUID; @@ -77,6 +79,11 @@ public void setUp() { DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setId(UUID.randomUUID().toString()); + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + collectionDefinition.setPartitionKey(partitionKeyDef); // Create database createdDatabase = Utils.createDatabaseForTest(client); diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentCRUDAsyncAPITest.java b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentCRUDAsyncAPITest.java index a9df3991e84c8..c68157454ca46 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentCRUDAsyncAPITest.java @@ -221,9 +221,11 @@ public void createDocumentWithProgrammableDocumentDefinition() throws Exception .createDocument(getCollectionLink(), documentDefinition, null, false).toBlocking().single() .getResource(); + RequestOptions options = new RequestOptions(); + options.setPartitionKey(PartitionKey.None); // Read the created document Observable> readDocumentObservable = asyncClient - .readDocument(getDocumentLink(createdDocument), null); + .readDocument(getDocumentLink(createdDocument), options); final CountDownLatch completionLatch = new CountDownLatch(1); diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentQueryAsyncAPITest.java b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentQueryAsyncAPITest.java index 35d652c3efdf5..0cb6ec4013996 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentQueryAsyncAPITest.java +++ b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentQueryAsyncAPITest.java @@ -83,7 +83,7 @@ * {@link #transformObservableToGoogleGuavaListenableFuture()} */ public class DocumentQueryAsyncAPITest { - private final static int TIMEOUT = 60000; + private final static int TIMEOUT = 3 * 60000; private AsyncDocumentClient asyncClient; private DocumentCollection createdCollection; private Database createdDatabase; @@ -102,6 +102,11 @@ public void setUp() { DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setId(UUID.randomUUID().toString()); + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + collectionDefinition.setPartitionKey(partitionKeyDef); // Create database @@ -136,6 +141,7 @@ public void queryDocuments_Async() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.setMaxItemCount(requestPageSize); + options.setEnableCrossPartitionQuery(true); Observable> documentQueryObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); @@ -182,6 +188,7 @@ public void queryDocuments_Async_withoutLambda() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.setMaxItemCount(requestPageSize); + options.setEnableCrossPartitionQuery(true); Observable> documentQueryObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); @@ -231,6 +238,7 @@ public void queryDocuments_findTotalRequestCharge() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.setMaxItemCount(requestPageSize); + options.setEnableCrossPartitionQuery(true); Observable totalChargeObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options) @@ -256,6 +264,7 @@ public void queryDocuments_unsubscribeAfterFirstPage() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.setMaxItemCount(requestPageSize); + options.setEnableCrossPartitionQuery(true); Observable> requestChargeObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); @@ -300,6 +309,7 @@ public void queryDocuments_filterFetchedResults() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.setMaxItemCount(requestPageSize); + options.setEnableCrossPartitionQuery(true); Func1 isPrimeNumber = new Func1() { @@ -359,6 +369,7 @@ public void queryDocuments_toBlocking_toIterator() { int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.setMaxItemCount(requestPageSize); + options.setEnableCrossPartitionQuery(true); Observable> documentQueryObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); @@ -448,6 +459,7 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.setMaxItemCount(requestPageSize); + options.setEnableCrossPartitionQuery(true); Observable> documentQueryObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/InMemoryGroupbyTest.java b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/InMemoryGroupbyTest.java index baeac40b2a029..23c97a7dadba0 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/InMemoryGroupbyTest.java +++ b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/InMemoryGroupbyTest.java @@ -29,6 +29,7 @@ import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; import com.microsoft.azure.cosmosdb.SqlParameter; import com.microsoft.azure.cosmosdb.SqlParameterCollection; import com.microsoft.azure.cosmosdb.SqlQuerySpec; @@ -40,6 +41,7 @@ import rx.observables.GroupedObservable; import java.time.LocalDateTime; +import java.util.ArrayList; import java.util.List; import java.util.UUID; @@ -66,6 +68,11 @@ public static void setUp() throws Exception { DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setId(UUID.randomUUID().toString()); + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + collectionDefinition.setPartitionKey(partitionKeyDef); // Create collection createdCollection = asyncClient @@ -112,6 +119,7 @@ public void groupByInMemory() { int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.setMaxItemCount(requestPageSize); + options.setEnableCrossPartitionQuery(true); Observable documentsObservable = asyncClient .queryDocuments(getCollectionLink(), @@ -144,7 +152,7 @@ public void groupByInMemory_MoreDetail() { int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.setMaxItemCount(requestPageSize); - + options.setEnableCrossPartitionQuery(true); Observable documentsObservable = asyncClient .queryDocuments(getCollectionLink(), diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TokenResolverTest.java b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TokenResolverTest.java index c33f14fdc2b38..4c56170eb4972 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TokenResolverTest.java +++ b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TokenResolverTest.java @@ -31,6 +31,8 @@ import com.microsoft.azure.cosmosdb.Database; import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; import com.microsoft.azure.cosmosdb.Permission; import com.microsoft.azure.cosmosdb.PermissionMode; import com.microsoft.azure.cosmosdb.RequestOptions; @@ -86,6 +88,11 @@ public void setUp() { DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setId(UUID.randomUUID().toString()); + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + collectionDefinition.setPartitionKey(partitionKeyDef); // Create database createdDatabase = Utils.createDatabaseForTest(asyncClient); @@ -163,6 +170,7 @@ public void readDocumentThroughTokenResolver() throws Exception { .build(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setProperties(properties); + requestOptions.setPartitionKey(PartitionKey.None); Observable> readDocumentObservable = asyncClientWithTokenResolver .readDocument(documentLink, requestOptions); readDocumentObservable.subscribe(resourceResponse -> { @@ -204,6 +212,7 @@ public void deleteDocumentThroughTokenResolver() throws Exception { RequestOptions requestOptions = new RequestOptions(); requestOptions.setProperties(properties); + requestOptions.setPartitionKey(PartitionKey.None); Observable> readDocumentObservable = asyncClientWithTokenResolver .deleteDocument(documentLink, requestOptions); readDocumentObservable.subscribe(resourceResponse -> { diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/UniqueIndexAsyncAPITest.java b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/UniqueIndexAsyncAPITest.java index e253729f1ee4b..a1e8e3cdf4972 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/UniqueIndexAsyncAPITest.java +++ b/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/UniqueIndexAsyncAPITest.java @@ -30,6 +30,7 @@ import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; import com.microsoft.azure.cosmosdb.ResourceResponse; import com.microsoft.azure.cosmosdb.UniqueKey; import com.microsoft.azure.cosmosdb.UniqueKeyPolicy; @@ -40,6 +41,7 @@ import rx.Observable; import rx.observers.TestSubscriber; +import java.util.ArrayList; import java.util.Collections; import java.util.UUID; @@ -62,6 +64,11 @@ public void uniqueIndex() { uniqueKey.setPaths(ImmutableList.of("/name", "/field")); uniqueKeyPolicy.setUniqueKeys(Collections.singleton(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + collectionDefinition.setPartitionKey(partitionKeyDef); DocumentCollection collection = client.createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single().getResource(); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentQueryExecutionContextFactory.java b/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentQueryExecutionContextFactory.java index 4b4b2891dfe58..32a99af6e715a 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentQueryExecutionContextFactory.java +++ b/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentQueryExecutionContextFactory.java @@ -25,8 +25,10 @@ import java.util.List; import java.util.UUID; +import com.microsoft.azure.cosmosdb.BridgeInternal; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.PartitionKey; import com.microsoft.azure.cosmosdb.PartitionKeyRange; import com.microsoft.azure.cosmosdb.Resource; import com.microsoft.azure.cosmosdb.SqlQuerySpec; @@ -86,17 +88,21 @@ public static Observable> proxyQueryExecutionContext = - collectionObs.flatMap(collection -> - ProxyDocumentQueryExecutionContext.createAsync( - client, - resourceTypeEnum, - resourceType, - query, - feedOptions, - resourceLink, - collection, - isContinuationExpected, - correlatedActivityId)); + collectionObs.flatMap(collection -> { + if (feedOptions != null && feedOptions.getPartitionKey() != null && feedOptions.getPartitionKey().equals(PartitionKey.None)) { + feedOptions.setPartitionKey(BridgeInternal.getPartitionKey(BridgeInternal.getNonePartitionKey(collection.getPartitionKey()))); + } + return ProxyDocumentQueryExecutionContext.createAsync( + client, + resourceTypeEnum, + resourceType, + query, + feedOptions, + resourceLink, + collection, + isContinuationExpected, + correlatedActivityId); + }); return proxyQueryExecutionContext; } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java index 920df75cb493c..5ce31ded234ba 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java @@ -26,13 +26,17 @@ import com.microsoft.azure.cosmosdb.ConnectionPolicy; import com.microsoft.azure.cosmosdb.ConsistencyLevel; import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.DatabaseAccount; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.Permission; import com.microsoft.azure.cosmosdb.SqlQuerySpec; +import com.microsoft.azure.cosmosdb.TokenResolver; import com.microsoft.azure.cosmosdb.internal.HttpConstants; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.microsoft.azure.cosmosdb.rx.internal.Configs; + import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; @@ -48,25 +52,31 @@ public class CosmosClient { //Document client wrapper + private final Configs configs; private final AsyncDocumentClient asyncDocumentClient; private final String serviceEndpoint; private final String keyOrResourceToken; private final ConnectionPolicy connectionPolicy; private final ConsistencyLevel desiredConsistencyLevel; private final List permissions; + private final TokenResolver tokenResolver; CosmosClient(CosmosClientBuilder builder) { - this.serviceEndpoint = builder.getServiceEndpoint(); + this.configs = builder.getConfigs(); + this.serviceEndpoint = builder.getServiceEndpoint(); this.keyOrResourceToken = builder.getKeyOrResourceToken(); this.connectionPolicy = builder.getConnectionPolicy(); this.desiredConsistencyLevel = builder.getDesiredConsistencyLevel(); this.permissions = builder.getPermissions(); + this.tokenResolver = builder.getTokenResolver(); this.asyncDocumentClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(this.serviceEndpoint) .withMasterKeyOrResourceToken(this.keyOrResourceToken) .withConnectionPolicy(this.connectionPolicy) .withConsistencyLevel(this.desiredConsistencyLevel) + .withConfigs(this.configs) + .withTokenResolver(this.tokenResolver) .build(); } @@ -130,6 +140,22 @@ AsyncDocumentClient getDocClientWrapper(){ return asyncDocumentClient; } + /** + * Gets the configs + * @return the configs + */ + public Configs getConfigs() { + return configs; + } + + /** + * Gets the token resolver + * @return the token resolver + */ + public TokenResolver getTokenResolver() { + return tokenResolver; + } + /** * Create a Database if it does not already exist on the service * @@ -283,6 +309,10 @@ public Flux> queryDatabases(SqlQuerySpec qu response.getResponseHeaders())))); } + Mono getDatabaseAccount() { + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(asyncDocumentClient.getDatabaseAccount().toSingle())); + } + /** * Gets a database object without making a service call. * diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java index eb0266bc6ecf8..34143019f2f3d 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java @@ -25,6 +25,8 @@ import com.microsoft.azure.cosmosdb.ConnectionPolicy; import com.microsoft.azure.cosmosdb.ConsistencyLevel; import com.microsoft.azure.cosmosdb.Permission; +import com.microsoft.azure.cosmosdb.TokenResolver; +import com.microsoft.azure.cosmosdb.rx.internal.Configs; import java.util.List; @@ -47,15 +49,37 @@ */ public class CosmosClientBuilder { + private Configs configs = new Configs(); private String serviceEndpoint; private String keyOrResourceToken; private ConnectionPolicy connectionPolicy; private ConsistencyLevel desiredConsistencyLevel; private List permissions; + private TokenResolver tokenResolver; CosmosClientBuilder() { } + /** + * Configs + * @param configs + * @return current builder + */ + public CosmosClientBuilder configs(Configs configs) { + this.configs = configs; + return this; + } + + /** + * Token Resolver + * @param tokenResolver + * @return current builder + */ + public CosmosClientBuilder tokenResolver(TokenResolver tokenResolver) { + this.tokenResolver = tokenResolver; + return this; + } + /** * The service endpoint url * @param serviceEndpoint the service endpoint @@ -138,15 +162,23 @@ String getKeyOrResourceToken() { return keyOrResourceToken; } - ConnectionPolicy getConnectionPolicy() { + public ConnectionPolicy getConnectionPolicy() { return connectionPolicy; } - ConsistencyLevel getDesiredConsistencyLevel() { + public ConsistencyLevel getDesiredConsistencyLevel() { return desiredConsistencyLevel; } List getPermissions() { return permissions; } + + public Configs getConfigs() { + return configs; + } + + public TokenResolver getTokenResolver() { + return tokenResolver; + } } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java index e7d31c656818d..9f168dbd83d34 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java @@ -31,8 +31,11 @@ import com.microsoft.azure.cosmosdb.StoredProcedure; import com.microsoft.azure.cosmosdb.Trigger; import com.microsoft.azure.cosmosdb.UserDefinedFunction; +import com.microsoft.azure.cosmosdb.internal.Constants; import com.microsoft.azure.cosmosdb.internal.Paths; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; + import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; @@ -87,11 +90,11 @@ public static String getSelfLink(CosmosContainer cosmosContainer) { * Reads the document container * * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cossmos container response with the read + * The {@link Mono} upon successful completion will contain a single cosmos container response with the read * container. * In case of failure the {@link Mono} will error. * - * @return an {@link Mono} containing the single cossmos container response with the read container or an error. + * @return an {@link Mono} containing the single cosmos container response with the read container or an error. */ public Mono read() { return read(new CosmosContainerRequestOptions()); @@ -101,10 +104,11 @@ public Mono read() { * Reads the document container by the container link. * * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cossmos container response with the read container. + * The {@link Mono} upon successful completion will contain a single cosmos container response with the read container. * In case of failure the {@link Mono} will error. - * @param options the cosmos container request options - * @return an {@link Mono} containing the single cossmos container response with the read container or an error. + * + * @param options The cosmos container request options. + * @return an {@link Mono} containing the single cosmos container response with the read container or an error. */ public Mono read(CosmosContainerRequestOptions options) { if (options == null) { @@ -119,11 +123,11 @@ public Mono read(CosmosContainerRequestOptions options) * Deletes the item container * * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cossmos container response for the deleted database. + * The {@link Mono} upon successful completion will contain a single cosmos container response for the deleted database. * In case of failure the {@link Mono} will error. * * @param options the request options. - * @return an {@link Mono} containing the single cossmos container response for the deleted database or an error. + * @return an {@link Mono} containing the single cosmos container response for the deleted database or an error. */ public Mono delete(CosmosContainerRequestOptions options) { if (options == null) { @@ -143,7 +147,7 @@ public Mono delete(CosmosContainerRequestOptions option * The {@link Mono} upon successful completion will contain a single cosmos container response for the deleted container. * In case of failure the {@link Mono} will error. * - * @return an {@link Mono} containing the single cossmos container response for the deleted container or an error. + * @return an {@link Mono} containing the single cosmos container response for the deleted container or an error. */ public Mono delete() { return delete(new CosmosContainerRequestOptions()); @@ -153,12 +157,12 @@ public Mono delete() { * Replaces a document container. * * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cossmos container response with the replaced document container. + * The {@link Mono} upon successful completion will contain a single cosmos container response with the replaced document container. * In case of failure the {@link Mono} will error. * * @param containerSettings the item container settings * @param options the cosmos container request options. - * @return an {@link Mono} containing the single cossmos container response with the replaced document container or an error. + * @return an {@link Mono} containing the single cosmos container response with the replaced document container or an error. */ public Mono replace(CosmosContainerSettings containerSettings, CosmosContainerRequestOptions options) { @@ -186,7 +190,7 @@ public Mono replace(CosmosContainerSettings containerSe * @return an {@link Mono} containing the single resource response with the created cosmos item or an error. */ public Mono createItem(Object item){ - return createItem(item, null); + return createItem(item, new CosmosItemRequestOptions()); } /** @@ -232,6 +236,35 @@ public Mono createItem(Object item, CosmosItemRequestOptions .toSingle())); } + /** + * Upserts an item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the upserted item. + * In case of failure the {@link Mono} will error. + * + * @param item the item represented as a POJO or Item object to upsert. + * @return an {@link Mono} containing the single resource response with the upserted document or an error. + */ + public Mono upsertItem(Object item) { + return upsertItem(item, new CosmosItemRequestOptions()); + } + + /** + * Upserts an item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the upserted item. + * In case of failure the {@link Mono} will error. + * + * @param item the item represented as a POJO or Item object to upsert. + * @param partitionKey the partitionKey to be used. + * @return an {@link Mono} containing the single resource response with the upserted document or an error. + */ + public Mono upsertItem(Object item, Object partitionKey) { + return upsertItem(item, new CosmosItemRequestOptions(partitionKey)); + } + /** * Upserts a cosmos item. * @@ -362,6 +395,21 @@ public CosmosItem getItem(String id, Object partitionKey){ /* CosmosStoredProcedure operations */ + /** + * Creates a cosmos stored procedure. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos stored procedure response with the + * created cosmos stored procedure. + * In case of failure the {@link Mono} will error. + * + * @param settings the cosmos stored procedure settings. + * @return an {@link Mono} containing the single cosmos stored procedure resource response or an error. + */ + public Mono createStoredProcedure(CosmosStoredProcedureSettings settings){ + return this.createStoredProcedure(settings, new CosmosStoredProcedureRequestOptions()); + } + /** * Creates a cosmos stored procedure. * diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java index e8306ff8bc7f0..75fb16970a13e 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java @@ -282,15 +282,19 @@ public Flux> queryContainers(SqlQuerySpec public CosmosContainer getContainer(String id) { return new CosmosContainer(id, this); } - + /** User operations **/ + public Mono createUser(CosmosUserSettings settings) { + return this.createUser(settings, null); + } + /** * Creates a user * After subscription the operation will be performed. * The {@link Mono} upon successful completion will contain a single resource response with the created user. * In case of failure the {@link Mono} will error. - * + * * @param settings the cosmos user settings * @param options the request options * @return an {@link Mono} containing the single resource response with the created cosmos user or an error. @@ -298,7 +302,11 @@ public CosmosContainer getContainer(String id) { public Mono createUser(CosmosUserSettings settings, RequestOptions options){ return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(getDocClientWrapper().createUser(this.getLink(), settings.getV2User(), options).map(response -> - new CosmosUserResponse(response, this)).toSingle())); + new CosmosUserResponse(response, this)).toSingle())); + } + + public Mono upsertUser(CosmosUserSettings settings) { + return this.upsertUser(settings, null); } /** @@ -306,7 +314,7 @@ public Mono createUser(CosmosUserSettings settings, RequestO * After subscription the operation will be performed. * The {@link Mono} upon successful completion will contain a single resource response with the created user. * In case of failure the {@link Mono} will error. - * + * * @param settings the cosmos user settings * @param options the request options * @return an {@link Mono} containing the single resource response with the upserted user or an error. @@ -317,6 +325,10 @@ public Mono upsertUser(CosmosUserSettings settings, RequestO new CosmosUserResponse(response, this)).toSingle())); } + public Flux> listUsers() { + return listUsers(new FeedOptions()); + } + /** * Reads all cosmos users in a database. * @@ -335,10 +347,14 @@ public Flux> listUsers(FeedOptions options){ response.getResponseHeaders())))); } + public Flux> queryUsers(String query, FeedOptions options){ + return queryUsers(new SqlQuerySpec(query), options); + } + /** * Query for cosmos users in a database. * - * After subscription the operation will be performed. + * After subscription the operation will be performed. * The {@link Flux} will contain one or several feed response of the obtained users. * In case of failure the {@link Flux} will error. * @@ -355,6 +371,10 @@ public Flux> queryUsers(SqlQuerySpec querySpec, response.getResponseHeaders(), response.getQueryMetrics())))); } + public CosmosUser getUser(String id) { + return new CosmosUser(id, this); + } + CosmosClient getClient() { return client; } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java index fca34f5d8480c..883abecd108f8 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItem.java @@ -1,163 +1,162 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.internal.Paths; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; -import reactor.core.publisher.Mono; - -public class CosmosItem extends CosmosResource{ - private Object partitionKey; - private CosmosContainer container; - - CosmosItem(String id, Object partitionKey, CosmosContainer container) { - super(id); - this.partitionKey = partitionKey; - this.container = container; - } - - /** - * Reads an item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos item response with the read item - * In case of failure the {@link Mono} will error. - * - * @return an {@link Mono} containing the cosmos item response with the read item or an error - */ - public Mono read() { - return read(new CosmosItemRequestOptions(partitionKey)); - } - - /** - * Reads an item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos item response with the read item - * In case of failure the {@link Mono} will error. - * - * @param options the request comosItemRequestOptions - * @return an {@link Mono} containing the cosmos item response with the read item or an error - */ - public Mono read(CosmosItemRequestOptions options) { - if (options == null) { - options = new CosmosItemRequestOptions(); - } - RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase().getDocClientWrapper() - .readDocument(getLink(), requestOptions) - .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) - .toSingle())); - } - - /** - * Replaces an item with the passed in item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. - * In case of failure the {@link Mono} will error. - * - * @param item the item to replace (containing the document id). - * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. - */ - public Mono replace(Object item){ - return replace(item, new CosmosItemRequestOptions(partitionKey)); - } - - /** - * Replaces an item with the passed in item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. - * In case of failure the {@link Mono} will error. - * - * @param item the item to replace (containing the document id). - * @param options the request comosItemRequestOptions - * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. - */ - public Mono replace(Object item, CosmosItemRequestOptions options){ - Document doc = CosmosItemSettings.fromObject(item); - if (options == null) { - options = new CosmosItemRequestOptions(); - } - RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase() - .getDocClientWrapper() - .replaceDocument(getLink(), doc, requestOptions) - .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) - .toSingle())); - } - - /** - * Deletes the item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. - * In case of failure the {@link Mono} will error. - * @return an {@link Mono} containing the cosmos item resource response. - */ - public Mono delete() { - return delete(new CosmosItemRequestOptions(partitionKey)); - } - - /** - * Deletes the item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. - * In case of failure the {@link Mono} will error. - * - * @param options the request options - * @return an {@link Mono} containing the cosmos item resource response. - */ - public Mono delete(CosmosItemRequestOptions options){ - if (options == null) { - options = new CosmosItemRequestOptions(); - } - RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(container.getDatabase() - .getDocClientWrapper() - .deleteDocument(getLink(), requestOptions) - .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) - .toSingle())); - } - - void setContainer(CosmosContainer container) { - this.container = container; - } - - @Override - protected String getURIPathSegment() { - return Paths.DOCUMENTS_PATH_SEGMENT; - } - - @Override - protected String getParentLink() { - return this.container.getLink(); - } - -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.internal.Paths; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Mono; + +public class CosmosItem extends CosmosResource{ + private Object partitionKey; + private CosmosContainer container; + + CosmosItem(String id, Object partitionKey, CosmosContainer container) { + super(id); + this.partitionKey = partitionKey; + this.container = container; + } + + /** + * Reads an item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos item response with the read item + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the cosmos item response with the read item or an error + */ + public Mono read() { + return read(new CosmosItemRequestOptions(partitionKey)); + } + + /** + * Reads an item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos item response with the read item + * In case of failure the {@link Mono} will error. + * + * @param options the request comosItemRequestOptions + * @return an {@link Mono} containing the cosmos item response with the read item or an error + */ + public Mono read(CosmosItemRequestOptions options) { + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase().getDocClientWrapper() + .readDocument(getLink(), requestOptions) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) + .toSingle())); + } + + /** + * Replaces an item with the passed in item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * + * @param item the item to replace (containing the document id). + * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. + */ + public Mono replace(Object item){ + return replace(item, new CosmosItemRequestOptions(partitionKey)); + } + + /** + * Replaces an item with the passed in item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * + * @param item the item to replace (containing the document id). + * @param options the request comosItemRequestOptions + * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. + */ + public Mono replace(Object item, CosmosItemRequestOptions options){ + Document doc = CosmosItemSettings.fromObject(item); + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .replaceDocument(getLink(), doc, requestOptions) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) + .toSingle())); + } + + /** + * Deletes the item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * @return an {@link Mono} containing the cosmos item resource response. + */ + public Mono delete() { + return delete(new CosmosItemRequestOptions(partitionKey)); + } + + /** + * Deletes the item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * + * @param options the request options + * @return an {@link Mono} containing the cosmos item resource response. + */ + public Mono delete(CosmosItemRequestOptions options){ + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .deleteDocument(getLink(), requestOptions) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) + .toSingle())); + } + + void setContainer(CosmosContainer container) { + this.container = container; + } + + @Override + protected String getURIPathSegment() { + return Paths.DOCUMENTS_PATH_SEGMENT; + } + + @Override + protected String getParentLink() { + return this.container.getLink(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java index f150206113cf8..5d4024d6bc004 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java @@ -1,57 +1,65 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.ResourceResponse; - -public class CosmosItemResponse extends CosmosResponse{ - private CosmosItem itemClient; - - CosmosItemResponse(ResourceResponse response, PartitionKey partitionKey, CosmosContainer container) { - super(response); - if(response.getResource() == null){ - super.setResourceSettings(null); - }else{ - super.setResourceSettings(new CosmosItemSettings(response.getResource().toJson())); - itemClient = new CosmosItem(response.getResource().getId(),partitionKey, container); - } - } - - /** - * Gets the itemSettings - * @return the itemSettings - */ - public CosmosItemSettings getCosmosItemSettings() { - return getResourceSettings(); - } - - /** - * Gets the CosmosItem - * @return the cosmos item - */ - public CosmosItem getItem() { - return itemClient; - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.ResourceResponse; + +public class CosmosItemResponse extends CosmosResponse{ + private CosmosItem itemClient; + + CosmosItemResponse(ResourceResponse response, PartitionKey partitionKey, CosmosContainer container) { + super(response); + if(response.getResource() == null){ + super.setResourceSettings(null); + }else{ + super.setResourceSettings(new CosmosItemSettings(response.getResource().toJson())); + itemClient = new CosmosItem(response.getResource().getId(),partitionKey, container); + } + } + + /** + * Gets the itemSettings + * @return the itemSettings + */ + public CosmosItemSettings getCosmosItemSettings() { + return getResourceSettings(); + } + + /** + * Gets the CosmosItem + * @return the cosmos item + */ + public CosmosItem getItem() { + return itemClient; + } + + /** + * Gets the CosmosItem + * @return the cosmos item + */ + public CosmosItem getCosmosItem() { + return itemClient; + } +} \ No newline at end of file diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java index 6dd0b4593f36c..cbdaa7130016b 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerResponse.java @@ -33,6 +33,7 @@ public class CosmosTriggerResponse extends CosmosResponse CosmosTriggerResponse(ResourceResponse response, CosmosContainer container) { super(response); if(response.getResource() != null) { + super.setResourceSettings(new CosmosTriggerSettings(response)); cosmosTriggerSettings = new CosmosTriggerSettings(response); cosmosTrigger = new CosmosTrigger(cosmosTriggerSettings.getId(), container); } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java index 511f1654e5626..fc8b3cc7f8f1a 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java @@ -15,7 +15,14 @@ public CosmosUser(String id, CosmosDatabase database) { /** * Reads a cosmos user - * + * @return an {@link Mono} containing the single cosmos user response with the read user or an error. + */ + public Mono read() { + return this.read(null); + } + + /** + * Reads a cosmos user * @param options the request options * @return a {@link Mono} containing the single resource response with the read user or an error. */ @@ -59,4 +66,4 @@ protected String getURIPathSegment() { protected String getParentLink() { return database.getLink() ; } -} +} \ No newline at end of file diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java index 2b4f301b9a45d..59251a9f93c12 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java @@ -1,56 +1,57 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; - -public class CosmosUserDefinedFunctionResponse extends CosmosResponse { - - private CosmosUserDefinedFunctionSettings cosmosUserDefinedFunctionSettings; - private CosmosUserDefinedFunction cosmosUserDefinedFunction; - - CosmosUserDefinedFunctionResponse(ResourceResponse response, CosmosContainer container) { - super(response); - if(response.getResource() != null) { - cosmosUserDefinedFunctionSettings = new CosmosUserDefinedFunctionSettings(response); - cosmosUserDefinedFunction = new CosmosUserDefinedFunction(cosmosUserDefinedFunctionSettings.getId(), container); - } - } - - /** - * Gets the cosmos user defined function settings - * @return the cosmos user defined function settings - */ - public CosmosUserDefinedFunctionSettings getCosmosUserDefinedFunctionSettings() { - return cosmosUserDefinedFunctionSettings; - } - - /** - * Gets the cosmos user defined function object - * @return the cosmos user defined function object - */ - public CosmosUserDefinedFunction getCosmosUserDefinedFunction() { - return cosmosUserDefinedFunction; - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.UserDefinedFunction; + +public class CosmosUserDefinedFunctionResponse extends CosmosResponse { + + private CosmosUserDefinedFunctionSettings cosmosUserDefinedFunctionSettings; + private CosmosUserDefinedFunction cosmosUserDefinedFunction; + + CosmosUserDefinedFunctionResponse(ResourceResponse response, CosmosContainer container) { + super(response); + if(response.getResource() != null) { + super.setResourceSettings(new CosmosUserDefinedFunctionSettings(response)); + cosmosUserDefinedFunctionSettings = new CosmosUserDefinedFunctionSettings(response); + cosmosUserDefinedFunction = new CosmosUserDefinedFunction(cosmosUserDefinedFunctionSettings.getId(), container); + } + } + + /** + * Gets the cosmos user defined function settings + * @return the cosmos user defined function settings + */ + public CosmosUserDefinedFunctionSettings getCosmosUserDefinedFunctionSettings() { + return cosmosUserDefinedFunctionSettings; + } + + /** + * Gets the cosmos user defined function object + * @return the cosmos user defined function object + */ + public CosmosUserDefinedFunction getCosmosUserDefinedFunction() { + return cosmosUserDefinedFunction; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java index a4b170353c182..6b9f8b9a36ef8 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java @@ -34,5 +34,5 @@ public CosmosUserSettings getCosmosUserSettings(){ return getResourceSettings(); } - + } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientImpl.java b/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientImpl.java index 40c9ba72a7fe5..e79e27b859c4a 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientImpl.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientImpl.java @@ -909,10 +909,6 @@ private Map getRequestHeaders(RequestOptions options) { headers.put(HttpConstants.HttpHeaders.OFFER_TYPE, options.getOfferType()); } - if (options.getPartitionKey() != null) { - headers.put(HttpConstants.HttpHeaders.PARTITION_KEY, options.getPartitionKey().toString()); - } - if (options.isPopulateQuotaInfo()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, String.valueOf(true)); } @@ -972,7 +968,9 @@ private void addPartitionKeyInformation(RxDocumentServiceRequest request, Docume PartitionKeyDefinition partitionKeyDefinition = collection.getPartitionKey(); PartitionKeyInternal partitionKeyInternal = null; - if (options != null && options.getPartitionKey() != null) { + if (options != null && options.getPartitionKey() != null && options.getPartitionKey().equals(PartitionKey.None)){ + partitionKeyInternal = BridgeInternal.getNonePartitionKey(partitionKeyDefinition); + } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = options.getPartitionKey().getInternalPartitionKey(); } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { // For backward compatibility, if collection doesn't have partition key defined, we assume all documents @@ -1009,10 +1007,14 @@ private static PartitionKeyInternal extractPartitionKeyValueFromDocument( if (parts.size() >= 1) { Object value = document.getObjectByPath(parts); if (value == null || value.getClass() == ObjectNode.class) { - value = Undefined.Value(); + value = BridgeInternal.getNonePartitionKey(partitionKeyDefinition); } - return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); + if (value instanceof PartitionKeyInternal) { + return (PartitionKeyInternal) value; + } else { + return PartitionKeyInternal.fromObjectArray(Collections.singletonList(value), false); + } } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ClientUnderTestBuilder.java b/sdk/src/test/java/com/microsoft/azure/cosmos/ClientUnderTestBuilder.java similarity index 50% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ClientUnderTestBuilder.java rename to sdk/src/test/java/com/microsoft/azure/cosmos/ClientUnderTestBuilder.java index 914014c2bb2c7..d7fcc8954e705 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ClientUnderTestBuilder.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/ClientUnderTestBuilder.java @@ -20,28 +20,39 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.microsoft.azure.cosmos; + +import java.net.URI; +import java.net.URISyntaxException; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientUnderTest; +import com.microsoft.azure.cosmosdb.rx.internal.directconnectivity.ReflectionUtils; -public class ClientUnderTestBuilder extends Builder { +public class ClientUnderTestBuilder extends CosmosClientBuilder { - public ClientUnderTestBuilder(Builder builder) { - this.configs = builder.configs; - this.connectionPolicy = builder.connectionPolicy; - this.desiredConsistencyLevel = builder.desiredConsistencyLevel; - this.masterKeyOrResourceToken = builder.masterKeyOrResourceToken; - this.serviceEndpoint = builder.serviceEndpoint; + public ClientUnderTestBuilder(CosmosClientBuilder builder) { + this.configs(builder.getConfigs()); + this.connectionPolicy(builder.getConnectionPolicy()); + this.consistencyLevel(builder.getDesiredConsistencyLevel()); + this.key(builder.getKeyOrResourceToken()); + this.endpoint(builder.getServiceEndpoint()); } @Override - public RxDocumentClientUnderTest build() { - return new RxDocumentClientUnderTest( - this.serviceEndpoint, - this.masterKeyOrResourceToken, - this.connectionPolicy, - this.desiredConsistencyLevel, - this.configs); + public CosmosClient build() { + RxDocumentClientUnderTest rxClient; + try { + rxClient = new RxDocumentClientUnderTest( + new URI(this.getServiceEndpoint()), + this.getKeyOrResourceToken(), + this.getConnectionPolicy(), + this.getDesiredConsistencyLevel(), + this.getConfigs()); + } catch (URISyntaxException e) { + throw new IllegalArgumentException(e.getMessage()); + } + CosmosClient cosmosClient = super.build(); + ReflectionUtils.setAsyncDocumentClient(cosmosClient, rxClient); + return cosmosClient; } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosBridgeInternal.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosBridgeInternal.java new file mode 100644 index 0000000000000..9e12488d5a0c6 --- /dev/null +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosBridgeInternal.java @@ -0,0 +1,34 @@ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.DatabaseAccount; +import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; + +import reactor.core.publisher.Mono; + +public class CosmosBridgeInternal { + + public static String getLink(CosmosResource resource) { + return resource.getLink(); + } + + public static DocumentCollection toDocumentCollection(CosmosContainerSettings cosmosContainerSettings) { + return new DocumentCollection(cosmosContainerSettings.toJson()); + } + + public static AsyncDocumentClient getAsyncDocumentClient(CosmosClient client) { + return client.getDocClientWrapper(); + } + + public static CosmosDatabase getCosmosDatabaseWithNewClient(CosmosDatabase cosmosDatabase, CosmosClient client) { + return new CosmosDatabase(cosmosDatabase.getId(), client); + } + + public static CosmosContainer getCosmosContainerWithNewClient(CosmosContainer cosmosContainer, CosmosDatabase cosmosDatabase, CosmosClient client) { + return new CosmosContainer(cosmosContainer.getId(), CosmosBridgeInternal.getCosmosDatabaseWithNewClient(cosmosDatabase, client)); + } + + public static Mono getDatabaseAccount(CosmosClient client) { + return client.getDatabaseAccount(); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseForTest.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseForTest.java new file mode 100644 index 0000000000000..925f1836878f3 --- /dev/null +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseForTest.java @@ -0,0 +1,137 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.microsoft.azure.cosmos; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.microsoft.azure.cosmos.CosmosDatabaseSettings; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.SqlParameter; +import com.microsoft.azure.cosmosdb.SqlParameterCollection; +import com.microsoft.azure.cosmosdb.SqlQuerySpec; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CosmosDatabaseForTest { + private static Logger logger = LoggerFactory.getLogger(CosmosDatabaseForTest.class); + public static final String SHARED_DB_ID_PREFIX = "RxJava.SDKTest.SharedDatabase"; + private static final Duration CLEANUP_THRESHOLD_DURATION = Duration.ofHours(2); + private static final String DELIMITER = "_"; + private static DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss"); + + public LocalDateTime createdTime; + public CosmosDatabase createdDatabase; + + private CosmosDatabaseForTest(CosmosDatabase db, LocalDateTime createdTime) { + this.createdDatabase = db; + this.createdTime = createdTime; + } + + private boolean isStale() { + return isOlderThan(CLEANUP_THRESHOLD_DURATION); + } + + private boolean isOlderThan(Duration dur) { + return createdTime.isBefore(LocalDateTime.now().minus(dur)); + } + + public static String generateId() { + return SHARED_DB_ID_PREFIX + DELIMITER + TIME_FORMATTER.format(LocalDateTime.now()) + DELIMITER + RandomStringUtils.randomAlphabetic(3); + } + + private static CosmosDatabaseForTest from(CosmosDatabase db) { + if (db == null || db.getId() == null || db.getLink() == null) { + return null; + } + + String id = db.getId(); + if (id == null) { + return null; + } + + String[] parts = StringUtils.split(id, DELIMITER); + if (parts.length != 3) { + return null; + } + if (!StringUtils.equals(parts[0], SHARED_DB_ID_PREFIX)) { + return null; + } + + try { + LocalDateTime parsedTime = LocalDateTime.parse(parts[1], TIME_FORMATTER); + return new CosmosDatabaseForTest(db, parsedTime); + } catch (Exception e) { + return null; + } + } + + public static CosmosDatabaseForTest create(DatabaseManager client) { + CosmosDatabaseSettings dbDef = new CosmosDatabaseSettings(generateId()); + + CosmosDatabase db = client.createDatabase(dbDef).block().getDatabase(); + CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.from(db); + assertThat(dbForTest).isNotNull(); + return dbForTest; + } + + public static void cleanupStaleTestDatabases(DatabaseManager client) { + logger.info("Cleaning stale test databases ..."); + List dbs = client.queryDatabases( + new SqlQuerySpec("SELECT * FROM c WHERE STARTSWITH(c.id, @PREFIX)", + new SqlParameterCollection(new SqlParameter("@PREFIX", CosmosDatabaseForTest.SHARED_DB_ID_PREFIX)))) + .flatMap(page -> Flux.fromIterable(page.getResults())).collectList().block(); + + for (CosmosDatabaseSettings db : dbs) { + assertThat(db.getId()).startsWith(CosmosDatabaseForTest.SHARED_DB_ID_PREFIX); + + CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.from(client.getDatabase(db.getId())); + + if (db != null && dbForTest.isStale()) { + logger.info("Deleting database {}", db.getId()); + dbForTest.deleteDatabase(db.getId()); + } + } + } + + private void deleteDatabase(String id) { + this.createdDatabase.delete().block(); + } + + public interface DatabaseManager { + Flux> queryDatabases(SqlQuerySpec query); + Mono createDatabase(CosmosDatabaseSettings databaseDefinition); + CosmosDatabase getDatabase(String id); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosPartitionKeyTests.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosPartitionKeyTests.java new file mode 100644 index 0000000000000..eff5aa465293d --- /dev/null +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosPartitionKeyTests.java @@ -0,0 +1,331 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +import com.microsoft.azure.cosmosdb.ConnectionPolicy; +import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.internal.BaseAuthorizationTokenProvider; +import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.microsoft.azure.cosmosdb.internal.OperationType; +import com.microsoft.azure.cosmosdb.internal.Paths; +import com.microsoft.azure.cosmosdb.internal.ResourceType; +import com.microsoft.azure.cosmosdb.internal.Utils; +import com.microsoft.azure.cosmosdb.rx.FeedResponseListValidator; +import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; +import com.microsoft.azure.cosmosdb.rx.internal.Configs; +import com.microsoft.azure.cosmosdb.rx.internal.HttpClientFactory; +import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; + +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.HttpMethod; +import io.reactivex.netty.client.RxClient; +import io.reactivex.netty.protocol.http.client.CompositeHttpClient; +import io.reactivex.netty.protocol.http.client.HttpClientRequest; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import rx.Observable; + +public class CosmosPartitionKeyTests extends TestSuiteBase { + + private final static String NON_PARTITIONED_CONTAINER_ID = "NonPartitionContainer" + UUID.randomUUID().toString(); + private final static String NON_PARTITIONED_CONTAINER_DOCUEMNT_ID = "NonPartitionContainer_Document" + UUID.randomUUID().toString(); + + private CosmosClient client; + private CosmosDatabase createdDatabase; + private CosmosClientBuilder clientBuilder; + + @Factory(dataProvider = "clientBuilders") + public CosmosPartitionKeyTests(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; + } + + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) + public void beforeClass() throws URISyntaxException, IOException { + client = clientBuilder.build(); + createdDatabase = getSharedCosmosDatabase(client); + } + + @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeDeleteDatabase(createdDatabase); + safeClose(client); + } + + private void createContainerWithoutPk() throws URISyntaxException, IOException { + ConnectionPolicy connectionPolicy = new ConnectionPolicy(); + HttpClientFactory factory = new HttpClientFactory(new Configs()) + .withMaxIdleConnectionTimeoutInMillis(connectionPolicy.getIdleConnectionTimeoutInMillis()) + .withPoolSize(connectionPolicy.getMaxPoolSize()) + .withHttpProxy(connectionPolicy.getProxy()) + .withRequestTimeoutInMillis(connectionPolicy.getRequestTimeoutInMillis()); + + CompositeHttpClient httpClient = factory.toHttpClientBuilder().build(); + + // Create a non partitioned collection using the rest API and older version + String resourceId = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.getId(); + String path = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.getId() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/"; + DocumentCollection collection = new DocumentCollection(); + collection.setId(NON_PARTITIONED_CONTAINER_ID); + + HashMap headers = new HashMap(); + headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); + headers.put(HttpConstants.HttpHeaders.VERSION, "2018-09-17"); + BaseAuthorizationTokenProvider base = new BaseAuthorizationTokenProvider(TestConfigurations.MASTER_KEY); + String authorization = base.generateKeyAuthorizationSignature(HttpConstants.HttpMethods.POST, resourceId, Paths.COLLECTIONS_PATH_SEGMENT, headers); + headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, URLEncoder.encode(authorization, "UTF-8")); + RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Create, + ResourceType.DocumentCollection, path, collection, headers, new RequestOptions()); + + String[] baseUrlSplit = TestConfigurations.HOST.split(":"); + String resourceUri = baseUrlSplit[0] + ":" + baseUrlSplit[1] + ":" + baseUrlSplit[2].split("/")[ + 0] + "//" + Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.getId() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/"; + URI uri = new URI(resourceUri); + + HttpClientRequest httpRequest = HttpClientRequest.create(HttpMethod.POST, uri.toString()); + + for (Map.Entry entry : headers.entrySet()) { + httpRequest.withHeader(entry.getKey(), entry.getValue()); + } + + httpRequest.withContent(request.getContent()); + + RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(uri.getHost(), uri.getPort()); + + InputStream responseStream = httpClient.submit(serverInfo, httpRequest).flatMap(clientResponse -> { + return toInputStream(clientResponse.getContent()); + }) + .toBlocking().single(); + String createdContainerAsString = IOUtils.readLines(responseStream, "UTF-8").get(0); + assertThat(createdContainerAsString).contains("\"id\":\"" + NON_PARTITIONED_CONTAINER_ID + "\""); + + // Create a document in the non partitioned collection using the rest API and older version + resourceId = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.getId() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/" + collection.getId(); + path = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.getId() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + + "/" + collection.getId() + "/" + Paths.DOCUMENTS_PATH_SEGMENT + "/"; + Document document = new Document(); + document.setId(NON_PARTITIONED_CONTAINER_DOCUEMNT_ID); + + authorization = base.generateKeyAuthorizationSignature(HttpConstants.HttpMethods.POST, resourceId, Paths.DOCUMENTS_PATH_SEGMENT, headers); + headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, URLEncoder.encode(authorization, "UTF-8")); + request = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Document, path, + document, headers, new RequestOptions()); + + resourceUri = baseUrlSplit[0] + ":" + baseUrlSplit[1] + ":" + baseUrlSplit[2].split("/")[0] + "//" + Paths.DATABASES_PATH_SEGMENT + "/" + + createdDatabase.getId() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/" + collection.getId() + "/" + Paths.DOCUMENTS_PATH_SEGMENT + "/"; + uri = new URI(resourceUri); + + httpRequest = HttpClientRequest.create(HttpMethod.POST, uri.toString()); + + for (Map.Entry entry : headers.entrySet()) { + httpRequest.withHeader(entry.getKey(), entry.getValue()); + } + + httpRequest.withContent(request.getContent()); + + serverInfo = new RxClient.ServerInfo(uri.getHost(), uri.getPort()); + + responseStream = httpClient.submit(serverInfo, httpRequest).flatMap(clientResponse -> { + return toInputStream(clientResponse.getContent()); + }).toBlocking().single(); + String createdItemAsString = IOUtils.readLines(responseStream, "UTF-8").get(0); + assertThat(createdItemAsString).contains("\"id\":\"" + NON_PARTITIONED_CONTAINER_DOCUEMNT_ID + "\""); + } + + @Test(groups = { "simple" }, timeOut = 10 * TIMEOUT) + public void testNonPartitionedCollectionOperations() throws Exception { + createContainerWithoutPk(); + CosmosContainer createdContainer = createdDatabase.getContainer(NON_PARTITIONED_CONTAINER_ID); + + Mono readMono = createdContainer.getItem(NON_PARTITIONED_CONTAINER_DOCUEMNT_ID, PartitionKey.None).read(); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(NON_PARTITIONED_CONTAINER_DOCUEMNT_ID).build(); + validateSuccess(readMono, validator); + + String createdItemId = UUID.randomUUID().toString(); + Mono createMono = createdContainer.createItem(new CosmosItemSettings("{'id':'" + createdItemId + "'}")); + validator = new CosmosResponseValidator.Builder() + .withId(createdItemId).build(); + validateSuccess(createMono, validator); + + readMono = createdContainer.getItem(createdItemId, PartitionKey.None).read(); + validator = new CosmosResponseValidator.Builder() + .withId(createdItemId).build(); + validateSuccess(readMono, validator); + + CosmosItem itemToReplace = createdContainer.getItem(createdItemId, PartitionKey.None).read().block().getCosmosItem(); + CosmosItemSettings itemSettingsToReplace = itemToReplace.read().block().getCosmosItemSettings(); + String replacedItemId = UUID.randomUUID().toString(); + itemSettingsToReplace.setId(replacedItemId); + Mono replaceMono = itemToReplace.replace(itemSettingsToReplace); + validator = new CosmosResponseValidator.Builder() + .withId(replacedItemId).build(); + validateSuccess(replaceMono, validator); + + String upsertedItemId = UUID.randomUUID().toString(); + + Mono upsertMono = createdContainer.upsertItem(new CosmosItemSettings("{'id':'" + upsertedItemId + "'}")); + validator = new CosmosResponseValidator.Builder() + .withId(upsertedItemId).build(); + validateSuccess(upsertMono, validator); + + // one document was created during setup, one with create (which was replaced) and one with upsert + FeedOptions feedOptions = new FeedOptions(); + feedOptions.setPartitionKey(PartitionKey.None); + ArrayList expectedIds = new ArrayList(); + expectedIds.add(NON_PARTITIONED_CONTAINER_DOCUEMNT_ID); + expectedIds.add(replacedItemId); + expectedIds.add(upsertedItemId); + Flux> queryFlux = createdContainer.queryItems("SELECT * from c", feedOptions); + FeedResponseListValidator queryValidator = new FeedResponseListValidator.Builder() + .totalSize(3) + .numberOfPages(1) + .containsExactlyIds(expectedIds) + .build(); + validateQuerySuccess(queryFlux, queryValidator); + + queryFlux = createdContainer.listItems(feedOptions); + queryValidator = new FeedResponseListValidator.Builder() + .totalSize(3) + .numberOfPages(1) + .containsExactlyIds(expectedIds) + .build(); + validateQuerySuccess(queryFlux, queryValidator); + + String documentCreatedBySprocId = "testDoc"; + CosmosStoredProcedureSettings sproc = new CosmosStoredProcedureSettings( + "{" + + " 'id': '" +UUID.randomUUID().toString() + "'," + + " 'body':'" + + " function() {" + + " var client = getContext().getCollection();" + + " var doc = client.createDocument(client.getSelfLink(), { \\'id\\': \\'" + documentCreatedBySprocId + "\\'}, {}, function(err, docCreated, options) { " + + " if(err) throw new Error(\\'Error while creating document: \\' + err.message);" + + " else {" + + " getContext().getResponse().setBody(1);" + + " }" + + " });" + + "}'" + + "}"); + CosmosStoredProcedure createdSproc = createdContainer.createStoredProcedure(sproc).block().getStoredProcedure(); + + // Partiton Key value same as what is specified in the stored procedure body + RequestOptions options = new RequestOptions(); + options.setPartitionKey(PartitionKey.None); + int result = Integer.parseInt(createdSproc.execute(null, options).block().getResponseAsString()); + assertThat(result).isEqualTo(1); + + // 3 previous items + 1 created from the sproc + expectedIds.add(documentCreatedBySprocId); + queryFlux = createdContainer.listItems(feedOptions); + queryValidator = new FeedResponseListValidator.Builder() + .totalSize(4) + .numberOfPages(1) + .containsExactlyIds(expectedIds) + .build(); + validateQuerySuccess(queryFlux, queryValidator); + + Mono deleteMono = createdContainer.getItem(upsertedItemId, PartitionKey.None).delete(); + validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteMono, validator); + + deleteMono = createdContainer.getItem(replacedItemId, PartitionKey.None).delete(); + validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteMono, validator); + + deleteMono = createdContainer.getItem(NON_PARTITIONED_CONTAINER_DOCUEMNT_ID, PartitionKey.None).delete(); + validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteMono, validator); + + deleteMono = createdContainer.getItem(documentCreatedBySprocId, PartitionKey.None).delete(); + validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteMono, validator); + + queryFlux = createdContainer.listItems(feedOptions); + queryValidator = new FeedResponseListValidator.Builder() + .totalSize(0) + .numberOfPages(1) + .build(); + validateQuerySuccess(queryFlux, queryValidator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT*100) + public void testMultiPartitionCollectionReadDocumentWithNoPk() throws InterruptedException { + String partitionedCollectionId = "PartitionedCollection" + UUID.randomUUID().toString(); + String IdOfDocumentWithNoPk = UUID.randomUUID().toString(); + CosmosContainerSettings containerSettings = new CosmosContainerSettings(partitionedCollectionId, "/mypk"); + CosmosContainer createdContainer = createdDatabase.createContainer(containerSettings).block().getContainer(); + CosmosItemSettings cosmosItemSettings = new CosmosItemSettings(); + cosmosItemSettings.setId(IdOfDocumentWithNoPk); + CosmosItem createdItem = createdContainer.createItem(cosmosItemSettings).block().getCosmosItem(); + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(PartitionKey.None); + Mono readMono = createdItem.read(options); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(IdOfDocumentWithNoPk).build(); + validateSuccess(readMono, validator); + } + + private Observable toInputStream(Observable contentObservable) { + return contentObservable.reduce(new ByteArrayOutputStream(), (out, bb) -> { + try { + bb.readBytes(out, bb.readableBytes()); + return out; + } catch (java.io.IOException e) { + throw new RuntimeException(e); + } + }).map(out -> { + return new ByteArrayInputStream(out.toByteArray()); + }); + } + +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java index 1dba279227cc7..91a319718fb18 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java @@ -1,109 +1,269 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.IndexingMode; -import com.microsoft.azure.cosmosdb.Resource; - -import java.util.ArrayList; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -public interface CosmosResponseValidator { - void validate(T cosmosResponse); - - class Builder { - private List> validators = new ArrayList<>(); - - public CosmosResponseValidator build() { - return new CosmosResponseValidator() { - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void validate(T resourceResponse) { - for (CosmosResponseValidator validator : validators) { - validator.validate(resourceResponse); - } - } - }; - } - - public Builder withId(final String resourceId) { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(T resourceResponse) { - assertThat(getResource(resourceResponse)).isNotNull(); - assertThat(getResource(resourceResponse).getId()).as("check Resource Id").isEqualTo(resourceId); - } - }); - return this; - } - - private Resource getResource(T resourceResponse) { - if(resourceResponse instanceof CosmosDatabaseResponse){ - return ((CosmosDatabaseResponse)resourceResponse).getCosmosDatabaseSettings(); - }else if(resourceResponse instanceof CosmosContainerResponse){ - return ((CosmosContainerResponse)resourceResponse).getCosmosContainerSettings(); - }else if(resourceResponse instanceof CosmosItemResponse){ - return ((CosmosItemResponse)resourceResponse).getCosmosItemSettings(); - } - return null; - } - - public Builder nullResource() { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(T resourceResponse) { - assertThat(getResource(resourceResponse)).isNull(); - } - }); - return this; - } - - public Builder indexingMode(IndexingMode mode) { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(CosmosContainerResponse resourceResponse) { - assertThat(resourceResponse.getCosmosContainerSettings()).isNotNull(); - assertThat(resourceResponse.getCosmosContainerSettings().getIndexingPolicy()).isNotNull(); - assertThat(resourceResponse.getCosmosContainerSettings().getIndexingPolicy().getIndexingMode()).isEqualTo(mode); - } - }); - return this; - } - - public Builder withProperty(String propertyName, String value) { - validators.add(new CosmosResponseValidator() { - @Override - public void validate(T cosmosResponse) { - assertThat(getResource(cosmosResponse)).isNotNull(); - assertThat(getResource(cosmosResponse).get(propertyName)).isEqualTo(value); - } - }); - return this; - } - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.CompositePath; +import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.IndexingMode; +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.SpatialSpec; +import com.microsoft.azure.cosmosdb.SpatialType; +import com.microsoft.azure.cosmosdb.StoredProcedure; +import com.microsoft.azure.cosmosdb.Trigger; +import com.microsoft.azure.cosmosdb.TriggerOperation; +import com.microsoft.azure.cosmosdb.TriggerType; +import com.microsoft.azure.cosmosdb.UserDefinedFunction; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; + +import static org.assertj.core.api.Assertions.assertThat; + +public interface CosmosResponseValidator { + void validate(T cosmosResponse); + + class Builder { + private List> validators = new ArrayList<>(); + + public CosmosResponseValidator build() { + return new CosmosResponseValidator() { + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void validate(T resourceResponse) { + for (CosmosResponseValidator validator : validators) { + validator.validate(resourceResponse); + } + } + }; + } + + public Builder withId(final String resourceId) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(T resourceResponse) { + assertThat(getResource(resourceResponse)).isNotNull(); + assertThat(getResource(resourceResponse).getId()).as("check Resource Id").isEqualTo(resourceId); + } + }); + return this; + } + + private Resource getResource(T resourceResponse) { + if (resourceResponse instanceof CosmosDatabaseResponse) { + return ((CosmosDatabaseResponse)resourceResponse).getCosmosDatabaseSettings(); + } else if (resourceResponse instanceof CosmosContainerResponse) { + return ((CosmosContainerResponse)resourceResponse).getCosmosContainerSettings(); + } else if (resourceResponse instanceof CosmosItemResponse) { + return ((CosmosItemResponse)resourceResponse).getCosmosItemSettings(); + } else if (resourceResponse instanceof CosmosStoredProcedureResponse) { + return ((CosmosStoredProcedureResponse)resourceResponse).getStoredProcedureSettings(); + } else if (resourceResponse instanceof CosmosTriggerResponse) { + return ((CosmosTriggerResponse)resourceResponse).getCosmosTriggerSettings(); + } else if (resourceResponse instanceof CosmosUserDefinedFunctionResponse) { + return ((CosmosUserDefinedFunctionResponse)resourceResponse).getCosmosUserDefinedFunctionSettings(); + } else if (resourceResponse instanceof CosmosUserResponse) { + return ((CosmosUserResponse)resourceResponse).getCosmosUserSettings(); + } + return null; + } + + public Builder nullResource() { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(T resourceResponse) { + assertThat(getResource(resourceResponse)).isNull(); + } + }); + return this; + } + + public Builder indexingMode(IndexingMode mode) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosContainerResponse resourceResponse) { + assertThat(resourceResponse.getCosmosContainerSettings()).isNotNull(); + assertThat(resourceResponse.getCosmosContainerSettings().getIndexingPolicy()).isNotNull(); + assertThat(resourceResponse.getCosmosContainerSettings().getIndexingPolicy().getIndexingMode()).isEqualTo(mode); + } + }); + return this; + } + + public Builder withProperty(String propertyName, String value) { + validators.add(new CosmosResponseValidator() { + @Override + public void validate(T cosmosResponse) { + assertThat(getResource(cosmosResponse)).isNotNull(); + assertThat(getResource(cosmosResponse).get(propertyName)).isEqualTo(value); + } + }); + return this; + } + + public Builder withCompositeIndexes(Collection> compositeIndexesWritten) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosContainerResponse resourceResponse) { + Iterator> compositeIndexesReadIterator = resourceResponse.getCosmosContainerSettings() + .getIndexingPolicy().getCompositeIndexes().iterator(); + Iterator> compositeIndexesWrittenIterator = compositeIndexesWritten.iterator(); + + ArrayList readIndexesStrings = new ArrayList(); + ArrayList writtenIndexesStrings = new ArrayList(); + + while (compositeIndexesReadIterator.hasNext() && compositeIndexesWrittenIterator.hasNext()) { + Iterator compositeIndexReadIterator = compositeIndexesReadIterator.next().iterator(); + Iterator compositeIndexWrittenIterator = compositeIndexesWrittenIterator.next().iterator(); + + StringBuilder readIndexesString = new StringBuilder(); + StringBuilder writtenIndexesString = new StringBuilder(); + + while (compositeIndexReadIterator.hasNext() && compositeIndexWrittenIterator.hasNext()) { + CompositePath compositePathRead = compositeIndexReadIterator.next(); + CompositePath compositePathWritten = compositeIndexWrittenIterator.next(); + + readIndexesString.append(compositePathRead.getPath() + ":" + compositePathRead.getOrder() + ";"); + writtenIndexesString.append(compositePathWritten.getPath() + ":" + compositePathRead.getOrder() + ";"); + } + + readIndexesStrings.add(readIndexesString.toString()); + writtenIndexesStrings.add(writtenIndexesString.toString()); + } + + assertThat(readIndexesStrings).containsExactlyInAnyOrderElementsOf(writtenIndexesStrings); + } + + }); + return this; + } + + public Builder withSpatialIndexes(Collection spatialIndexes) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosContainerResponse resourceResponse) { + Iterator spatialIndexesReadIterator = resourceResponse.getCosmosContainerSettings() + .getIndexingPolicy().getSpatialIndexes().iterator(); + Iterator spatialIndexesWrittenIterator = spatialIndexes.iterator(); + + HashMap> readIndexMap = new HashMap>(); + HashMap> writtenIndexMap = new HashMap>(); + + while (spatialIndexesReadIterator.hasNext() && spatialIndexesWrittenIterator.hasNext()) { + SpatialSpec spatialSpecRead = spatialIndexesReadIterator.next(); + SpatialSpec spatialSpecWritten = spatialIndexesWrittenIterator.next(); + + String readPath = spatialSpecRead.getPath() + ":"; + String writtenPath = spatialSpecWritten.getPath() + ":"; + + ArrayList readSpatialTypes = new ArrayList(); + ArrayList writtenSpatialTypes = new ArrayList(); + + Iterator spatialTypesReadIterator = spatialSpecRead.getSpatialTypes().iterator(); + Iterator spatialTypesWrittenIterator = spatialSpecWritten.getSpatialTypes().iterator(); + + while (spatialTypesReadIterator.hasNext() && spatialTypesWrittenIterator.hasNext()) { + readSpatialTypes.add(spatialTypesReadIterator.next()); + writtenSpatialTypes.add(spatialTypesWrittenIterator.next()); + } + + readIndexMap.put(readPath, readSpatialTypes); + writtenIndexMap.put(writtenPath, writtenSpatialTypes); + } + + for (Entry> entry : readIndexMap.entrySet()) { + assertThat(entry.getValue()) + .containsExactlyInAnyOrderElementsOf(writtenIndexMap.get(entry.getKey())); + } + } + }); + return this; + } + + public Builder withStoredProcedureBody(String storedProcedureBody) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosStoredProcedureResponse resourceResponse) { + assertThat(resourceResponse.getStoredProcedureSettings().getBody()).isEqualTo(storedProcedureBody); + } + }); + return this; + } + + public Builder notNullEtag() { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(T resourceResponse) { + assertThat(resourceResponse.getResourceSettings()).isNotNull(); + assertThat(resourceResponse.getResourceSettings().getETag()).isNotNull(); + } + }); + return this; + } + + public Builder withTriggerBody(String functionBody) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosTriggerResponse resourceResponse) { + assertThat(resourceResponse.getCosmosTriggerSettings().getBody()).isEqualTo(functionBody); + } + }); + return this; + } + + public Builder withTriggerInternals(TriggerType type, TriggerOperation op) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosTriggerResponse resourceResponse) { + assertThat(resourceResponse.getCosmosTriggerSettings().getTriggerType()).isEqualTo(type); + assertThat(resourceResponse.getCosmosTriggerSettings().getTriggerOperation()).isEqualTo(op); + } + }); + return this; + } + + public Builder withUserDefinedFunctionBody(String functionBody) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosUserDefinedFunctionResponse resourceResponse) { + assertThat(resourceResponse.getCosmosUserDefinedFunctionSettings().getBody()).isEqualTo(functionBody); + } + }); + return this; + } + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DCDocumentCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/DCDocumentCrudTest.java similarity index 96% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DCDocumentCrudTest.java rename to sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/DCDocumentCrudTest.java index 7a73fa0e04bde..a6d5286aab9d5 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/DCDocumentCrudTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.microsoft.azure.cosmosdb.internal.directconnectivity; import com.microsoft.azure.cosmosdb.ConnectionMode; import com.microsoft.azure.cosmosdb.ConnectionPolicy; @@ -38,10 +38,15 @@ import com.microsoft.azure.cosmosdb.internal.OperationType; import com.microsoft.azure.cosmosdb.internal.ResourceType; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.microsoft.azure.cosmosdb.rx.DocumentServiceRequestValidator; +import com.microsoft.azure.cosmosdb.rx.FeedResponseListValidator; +import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; +import com.microsoft.azure.cosmosdb.rx.TestConfigurations; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import com.microsoft.azure.cosmosdb.rx.internal.Configs; import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; import com.microsoft.azure.cosmosdb.rx.internal.SpyClientUnderTestFactory; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import org.mockito.stubbing.Answer; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -67,6 +72,7 @@ * The tests in other test classes validate the actual behaviour and different scenarios. */ public class DCDocumentCrudTest extends TestSuiteBase { + private final static int QUERY_TIMEOUT = 40000; private final static String PARTITION_KEY_FIELD_NAME = "mypk"; @@ -249,8 +255,8 @@ public void crossPartitionQuery() { // validates only the first query for fetching query plan goes to gateway. assertThat(client.getCapturedRequests().stream().filter(r -> r.getResourceType() == ResourceType.Document)).hasSize(1); } catch (Throwable error) { - if (clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -340,4 +346,5 @@ private Document getDocumentDefinition() { doc.set("name", "Hafez"); return doc; } + } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayAddressCacheTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayAddressCacheTest.java index 54d581f42615c..9357869954706 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayAddressCacheTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayAddressCacheTest.java @@ -36,12 +36,12 @@ import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; import com.microsoft.azure.cosmosdb.rx.internal.Configs; import com.microsoft.azure.cosmosdb.rx.internal.HttpClientFactory; import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientImpl; import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import org.mockito.Matchers; @@ -877,4 +877,4 @@ private Document getDocumentDefinition() { , uuid, uuid)); return doc; } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java index 691139545995a..0f28160d1f3da 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java @@ -45,7 +45,7 @@ import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import com.microsoft.azure.cosmosdb.rx.internal.SpyClientUnderTestFactory; import com.microsoft.azure.cosmosdb.rx.internal.SpyClientUnderTestFactory.ClientUnderTest; @@ -202,4 +202,4 @@ private HttpClientResponse getMockResponse(String databaseAccountJson) } return resp; } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AggregateQueryTests.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AggregateQueryTests.java index 3a0fb11fb207f..2a3c7696d3f69 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AggregateQueryTests.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AggregateQueryTests.java @@ -23,23 +23,25 @@ package com.microsoft.azure.cosmosdb.rx; import java.util.ArrayList; +import java.util.UUID; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; + +import reactor.core.publisher.Flux; + import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; - -import rx.Observable; public class AggregateQueryTests extends TestSuiteBase { @@ -67,9 +69,8 @@ public AggregateConfig(String operator, Object expected, String condition) { } } - private Database createdDatabase; - private DocumentCollection createdCollection; - private ArrayList docs = new ArrayList(); + private CosmosContainer createdCollection; + private ArrayList docs = new ArrayList(); private ArrayList queryConfigs = new ArrayList(); private String partitionKey = "mypk"; @@ -80,10 +81,10 @@ public AggregateConfig(String operator, Object expected, String condition) { private int numberOfDocumentsWithNumericId; private int numberOfDocsWithSamePartitionKey = 400; - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public AggregateQueryTests(Builder clientBuilder) { + public AggregateQueryTests(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -105,10 +106,9 @@ public void queryDocumentsWithAggregates(boolean qmEnabled) throws Exception { for (QueryConfig queryConfig : queryConfigs) { - Observable> queryObservable = client - .queryDocuments(createdCollection.getSelfLink(), queryConfig.query, options); + Flux> queryObservable = createdCollection.queryItems(queryConfig.query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .withAggregateValue(queryConfig.expected) .numberOfPages(1) .hasValidQueryMetrics(qmEnabled) @@ -117,8 +117,8 @@ public void queryDocumentsWithAggregates(boolean qmEnabled) throws Exception { try { validateQuerySuccess(queryObservable, validator); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -127,38 +127,35 @@ public void queryDocumentsWithAggregates(boolean qmEnabled) throws Exception { } } - public void bulkInsert(AsyncDocumentClient client) { + public void bulkInsert() { generateTestData(); - - ArrayList>> result = new ArrayList>>(); - for (int i = 0; i < docs.size(); i++) { - result.add(client.createDocument("dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(), docs.get(i), null, false)); - } - - Observable.merge(result, 100).toList().toBlocking().single(); + bulkInsertBlocking(createdCollection, docs); } public void generateTestData() { Object[] values = new Object[]{null, false, true, "abc", "cdfg", "opqrs", "ttttttt", "xyz", "oo", "ppp"}; for (int i = 0; i < values.length; i++) { - Document d = new Document(); + CosmosItemSettings d = new CosmosItemSettings(); + d.setId(UUID.randomUUID().toString()); d.set(partitionKey, values[i]); docs.add(d); } for (int i = 0; i < numberOfDocsWithSamePartitionKey; i++) { - Document d = new Document(); + CosmosItemSettings d = new CosmosItemSettings(); d.set(partitionKey, uniquePartitionKey); d.set("resourceId", Integer.toString(i)); d.set(field, i + 1); + d.setId(UUID.randomUUID().toString()); docs.add(d); } numberOfDocumentsWithNumericId = numberOfDocuments - values.length - numberOfDocsWithSamePartitionKey; for (int i = 0; i < numberOfDocumentsWithNumericId; i++) { - Document d = new Document(); + CosmosItemSettings d = new CosmosItemSettings(); d.set(partitionKey, i + 1); + d.setId(UUID.randomUUID().toString()); docs.add(d); } @@ -223,14 +220,13 @@ public void afterClass() { safeClose(client); } - @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT * 100) public void beforeClass() throws Exception { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; - truncateCollection(SHARED_MULTI_PARTITION_COLLECTION); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); - bulkInsert(client); + bulkInsert(); generateTestConfigs(); waitIfNeededForReplicasToCatchUp(clientBuilder); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AttachmentCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AttachmentCrudTest.java deleted file mode 100644 index a229e251a2a5d..0000000000000 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AttachmentCrudTest.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx; - -import java.util.UUID; - -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import org.testng.SkipException; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import com.microsoft.azure.cosmosdb.Attachment; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; - -import rx.Observable; - -import javax.net.ssl.SSLException; - -public class AttachmentCrudTest extends TestSuiteBase { - - private Database createdDatabase; - private DocumentCollection createdCollection; - private Document createdDocument; - - private AsyncDocumentClient client; - - @Factory(dataProvider = "clientBuildersWithDirectHttps") // Direct TCP mode does not support attachments - public AttachmentCrudTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void createAttachment() throws Exception { - // create an Attachment - String uuid = UUID.randomUUID().toString(); - Attachment attachment = getAttachmentDefinition(uuid, "application/text"); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(createdDocument.getId())); - Observable> createObservable = client.createAttachment(getDocumentLink(), attachment, options); - - // validate attachment creation - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(attachment.getId()) - .withContentType("application/text") - .notNullEtag() - .build(); - validateSuccess(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void readAttachment() throws Exception { - // create an Attachment - String uuid = UUID.randomUUID().toString(); - Attachment attachment = getAttachmentDefinition(uuid, "application/text"); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(createdDocument.getId())); - Attachment readBackAttachment = client.createAttachment(getDocumentLink(), attachment, options).toBlocking().single().getResource(); - - waitIfNeededForReplicasToCatchUp(clientBuilder); - - // read attachment - Observable> readObservable = client.readAttachment(readBackAttachment.getSelfLink(), options); - - // validate attachment read - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(attachment.getId()) - .withContentType("application/text") - .notNullEtag() - .build(); - validateSuccess(readObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void deleteAttachment() throws Exception { - // create an Attachment - String uuid = UUID.randomUUID().toString(); - Attachment attachment = getAttachmentDefinition(uuid, "application/text"); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(createdDocument.getId())); - Attachment readBackAttachment = client.createAttachment(getDocumentLink(), attachment, options).toBlocking().single().getResource(); - - // delete attachment - Observable> deleteObservable = client.deleteAttachment(readBackAttachment.getSelfLink(), options); - - // validate attachment delete - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .nullResource() - .build(); - validateSuccess(deleteObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void upsertAttachment() throws Exception { - // create an Attachment - String uuid = UUID.randomUUID().toString(); - Attachment attachment = getAttachmentDefinition(uuid, "application/text"); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(createdDocument.getId())); - Attachment readBackAttachment = client.upsertAttachment(getDocumentLink(), attachment, options).toBlocking().single().getResource(); - - // read attachment - waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readAttachment(readBackAttachment.getSelfLink(), options); - - // validate attachment read - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(attachment.getId()) - .withContentType("application/text") - .notNullEtag() - .build(); - validateSuccess(readObservable, validator); - - //update attachment - readBackAttachment.setContentType("application/json"); - - Observable> updateObservable = client.upsertAttachment(getDocumentLink(), readBackAttachment, options); - - // validate attachment update - ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() - .withId(readBackAttachment.getId()) - .withContentType("application/json") - .notNullEtag() - .build(); - validateSuccess(updateObservable, validatorForUpdate); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void replaceAttachment() throws Exception { - // create an Attachment - String uuid = UUID.randomUUID().toString(); - Attachment attachment = getAttachmentDefinition(uuid, "application/text"); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(createdDocument.getId())); - Attachment readBackAttachment = client.createAttachment(getDocumentLink(), attachment, options).toBlocking().single().getResource(); - - - // read attachment - waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readAttachment(readBackAttachment.getSelfLink(), options); - - // validate attachment read - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(attachment.getId()) - .withContentType("application/text") - .notNullEtag() - .build(); - validateSuccess(readObservable, validator); - - //update attachment - readBackAttachment.setContentType("application/json"); - - Observable> updateObservable = client.replaceAttachment(readBackAttachment, options); - - // validate attachment update - ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() - .withId(readBackAttachment.getId()) - .withContentType("application/json") - .notNullEtag() - .build(); - validateSuccess(updateObservable, validatorForUpdate); - } - - @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; - createdDocument = createDocument(client, createdDatabase.getId(), createdCollection.getId(), getDocumentDefinition()); - } - - @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeClose(client); - } - - private String getDocumentLink() { - return createdDocument.getSelfLink(); - } - - private static Document getDocumentDefinition() { - String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " - + "\"id\": \"%s\", " - + "\"mypk\": \"%s\", " - + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" - + "}" - , uuid, uuid)); - return doc; - } - - private static Attachment getAttachmentDefinition(String uuid, String type) { - return new Attachment(String.format( - "{" + - " 'id': '%s'," + - " 'media': 'http://xstore.'," + - " 'MediaType': 'Book'," + - " 'Author': 'My Book Author'," + - " 'Title': 'My Book Title'," + - " 'contentType': '%s'" + - "}", uuid, type)); - } -} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AttachmentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AttachmentQueryTest.java deleted file mode 100644 index 1a353241e4b95..0000000000000 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AttachmentQueryTest.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import com.microsoft.azure.cosmosdb.Attachment; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; - -import rx.Observable; - -public class AttachmentQueryTest extends TestSuiteBase { - - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdAttachments = new ArrayList<>(); - - private Document createdDocument; - - private AsyncDocumentClient client; - - public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); - } - - public String getDocumentLink() { - return createdDocument.getSelfLink(); - } - - @Factory(dataProvider = "clientBuilders") - public AttachmentQueryTest(Builder clientBuilder) { - this.clientBuilder = clientBuilder; - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void queryWithFilter() throws Exception { - - String filterId = createdAttachments.get(0).getId(); - String query = String.format("SELECT * from c where c.id = '%s'", filterId); - - FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); - Observable> queryObservable = client - .queryAttachments(getDocumentLink(), query, options); - - List expectedDocs = createdAttachments.stream().filter(sp -> filterId.equals(sp.getId()) ).collect(Collectors.toList()); - assertThat(expectedDocs).isNotEmpty(); - - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() - .totalSize(expectedDocs.size()) - .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) - .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() - .requestChargeGreaterThanOrEqualTo(1.0).build()) - .build(); - - validateQuerySuccess(queryObservable, validator, 10000); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void query_NoResults() throws Exception { - - String query = "SELECT * from root r where r.id = '2'"; - FeedOptions options = new FeedOptions(); - Observable> queryObservable = client - .queryAttachments(getDocumentLink(), query, options); - - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() - .containsExactly(new ArrayList<>()) - .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() - .requestChargeGreaterThanOrEqualTo(1.0).build()) - .build(); - validateQuerySuccess(queryObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void queryAll() throws Exception { - - String query = "SELECT * from root"; - FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); - options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryAttachments(getDocumentLink(), query, options); - - List expectedDocs = createdAttachments; - - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() - .exactlyContainsInAnyOrder(expectedDocs - .stream() - .map(d -> d.getResourceId()) - .collect(Collectors.toList())) - .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() - .requestChargeGreaterThanOrEqualTo(1.0).build()) - .build(); - validateQuerySuccess(queryObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void invalidQuerySytax() throws Exception { - String query = "I am an invalid query"; - FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); - - FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) - .statusCode(400) - .notNullActivityId() - .build(); - validateQueryFailure(queryObservable, validator); - } - - public Attachment createAttachment(AsyncDocumentClient client) { - Attachment attachment = getAttachmentDefinition(); - return client.createAttachment(getDocumentLink(), attachment, null).toBlocking().single().getResource(); - } - - @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeClose(client); - } - - @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) - public void beforeClass() throws Exception { - client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); - - Document docDef = new Document(); - docDef.setId(UUID.randomUUID().toString()); - - createdDocument = createDocument(client, createdDatabase.getId(), createdCollection.getId(), docDef); - - for(int i = 0; i < 5; i++) { - createdAttachments.add(createAttachment(client)); - } - - waitIfNeededForReplicasToCatchUp(clientBuilder); - } - - private static Attachment getAttachmentDefinition() { - return new Attachment(String.format( - "{" + - " 'id': '%s'," + - " 'media': 'http://xstore.'," + - " 'MediaType': 'Book'," + - " 'Author': 'My Book Author'," + - " 'Title': 'My Book Title'," + - " 'contentType': '%s'" + - "}", UUID.randomUUID().toString(), "application/text")); - } -} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureCrossPartitionTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureCrossPartitionTest.java index 2a40e985d409b..a8fc9f00ab9c2 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureCrossPartitionTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureCrossPartitionTest.java @@ -22,21 +22,29 @@ */ package com.microsoft.azure.cosmosdb.rx; +import com.microsoft.azure.cosmos.ClientUnderTestBuilder; +import com.microsoft.azure.cosmos.CosmosBridgeInternal; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.IncludedPath; import com.microsoft.azure.cosmosdb.Index; import com.microsoft.azure.cosmosdb.IndexingPolicy; import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientUnderTest; + +import io.reactivex.subscribers.TestSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.SkipException; @@ -45,10 +53,8 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.util.concurrent.Queues; import rx.Observable; -import rx.internal.util.RxRingBuffer; -import rx.observers.TestSubscriber; -import rx.schedulers.Schedulers; import java.util.ArrayList; import java.util.Collection; @@ -65,18 +71,18 @@ public class BackPressureCrossPartitionTest extends TestSuiteBase { private static final int SETUP_TIMEOUT = 60000; private int numberOfDocs = 4000; - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdDocuments; + private CosmosDatabase createdDatabase; + private CosmosContainer createdCollection; + private List createdDocuments; - private RxDocumentClientUnderTest client; + private CosmosClient client; private int numberOfPartitions; public String getCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); } - static protected DocumentCollection getCollectionDefinition() { + static protected CosmosContainerSettings getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); @@ -98,16 +104,16 @@ static protected DocumentCollection getCollectionDefinition() { includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); - collectionDefinition.setPartitionKey(partitionKeyDef); + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings( + UUID.randomUUID().toString(), + partitionKeyDef); collectionDefinition.setIndexingPolicy(indexingPolicy); return collectionDefinition; } @Factory(dataProvider = "simpleClientBuildersWithDirectHttps") - public BackPressureCrossPartitionTest(Builder clientBuilder) { + public BackPressureCrossPartitionTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -115,19 +121,19 @@ private void warmUp() { FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); // ensure collection is cached - client.queryDocuments(getCollectionLink(), "SELECT * FROM r", options).first().toBlocking().single(); + createdCollection.queryItems("SELECT * FROM r", options).blockFirst(); } @DataProvider(name = "queryProvider") public Object[][] queryProvider() { return new Object[][] { // query, maxItemCount, max expected back pressure buffered, total number of expected query results - { "SELECT * FROM r", 1, 2 * RxRingBuffer.SIZE, numberOfDocs}, - { "SELECT * FROM r", 100, 2 * RxRingBuffer.SIZE, numberOfDocs}, - { "SELECT * FROM r ORDER BY r.prop", 100, 2 * RxRingBuffer.SIZE + 3 * numberOfPartitions, numberOfDocs}, - { "SELECT TOP 1000 * FROM r", 1, 2 * RxRingBuffer.SIZE, 1000}, - { "SELECT TOP 1000 * FROM r", 100, 2 * RxRingBuffer.SIZE, 1000}, - { "SELECT TOP 1000 * FROM r ORDER BY r.prop", 100, 2 * RxRingBuffer.SIZE + 3 * numberOfPartitions , 1000}, + { "SELECT * FROM r", 1, 2 * Queues.SMALL_BUFFER_SIZE, numberOfDocs}, + { "SELECT * FROM r", 100, 2 * Queues.SMALL_BUFFER_SIZE, numberOfDocs}, + { "SELECT * FROM r ORDER BY r.prop", 100, 2 * Queues.SMALL_BUFFER_SIZE + 3 * numberOfPartitions, numberOfDocs}, + { "SELECT TOP 1000 * FROM r", 1, 2 * Queues.SMALL_BUFFER_SIZE, 1000}, + { "SELECT TOP 1000 * FROM r", 100, 2 * Queues.SMALL_BUFFER_SIZE, 1000}, + { "SELECT TOP 1000 * FROM r ORDER BY r.prop", 100, 2 * Queues.SMALL_BUFFER_SIZE + 3 * numberOfPartitions , 1000}, }; } @@ -140,20 +146,20 @@ public void query(String query, int maxItemCount, int maxExpectedBufferedCountFo options.setEnableCrossPartitionQuery(true); options.setMaxItemCount(maxItemCount); options.setMaxDegreeOfParallelism(2); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); - client.httpRequests.clear(); + RxDocumentClientUnderTest rxClient = (RxDocumentClientUnderTest)CosmosBridgeInternal.getAsyncDocumentClient(client); + rxClient.httpRequests.clear(); log.info("instantiating subscriber ..."); - TestSubscriber> subscriber = new TestSubscriber<>(1); - queryObservable.observeOn(Schedulers.io(), 1).subscribe(subscriber); + TestSubscriber> subscriber = new TestSubscriber<>(1); + queryObservable.publishOn(Schedulers.elastic()).subscribe(subscriber); int sleepTimeInMillis = 40000; int i = 0; // use a test subscriber and request for more result and sleep in between try { - while(subscriber.getCompletions() == 0 && subscriber.getOnErrorEvents().isEmpty()) { + while(subscriber.completions() == 0 && subscriber.errorCount() == 0) { log.debug("loop " + i); TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis); @@ -161,15 +167,14 @@ public void query(String query, int maxItemCount, int maxExpectedBufferedCountFo if (sleepTimeInMillis > 4000) { // validate that only one item is returned to subscriber in each iteration - assertThat(subscriber.getValueCount() - i).isEqualTo(1); + assertThat(subscriber.valueCount() - i).isEqualTo(1); } - log.debug("subscriber.getValueCount(): " + subscriber.getValueCount()); - log.debug("client.httpRequests.size(): " + client.httpRequests.size()); + log.debug("subscriber.getValueCount(): " + subscriber.valueCount()); + log.debug("client.httpRequests.size(): " + rxClient.httpRequests.size()); // validate that the difference between the number of requests to backend // and the number of returned results is always less than a fixed threshold - - assertThat(client.httpRequests.size() - subscriber.getValueCount()) + assertThat(rxClient.httpRequests.size() - subscriber.valueCount()) .isLessThanOrEqualTo(maxExpectedBufferedCountForBackPressure); log.debug("requesting more"); @@ -177,8 +182,8 @@ public void query(String query, int maxItemCount, int maxExpectedBufferedCountFo i++; } } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -187,11 +192,11 @@ public void query(String query, int maxItemCount, int maxExpectedBufferedCountFo try { subscriber.assertNoErrors(); - subscriber.assertCompleted(); - assertThat(subscriber.getOnNextEvents().stream().mapToInt(p -> p.getResults().size()).sum()).isEqualTo(expectedNumberOfResults); + subscriber.assertComplete(); + assertThat(subscriber.values().stream().mapToInt(p -> p.getResults().size()).sum()).isEqualTo(expectedNumberOfResults); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -201,27 +206,22 @@ public void query(String query, int maxItemCount, int maxExpectedBufferedCountFo @BeforeClass(groups = { "long" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - RequestOptions options = new RequestOptions(); - options.setOfferThroughput(20000); - createdDatabase = SHARED_DATABASE; - createdCollection = createCollection(createdDatabase.getId(), getCollectionDefinition(), options); - + CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); + options.offerThroughput(20000); client = new ClientUnderTestBuilder(clientBuilder).build(); + createdDatabase = getSharedCosmosDatabase(client); + createdCollection = createCollection(createdDatabase, getCollectionDefinition(), options); - ArrayList docDefList = new ArrayList<>(); + ArrayList docDefList = new ArrayList<>(); for(int i = 0; i < numberOfDocs; i++) { docDefList.add(getDocumentDefinition(i)); } - Observable> documentBulkInsertObs = bulkInsert( - client, - getCollectionLink(), - docDefList, - 1000); - - createdDocuments = documentBulkInsertObs.map(ResourceResponse::getResource).toList().toBlocking().single(); + createdDocuments = bulkInsertBlocking( + createdCollection, + docDefList); - numberOfPartitions = client.readPartitionKeyRanges(getCollectionLink(), null) + numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client).readPartitionKeyRanges(getCollectionLink(), null) .flatMap(p -> Observable.from(p.getResults())).toList().toBlocking().single().size(); waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -233,13 +233,13 @@ public void beforeClass() { @AfterClass(groups = { "long" }, timeOut = 2 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteCollection(client, createdCollection); + safeDeleteCollection(createdCollection); safeClose(client); } - private static Document getDocumentDefinition(int cnt) { + private static CosmosItemSettings getDocumentDefinition(int cnt) { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " + CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + "\"id\": \"%s\", " + "\"prop\" : %d, " + "\"mypk\": \"%s\", " diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureTest.java index c22fc3a4da068..2ac124487fc5d 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureTest.java @@ -22,24 +22,30 @@ */ package com.microsoft.azure.cosmosdb.rx; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmos.ClientUnderTestBuilder; +import com.microsoft.azure.cosmos.CosmosBridgeInternal; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientUnderTest; + +import io.reactivex.subscribers.TestSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; + import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; -import rx.internal.util.RxRingBuffer; -import rx.observers.TestSubscriber; -import rx.schedulers.Schedulers; +import reactor.util.concurrent.Queues; import java.util.ArrayList; import java.util.List; @@ -53,24 +59,28 @@ public class BackPressureTest extends TestSuiteBase { private static final int TIMEOUT = 200000; private static final int SETUP_TIMEOUT = 60000; - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdDocuments; + private CosmosDatabase createdDatabase; + private CosmosContainer createdCollection; + private List createdDocuments; - private RxDocumentClientUnderTest client; + private CosmosClient client; public String getCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); } - private static DocumentCollection getSinglePartitionCollectionDefinition() { - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + private static CosmosContainerSettings getSinglePartitionCollectionDefinition() { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } @Factory(dataProvider = "simpleClientBuildersWithDirectHttps") - public BackPressureTest(Builder clientBuilder) { + public BackPressureTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -78,76 +88,78 @@ public BackPressureTest(Builder clientBuilder) { public void readFeed() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(1); - Observable> queryObservable = client - .readDocuments(getCollectionLink(), options); + options.setEnableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.listItems(options); - client.httpRequests.clear(); + RxDocumentClientUnderTest rxClient = (RxDocumentClientUnderTest)CosmosBridgeInternal.getAsyncDocumentClient(client); + rxClient.httpRequests.clear(); - TestSubscriber subscriber = new TestSubscriber(1); - queryObservable.observeOn(Schedulers.io(), 1).subscribe(subscriber); + TestSubscriber> subscriber = new TestSubscriber>(1); + queryObservable.publishOn(Schedulers.elastic()).subscribe(subscriber); int sleepTimeInMillis = 10000; // 10 seconds int i = 0; // use a test subscriber and request for more result and sleep in between - while (subscriber.getCompletions() == 0 && subscriber.getOnErrorEvents().isEmpty()) { + while (subscriber.completions() == 0 && subscriber.getEvents().get(1).isEmpty()) { TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis); sleepTimeInMillis /= 2; if (sleepTimeInMillis > 1000) { // validate that only one item is returned to subscriber in each iteration - assertThat(subscriber.getValueCount() - i).isEqualTo(1); + assertThat(subscriber.valueCount() - i).isEqualTo(1); } // validate that only one item is returned to subscriber in each iteration // validate that the difference between the number of requests to backend // and the number of returned results is always less than a fixed threshold - assertThat(client.httpRequests.size() - subscriber.getOnNextEvents().size()) - .isLessThanOrEqualTo(RxRingBuffer.SIZE); + assertThat(rxClient.httpRequests.size() - subscriber.getEvents().get(0).size()) + .isLessThanOrEqualTo(Queues.SMALL_BUFFER_SIZE); subscriber.requestMore(1); i++; } subscriber.assertNoErrors(); - subscriber.assertCompleted(); - assertThat(subscriber.getOnNextEvents()).hasSize(createdDocuments.size()); + subscriber.assertComplete(); + assertThat(subscriber.getEvents().get(0)).hasSize(createdDocuments.size()); } @Test(groups = { "long" }, timeOut = TIMEOUT) public void query() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(1); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), "SELECT * from r", options); + options.setEnableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems("SELECT * from r", options); - client.httpRequests.clear(); + RxDocumentClientUnderTest rxClient = (RxDocumentClientUnderTest)CosmosBridgeInternal.getAsyncDocumentClient(client); + rxClient.httpRequests.clear(); - TestSubscriber subscriber = new TestSubscriber(1); - queryObservable.observeOn(Schedulers.io(), 1).subscribe(subscriber); + TestSubscriber> subscriber = new TestSubscriber>(1); + queryObservable.publishOn(Schedulers.elastic()).subscribe(subscriber); int sleepTimeInMillis = 10000; int i = 0; // use a test subscriber and request for more result and sleep in between - while(subscriber.getCompletions() == 0 && subscriber.getOnErrorEvents().isEmpty()) { + while(subscriber.completions() == 0 && subscriber.getEvents().get(1).isEmpty()) { TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis); sleepTimeInMillis /= 2; if (sleepTimeInMillis > 1000) { // validate that only one item is returned to subscriber in each iteration - assertThat(subscriber.getValueCount() - i).isEqualTo(1); + assertThat(subscriber.valueCount() - i).isEqualTo(1); } // validate that the difference between the number of requests to backend // and the number of returned results is always less than a fixed threshold - assertThat(client.httpRequests.size() - subscriber.getValueCount()) - .isLessThanOrEqualTo(RxRingBuffer.SIZE); + assertThat(rxClient.httpRequests.size() - subscriber.valueCount()) + .isLessThanOrEqualTo(Queues.SMALL_BUFFER_SIZE); subscriber.requestMore(1); i++; } subscriber.assertNoErrors(); - subscriber.assertCompleted(); + subscriber.assertComplete(); - assertThat(subscriber.getOnNextEvents()).hasSize(createdDocuments.size()); + assertThat(subscriber.getEvents().get(0)).hasSize(createdDocuments.size()); } // TODO: DANOBLE: Investigate Direct TCP performance issue @@ -157,35 +169,31 @@ public void query() throws Exception { @BeforeClass(groups = { "long" }, timeOut = 2 * SETUP_TIMEOUT) public void beforeClass() throws Exception { - RequestOptions options = new RequestOptions(); - options.setOfferThroughput(1000); - createdDatabase = SHARED_DATABASE; - createdCollection = createCollection(createdDatabase.getId(), getSinglePartitionCollectionDefinition(), options); - + CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); + options.offerThroughput(1000); client = new ClientUnderTestBuilder(clientBuilder).build(); + createdDatabase = getSharedCosmosDatabase(client); + + createdCollection = createCollection(createdDatabase, getSinglePartitionCollectionDefinition(), options); + + RxDocumentClientUnderTest rxClient = (RxDocumentClientUnderTest)CosmosBridgeInternal.getAsyncDocumentClient(client); // increase throughput to max for a single partition collection to avoid throttling // for bulk insert and later queries. - Offer offer = client.queryOffers( + Offer offer = rxClient.queryOffers( String.format("SELECT * FROM r WHERE r.offerResourceId = '%s'", - createdCollection.getResourceId()) + createdCollection.read().block().getCosmosContainerSettings().getResourceId()) , null).first().map(FeedResponse::getResults).toBlocking().single().get(0); offer.setThroughput(6000); - offer = client.replaceOffer(offer).toBlocking().single().getResource(); + offer = rxClient.replaceOffer(offer).toBlocking().single().getResource(); assertThat(offer.getThroughput()).isEqualTo(6000); - ArrayList docDefList = new ArrayList<>(); + ArrayList docDefList = new ArrayList<>(); for(int i = 0; i < 1000; i++) { docDefList.add(getDocumentDefinition(i)); } - Observable> documentBulkInsertObs = bulkInsert( - client, - getCollectionLink(), - docDefList, - 200); - - createdDocuments = documentBulkInsertObs.map(ResourceResponse::getResource).toList().toBlocking().single(); + createdDocuments = bulkInsertBlocking(createdCollection, docDefList); waitIfNeededForReplicasToCatchUp(clientBuilder); warmUp(); @@ -193,7 +201,9 @@ public void beforeClass() throws Exception { private void warmUp() { // ensure collection is cached - client.queryDocuments(getCollectionLink(), "SELECT * from r", null).first().toBlocking().single(); + FeedOptions options = new FeedOptions(); + options.setEnableCrossPartitionQuery(true); + createdCollection.queryItems("SELECT * from r", options).blockFirst(); } // TODO: DANOBLE: Investigate Direct TCP performance issue @@ -202,13 +212,13 @@ private void warmUp() { @AfterClass(groups = { "long" }, timeOut = 2 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteCollection(client, createdCollection); + safeDeleteCollection(createdCollection); safeClose(client); } - private static Document getDocumentDefinition(int cnt) { + private static CosmosItemSettings getDocumentDefinition(int cnt) { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " + CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + "\"id\": \"%s\", " + "\"prop\" : %d, " + "\"mypk\": \"%s\", " diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ChangeFeedTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ChangeFeedTest.java index b2446f3330198..2dadeb8bf6df6 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ChangeFeedTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ChangeFeedTest.java @@ -35,13 +35,13 @@ import com.microsoft.azure.cosmosdb.ChangeFeedOptions; import com.microsoft.azure.cosmosdb.Database; import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.PartitionKey; import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; @@ -51,10 +51,10 @@ import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import rx.Observable; +//TODO: change to use external TestSuiteBase public class ChangeFeedTest extends TestSuiteBase { private static final int SETUP_TIMEOUT = 40000; @@ -312,4 +312,4 @@ private static void waitAtleastASecond(ZonedDateTime befTime) throws Interrupted Thread.sleep(100); } } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java index 7f157cf677bc3..6ed1c702cf7dc 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java @@ -1,336 +1,333 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.UUID; - -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RetryAnalyzer; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import com.microsoft.azure.cosmosdb.CompositePath; -import com.microsoft.azure.cosmosdb.CompositePathSortOrder; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.IndexingMode; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.SpatialSpec; -import com.microsoft.azure.cosmosdb.SpatialType; - -import rx.Observable; - -public class CollectionCrudTest extends TestSuiteBase { - private static final int TIMEOUT = 50000; - private static final int SETUP_TIMEOUT = 20000; - private static final int SHUTDOWN_TIMEOUT = 20000; - private final String databaseId = DatabaseForTest.generateId(); - - private AsyncDocumentClient client; - private Database database; - - @Factory(dataProvider = "clientBuildersWithDirect") - public CollectionCrudTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; - this.subscriberValidationTimeout = TIMEOUT; - } - - @DataProvider(name = "collectionCrudArgProvider") - public Object[][] collectionCrudArgProvider() { - return new Object[][] { - // collection name, is name base - {UUID.randomUUID().toString(), false } , - {UUID.randomUUID().toString(), true } , - - // with special characters in the name. - {"+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~", true } , - }; - } - - private DocumentCollection getCollectionDefinition(String collectionName) { - PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); - ArrayList paths = new ArrayList(); - paths.add("/mypk"); - partitionKeyDef.setPaths(paths); - - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(collectionName); - collectionDefinition.setPartitionKey(partitionKeyDef); - - return collectionDefinition; - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void createCollection(String collectionName, boolean isNameBased) { - DocumentCollection collectionDefinition = getCollectionDefinition(collectionName); - - Observable> createObservable = client - .createCollection(getDatabaseLink(database, isNameBased), collectionDefinition, null); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(collectionDefinition.getId()).build(); - - validateSuccess(createObservable, validator); - safeDeleteAllCollections(client, database); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT) - public void createCollectionWithCompositeIndexAndSpatialSpec() { - DocumentCollection collection = new DocumentCollection(); - - IndexingPolicy indexingPolicy = new IndexingPolicy(); - CompositePath compositePath1 = new CompositePath(); - compositePath1.setPath("/path1"); - compositePath1.setOrder(CompositePathSortOrder.Ascending); - CompositePath compositePath2 = new CompositePath(); - compositePath2.setPath("/path2"); - compositePath2.setOrder(CompositePathSortOrder.Descending); - CompositePath compositePath3 = new CompositePath(); - compositePath3.setPath("/path3"); - CompositePath compositePath4 = new CompositePath(); - compositePath4.setPath("/path4"); - compositePath4.setOrder(CompositePathSortOrder.Ascending); - CompositePath compositePath5 = new CompositePath(); - compositePath5.setPath("/path5"); - compositePath5.setOrder(CompositePathSortOrder.Descending); - CompositePath compositePath6 = new CompositePath(); - compositePath6.setPath("/path6"); - - ArrayList compositeIndex1 = new ArrayList(); - compositeIndex1.add(compositePath1); - compositeIndex1.add(compositePath2); - compositeIndex1.add(compositePath3); - - ArrayList compositeIndex2 = new ArrayList(); - compositeIndex2.add(compositePath4); - compositeIndex2.add(compositePath5); - compositeIndex2.add(compositePath6); - - Collection> compositeIndexes = new ArrayList>(); - compositeIndexes.add(compositeIndex1); - compositeIndexes.add(compositeIndex2); - indexingPolicy.setCompositeIndexes(compositeIndexes); - - SpatialType[] spatialTypes = new SpatialType[] { - SpatialType.Point, - SpatialType.LineString, - SpatialType.Polygon, - SpatialType.MultiPolygon - }; - Collection spatialIndexes = new ArrayList(); - for (int index = 0; index < 2; index++) { - Collection collectionOfSpatialTypes = new ArrayList(); - - SpatialSpec spec = new SpatialSpec(); - spec.setPath("/path" + index + "/*"); - - for (int i = index; i < index + 3; i++) { - collectionOfSpatialTypes.add(spatialTypes[i]); - } - spec.setSpatialTypes(collectionOfSpatialTypes); - spatialIndexes.add(spec); - } - - indexingPolicy.setSpatialIndexes(spatialIndexes); - - collection.setId(UUID.randomUUID().toString()); - collection.setIndexingPolicy(indexingPolicy); - - Observable> createObservable = client - .createCollection(database.getSelfLink(), collection, null); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(collection.getId()) - .withCompositeIndexes(compositeIndexes) - .withSpatialIndexes(spatialIndexes) - .build(); - - validateSuccess(createObservable, validator); - safeDeleteAllCollections(client, database); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void readCollection(String collectionName, boolean isNameBased) { - DocumentCollection collectionDefinition = getCollectionDefinition(collectionName); - - Observable> createObservable = client.createCollection(getDatabaseLink(database, isNameBased), collectionDefinition, - null); - DocumentCollection collection = createObservable.toBlocking().single().getResource(); - - Observable> readObservable = client.readCollection(getCollectionLink(database, collection, isNameBased), null); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(collection.getId()).build(); - validateSuccess(readObservable, validator); - safeDeleteAllCollections(client, database); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void readCollection_NameBase(String collectionName, boolean isNameBased) { - DocumentCollection collectionDefinition = getCollectionDefinition(collectionName); - - Observable> createObservable = client.createCollection(getDatabaseLink(database, isNameBased), collectionDefinition, - null); - DocumentCollection collection = createObservable.toBlocking().single().getResource(); - - Observable> readObservable = client.readCollection( - getCollectionLink(database, collection, isNameBased), null); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(collection.getId()).build(); - validateSuccess(readObservable, validator); - safeDeleteAllCollections(client, database); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void readCollection_DoesntExist(String collectionName, boolean isNameBased) throws Exception { - - Observable> readObservable = client - .readCollection(Utils.getCollectionNameLink(database.getId(), "I don't exist"), null); - - FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(readObservable, validator); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void deleteCollection(String collectionName, boolean isNameBased) { - DocumentCollection collectionDefinition = getCollectionDefinition(collectionName); - - Observable> createObservable = client.createCollection(getDatabaseLink(database, isNameBased), collectionDefinition, null); - DocumentCollection collection = createObservable.toBlocking().single().getResource(); - - Observable> deleteObservable = client.deleteCollection(getCollectionLink(database, collection, isNameBased), - null); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .nullResource().build(); - validateSuccess(deleteObservable, validator); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void replaceCollection(String collectionName, boolean isNameBased) { - // create a collection - DocumentCollection collectionDefinition = getCollectionDefinition(collectionName); - Observable> createObservable = client.createCollection(getDatabaseLink(database, isNameBased), collectionDefinition, null); - DocumentCollection collection = createObservable.toBlocking().single().getResource(); - // sanity check - assertThat(collection.getIndexingPolicy().getIndexingMode()).isEqualTo(IndexingMode.Consistent); - - // replace indexing mode - IndexingPolicy indexingMode = new IndexingPolicy(); - indexingMode.setIndexingMode(IndexingMode.Lazy); - collection.setIndexingPolicy(indexingMode); - Observable> readObservable = client.replaceCollection(collection, null); - - // validate - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .indexingMode(IndexingMode.Lazy).build(); - validateSuccess(readObservable, validator); - safeDeleteAllCollections(client, database); - } - - @Test(groups = { "emulator" }, timeOut = 10 * TIMEOUT, retryAnalyzer = RetryAnalyzer.class) - public void sessionTokenConsistencyCollectionDeleteCreateSameName() { - AsyncDocumentClient client1 = clientBuilder.build(); - AsyncDocumentClient client2 = clientBuilder.build(); - - String dbId = DatabaseForTest.generateId(); - String collectionId = "coll"; - try { - Database databaseDefinition = new Database(); - databaseDefinition.setId(dbId); - createDatabase(client1, dbId); - - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(collectionId); - DocumentCollection collection = createCollection(client1, dbId, collectionDefinition); - - Document document = new Document(); - document.setId("doc"); - document.set("name", "New Document"); - createDocument(client1, dbId, collectionId, document); - ResourceResponse readDocumentResponse = client1.readDocument(Utils.getDocumentNameLink(dbId, collectionId, document.getId()), null).toBlocking().single(); - logger.info("Client 1 Read Document Client Side Request Statistics {}", readDocumentResponse.getRequestDiagnosticsString()); - logger.info("Client 1 Read Document Latency {}", readDocumentResponse.getRequestLatency()); - - document.set("name", "New Updated Document"); - ResourceResponse upsertDocumentResponse = client1.upsertDocument(collection.getSelfLink(), document, null, - true).toBlocking().single(); - logger.info("Client 1 Upsert Document Client Side Request Statistics {}", upsertDocumentResponse.getRequestDiagnosticsString()); - logger.info("Client 1 Upsert Document Latency {}", upsertDocumentResponse.getRequestLatency()); - - // Delete the existing collection - deleteCollection(client2, Utils.getCollectionNameLink(dbId, collectionId)); - // Recreate the collection with the same name but with different client - createCollection(client2, dbId, collectionDefinition); - - Document newDocument = new Document(); - newDocument.setId("doc"); - newDocument.set("name", "New Created Document"); - createDocument(client2, dbId, collectionId, newDocument); - - readDocumentResponse = client1.readDocument(Utils.getDocumentNameLink(dbId, collectionId, newDocument.getId()), null).toBlocking().single(); - logger.info("Client 2 Read Document Client Side Request Statistics {}", readDocumentResponse.getRequestDiagnosticsString()); - logger.info("Client 2 Read Document Latency {}", readDocumentResponse.getRequestLatency()); - - Document readDocument = readDocumentResponse.getResource(); - - assertThat(readDocument.getId().equals(newDocument.getId())).isTrue(); - assertThat(readDocument.get("name").equals(newDocument.get("name"))).isTrue(); - } finally { - safeDeleteDatabase(client1, dbId); - safeClose(client1); - safeClose(client2); - } - } - - @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - client = clientBuilder.build(); - database = createDatabase(client, databaseId); - } - - @AfterClass(groups = { "emulator" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeDeleteDatabase(client, databaseId); - safeClose(client); - } - - private static String getDatabaseLink(Database db, boolean isNameLink) { - return isNameLink ? "dbs/" + db.getId() : db.getSelfLink(); - } - - private static String getCollectionLink(Database db, DocumentCollection documentCollection, boolean isNameLink) { - return isNameLink ? "dbs/" + db.getId() + "/colls/" + documentCollection.getId() : documentCollection.getSelfLink(); - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmosdb.rx; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; + +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; +import com.microsoft.azure.cosmosdb.RetryAnalyzer; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerResponse; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemResponse; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; +import com.microsoft.azure.cosmosdb.CompositePath; +import com.microsoft.azure.cosmosdb.CompositePathSortOrder; +import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.IndexingMode; +import com.microsoft.azure.cosmosdb.IndexingPolicy; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.SpatialSpec; +import com.microsoft.azure.cosmosdb.SpatialType; + +import reactor.core.publisher.Mono; + +public class CollectionCrudTest extends TestSuiteBase { + private static final int TIMEOUT = 50000; + private static final int SETUP_TIMEOUT = 20000; + private static final int SHUTDOWN_TIMEOUT = 20000; + private final String databaseId = CosmosDatabaseForTest.generateId(); + + private CosmosClient client; + private CosmosDatabase database; + + @Factory(dataProvider = "clientBuildersWithDirect") + public CollectionCrudTest(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; + this.subscriberValidationTimeout = TIMEOUT; + } + + @DataProvider(name = "collectionCrudArgProvider") + public Object[][] collectionCrudArgProvider() { + return new Object[][] { + // collection name, is name base + {UUID.randomUUID().toString()} , + + // with special characters in the name. + {"+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~"} , + }; + } + + private CosmosContainerSettings getCollectionDefinition(String collectionName) { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings( + collectionName, + partitionKeyDef); + + return collectionDefinition; + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") + public void createCollection(String collectionName) throws InterruptedException { + CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + + Mono createObservable = database + .createContainer(collectionDefinition); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(collectionDefinition.getId()).build(); + + validateSuccess(createObservable, validator); + safeDeleteAllCollections(database); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT) + public void createCollectionWithCompositeIndexAndSpatialSpec() throws InterruptedException { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + + CosmosContainerSettings collection = new CosmosContainerSettings( + UUID.randomUUID().toString(), + partitionKeyDef); + + IndexingPolicy indexingPolicy = new IndexingPolicy(); + CompositePath compositePath1 = new CompositePath(); + compositePath1.setPath("/path1"); + compositePath1.setOrder(CompositePathSortOrder.Ascending); + CompositePath compositePath2 = new CompositePath(); + compositePath2.setPath("/path2"); + compositePath2.setOrder(CompositePathSortOrder.Descending); + CompositePath compositePath3 = new CompositePath(); + compositePath3.setPath("/path3"); + CompositePath compositePath4 = new CompositePath(); + compositePath4.setPath("/path4"); + compositePath4.setOrder(CompositePathSortOrder.Ascending); + CompositePath compositePath5 = new CompositePath(); + compositePath5.setPath("/path5"); + compositePath5.setOrder(CompositePathSortOrder.Descending); + CompositePath compositePath6 = new CompositePath(); + compositePath6.setPath("/path6"); + + ArrayList compositeIndex1 = new ArrayList(); + compositeIndex1.add(compositePath1); + compositeIndex1.add(compositePath2); + compositeIndex1.add(compositePath3); + + ArrayList compositeIndex2 = new ArrayList(); + compositeIndex2.add(compositePath4); + compositeIndex2.add(compositePath5); + compositeIndex2.add(compositePath6); + + Collection> compositeIndexes = new ArrayList>(); + compositeIndexes.add(compositeIndex1); + compositeIndexes.add(compositeIndex2); + indexingPolicy.setCompositeIndexes(compositeIndexes); + + SpatialType[] spatialTypes = new SpatialType[] { + SpatialType.Point, + SpatialType.LineString, + SpatialType.Polygon, + SpatialType.MultiPolygon + }; + Collection spatialIndexes = new ArrayList(); + for (int index = 0; index < 2; index++) { + Collection collectionOfSpatialTypes = new ArrayList(); + + SpatialSpec spec = new SpatialSpec(); + spec.setPath("/path" + index + "/*"); + + for (int i = index; i < index + 3; i++) { + collectionOfSpatialTypes.add(spatialTypes[i]); + } + spec.setSpatialTypes(collectionOfSpatialTypes); + spatialIndexes.add(spec); + } + + indexingPolicy.setSpatialIndexes(spatialIndexes); + + collection.setIndexingPolicy(indexingPolicy); + + Mono createObservable = database + .createContainer(collection, new CosmosContainerRequestOptions()); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(collection.getId()) + .withCompositeIndexes(compositeIndexes) + .withSpatialIndexes(spatialIndexes) + .build(); + + validateSuccess(createObservable, validator); + safeDeleteAllCollections(database); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") + public void readCollection(String collectionName) throws InterruptedException { + CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + + Mono createObservable = database.createContainer(collectionDefinition); + CosmosContainer collection = createObservable.block().getContainer(); + + Mono readObservable = collection.read(); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(collection.getId()).build(); + validateSuccess(readObservable, validator); + safeDeleteAllCollections(database); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") + public void readCollection_DoesntExist(String collectionName) throws Exception { + + Mono readObservable = database + .getContainer("I don't exist").read(); + + FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(readObservable, validator); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") + public void deleteCollection(String collectionName) throws InterruptedException { + CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + + Mono createObservable = database.createContainer(collectionDefinition); + CosmosContainer collection = createObservable.block().getContainer(); + + Mono deleteObservable = collection.delete(); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteObservable, validator); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") + public void replaceCollection(String collectionName) throws InterruptedException { + // create a collection + CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + Mono createObservable = database.createContainer(collectionDefinition); + CosmosContainer collection = createObservable.block().getContainer(); + CosmosContainerSettings collectionSettings = collection.read().block().getCosmosContainerSettings(); + // sanity check + assertThat(collectionSettings.getIndexingPolicy().getIndexingMode()).isEqualTo(IndexingMode.Consistent); + + // replace indexing mode + IndexingPolicy indexingMode = new IndexingPolicy(); + indexingMode.setIndexingMode(IndexingMode.Lazy); + collectionSettings.setIndexingPolicy(indexingMode); + Mono readObservable = collection.replace(collectionSettings, new CosmosContainerRequestOptions()); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .indexingMode(IndexingMode.Lazy).build(); + validateSuccess(readObservable, validator); + safeDeleteAllCollections(database); + } + + @Test(groups = { "emulator" }, timeOut = 10 * TIMEOUT, retryAnalyzer = RetryAnalyzer.class) + public void sessionTokenConsistencyCollectionDeleteCreateSameName() { + CosmosClient client1 = clientBuilder.build(); + CosmosClient client2 = clientBuilder.build(); + + String dbId = CosmosDatabaseForTest.generateId(); + String collectionId = "coll"; + CosmosDatabase db = null; + try { + Database databaseDefinition = new Database(); + databaseDefinition.setId(dbId); + db = createDatabase(client1, dbId); + + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(collectionId, partitionKeyDef); + CosmosContainer collection = createCollection(db, collectionDefinition, new CosmosContainerRequestOptions()); + + CosmosItemSettings document = new CosmosItemSettings(); + document.setId("doc"); + document.set("name", "New Document"); + document.set("mypk", "mypkValue"); + CosmosItem item = createDocument(collection, document); + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(new PartitionKey("mypkValue")); + CosmosItemResponse readDocumentResponse = item.read(options).block(); + logger.info("Client 1 Read Document Client Side Request Statistics {}", readDocumentResponse.getRequestDiagnosticsString()); + logger.info("Client 1 Read Document Latency {}", readDocumentResponse.getRequestLatency()); + + document.set("name", "New Updated Document"); + CosmosItemResponse upsertDocumentResponse = collection.upsertItem(document).block(); + logger.info("Client 1 Upsert Document Client Side Request Statistics {}", upsertDocumentResponse.getRequestDiagnosticsString()); + logger.info("Client 1 Upsert Document Latency {}", upsertDocumentResponse.getRequestLatency()); + + // Delete the existing collection + deleteCollection(client2, dbId, collectionId); + // Recreate the collection with the same name but with different client + CosmosContainer collection2 = createCollection(client2, dbId, collectionDefinition); + + CosmosItemSettings newDocument = new CosmosItemSettings(); + newDocument.setId("doc"); + newDocument.set("name", "New Created Document"); + newDocument.set("mypk", "mypk"); + createDocument(collection2, newDocument); + + readDocumentResponse = client1.getDatabase(dbId).getContainer(collectionId).getItem(newDocument.getId(), newDocument.get("mypk")).read().block(); + logger.info("Client 2 Read Document Client Side Request Statistics {}", readDocumentResponse.getRequestDiagnosticsString()); + logger.info("Client 2 Read Document Latency {}", readDocumentResponse.getRequestLatency()); + + CosmosItemSettings readDocument = readDocumentResponse.getCosmosItemSettings(); + + assertThat(readDocument.getId().equals(newDocument.getId())).isTrue(); + assertThat(readDocument.get("name").equals(newDocument.get("name"))).isTrue(); + } finally { + safeDeleteDatabase(db); + safeClose(client1); + safeClose(client2); + } + } + + @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) + public void beforeClass() { + client = clientBuilder.build(); + database = createDatabase(client, databaseId); + } + + @AfterClass(groups = { "emulator" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeDeleteDatabase(database); + safeClose(client); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionQueryTest.java index 0a4500c9d6a78..dff6d520b0dcf 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionQueryTest.java @@ -29,33 +29,33 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DatabaseForTest; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import rx.Observable; +import reactor.core.publisher.Flux; public class CollectionQueryTest extends TestSuiteBase { private final static int TIMEOUT = 30000; - private final String databaseId = DatabaseForTest.generateId(); - private List createdCollections = new ArrayList<>(); - private AsyncDocumentClient client; + private final String databaseId = CosmosDatabaseForTest.generateId(); + private List createdCollections = new ArrayList<>(); + private CosmosClient client; + private CosmosDatabase createdDatabase; - private String getDatabaseLink() { - return Utils.getDatabaseNameLink(databaseId); - } - - @Factory(dataProvider = "clientBuilders") - public CollectionQueryTest(Builder clientBuilder) { + @Factory(dataProvider = "clientBuilders") + public CollectionQueryTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; this.subscriberValidationTimeout = TIMEOUT; } @@ -68,20 +68,20 @@ public void queryCollectionsWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - Observable> queryObservable = client.queryCollections(getDatabaseLink(), query, options); + Flux> queryObservable = createdDatabase.queryContainers(query, options); - List expectedCollections = createdCollections.stream() + List expectedCollections = createdCollections.stream() .filter(c -> StringUtils.equals(filterCollectionId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedCollections).isNotEmpty(); int expectedPageSize = (expectedCollections.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedCollections.size()) - .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.read().block().getCosmosContainerSettings().getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -95,20 +95,19 @@ public void queryAllCollections() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - String databaseLink = Utils.getDatabaseNameLink(databaseId); - Observable> queryObservable = client.queryCollections(databaseLink, query, options); + Flux> queryObservable = createdDatabase.queryContainers(query, options); - List expectedCollections = createdCollections; + List expectedCollections = createdCollections; assertThat(expectedCollections).isNotEmpty(); int expectedPageSize = (expectedCollections.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedCollections.size()) - .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.read().block().getCosmosContainerSettings().getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -121,12 +120,12 @@ public void queryCollections_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client.queryCollections(getDatabaseLink(), query, options); + Flux> queryObservable = createdDatabase.queryContainers(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -135,16 +134,20 @@ public void queryCollections_NoResults() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - createDatabase(client, databaseId); + createdDatabase = createDatabase(client, databaseId); + + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); - DocumentCollection collection = new DocumentCollection(); - collection.setId(UUID.randomUUID().toString()); + CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); createdCollections.add(createCollection(client, databaseId, collection)); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteDatabase(client, databaseId); + safeDeleteDatabase(createdDatabase); safeClose(client); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseCrudTest.java index 3df99491e5b24..01f4b02193868 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseCrudTest.java @@ -22,61 +22,59 @@ */ package com.microsoft.azure.cosmosdb.rx; -import com.microsoft.azure.cosmosdb.DatabaseForTest; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseRequestOptions; +import com.microsoft.azure.cosmos.CosmosDatabaseResponse; +import com.microsoft.azure.cosmos.CosmosDatabaseSettings; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import rx.Observable; - -import javax.net.ssl.SSLException; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.List; public class DatabaseCrudTest extends TestSuiteBase { - private final String preExistingDatabaseId = DatabaseForTest.generateId(); + private final String preExistingDatabaseId = CosmosDatabaseForTest.generateId(); private final List databases = new ArrayList<>(); - private AsyncDocumentClient client; + private CosmosClient client; + private CosmosDatabase createdDatabase; @Factory(dataProvider = "clientBuilders") - public DatabaseCrudTest(Builder clientBuilder) { + public DatabaseCrudTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void createDatabase() throws Exception { - Database databaseDefinition = new Database(); - databaseDefinition.setId(DatabaseForTest.generateId()); + CosmosDatabaseSettings databaseDefinition = new CosmosDatabaseSettings(CosmosDatabaseForTest.generateId()); databases.add(databaseDefinition.getId()); // create the database - Observable> createObservable = client.createDatabase(databaseDefinition, null); + Mono createObservable = client.createDatabase(databaseDefinition, new CosmosDatabaseRequestOptions()); // validate - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(databaseDefinition.getId()).build(); validateSuccess(createObservable, validator); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void createDatabase_AlreadyExists() throws Exception { - Database databaseDefinition = new Database(); - databaseDefinition.setId(DatabaseForTest.generateId()); + CosmosDatabaseSettings databaseDefinition = new CosmosDatabaseSettings(CosmosDatabaseForTest.generateId()); databases.add(databaseDefinition.getId()); - client.createDatabase(databaseDefinition, null).toBlocking().single(); + client.createDatabase(databaseDefinition, new CosmosDatabaseRequestOptions()).block(); // attempt to create the database - Observable> createObservable = client.createDatabase(databaseDefinition, null); + Mono createObservable = client.createDatabase(databaseDefinition, new CosmosDatabaseRequestOptions()); // validate FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); @@ -86,11 +84,10 @@ public void createDatabase_AlreadyExists() throws Exception { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void readDatabase() throws Exception { // read database - Observable> readObservable = client - .readDatabase(Utils.getDatabaseNameLink(preExistingDatabaseId), null); + Mono readObservable = client.getDatabase(preExistingDatabaseId).read(); // validate - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(preExistingDatabaseId).build(); validateSuccess(readObservable, validator); } @@ -98,8 +95,7 @@ public void readDatabase() throws Exception { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void readDatabase_DoesntExist() throws Exception { // read database - Observable> readObservable = client - .readDatabase(Utils.getDatabaseNameLink("I don't exist"), null); + Mono readObservable = client.getDatabase("I don't exist").read(); // validate FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); @@ -110,17 +106,15 @@ public void readDatabase_DoesntExist() throws Exception { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void deleteDatabase() throws Exception { // create the database - Database databaseDefinition = new Database(); - databaseDefinition.setId(DatabaseForTest.generateId()); + CosmosDatabaseSettings databaseDefinition = new CosmosDatabaseSettings(CosmosDatabaseForTest.generateId()); databases.add(databaseDefinition.getId()); - client.createDatabase(databaseDefinition, null).toCompletable().await(); + CosmosDatabase database = client.createDatabase(databaseDefinition, new CosmosDatabaseRequestOptions()).block().getDatabase(); // delete the database - Observable> deleteObservable = client - .deleteDatabase(Utils.getDatabaseNameLink(databaseDefinition.getId()), null); + Mono deleteObservable = database.delete(); // validate - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .nullResource().build(); validateSuccess(deleteObservable, validator); } @@ -128,8 +122,7 @@ public void deleteDatabase() throws Exception { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void deleteDatabase_DoesntExist() throws Exception { // delete the database - Observable> deleteObservable = client - .deleteDatabase(Utils.getDatabaseNameLink("I don't exist"), null); + Mono deleteObservable = client.getDatabase("I don't exist").delete(); // validate FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); @@ -139,14 +132,14 @@ public void deleteDatabase_DoesntExist() throws Exception { @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - createDatabase(client, preExistingDatabaseId); + createdDatabase = createDatabase(client, preExistingDatabaseId); } @AfterClass(groups = { "emulator" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteDatabase(client, preExistingDatabaseId); + safeDeleteDatabase(createdDatabase); for(String dbId: databases) { - safeDeleteDatabase(client, dbId); + safeDeleteDatabase(client.getDatabase(dbId)); } safeClose(client); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseQueryTest.java index 832e8fe62ea83..6a399ba68206d 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseQueryTest.java @@ -28,31 +28,33 @@ import java.util.List; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DatabaseForTest; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseSettings; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; -import rx.Observable; +import reactor.core.publisher.Flux; public class DatabaseQueryTest extends TestSuiteBase { - public final String databaseId1 = DatabaseForTest.generateId(); - public final String databaseId2 = DatabaseForTest.generateId(); + public final String databaseId1 = CosmosDatabaseForTest.generateId(); + public final String databaseId2 = CosmosDatabaseForTest.generateId(); - private List createdDatabases = new ArrayList<>(); + private List createdDatabases = new ArrayList<>(); - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuilders") - public DatabaseQueryTest(Builder clientBuilder) { + public DatabaseQueryTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -62,20 +64,20 @@ public void queryDatabaseWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - Observable> queryObservable = client.queryDatabases(query, options); + Flux> queryObservable = client.queryDatabases(query, options); - List expectedDatabases = createdDatabases.stream() - .filter(d -> StringUtils.equals(databaseId1, d.getId()) ).collect(Collectors.toList()); + List expectedDatabases = createdDatabases.stream() + .filter(d -> StringUtils.equals(databaseId1, d.getId()) ).map(d -> d.read().block().getCosmosDatabaseSettings()).collect(Collectors.toList()); assertThat(expectedDatabases).isNotEmpty(); int expectedPageSize = (expectedDatabases.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDatabases.size()) .exactlyContainsInAnyOrder(expectedDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -91,19 +93,19 @@ public void queryAllDatabase() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - Observable> queryObservable = client.queryDatabases(query, options); + Flux> queryObservable = client.queryDatabases(query, options); - List expectedDatabases = createdDatabases; + List expectedDatabases = createdDatabases.stream().map(d -> d.read().block().getCosmosDatabaseSettings()).collect(Collectors.toList()); assertThat(expectedDatabases).isNotEmpty(); int expectedPageSize = (expectedDatabases.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDatabases.size()) .exactlyContainsInAnyOrder(expectedDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -116,12 +118,12 @@ public void queryDatabases_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client.queryDatabases(query, options); + Flux> queryObservable = client.queryDatabases(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -130,20 +132,14 @@ public void queryDatabases_NoResults() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - - Database d1 = new Database(); - d1.setId(databaseId1); - createdDatabases.add(createDatabase(client, d1)); - - Database d2 = new Database(); - d2.setId(databaseId2); - createdDatabases.add(createDatabase(client, d2)); + createdDatabases.add(createDatabase(client, databaseId1)); + createdDatabases.add(createDatabase(client, databaseId2)); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteDatabase(client, databaseId1); - safeDeleteDatabase(client, databaseId2); + safeDeleteDatabase(createdDatabases.get(0)); + safeDeleteDatabase(createdDatabases.get(1)); safeClose(client); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentClientResourceLeakTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentClientResourceLeakTest.java index e3a1df72d70a5..333f0c148500f 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentClientResourceLeakTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentClientResourceLeakTest.java @@ -22,11 +22,12 @@ */ package com.microsoft.azure.cosmosdb.rx; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -39,23 +40,24 @@ import static org.assertj.core.api.Assertions.assertThat; public class DocumentClientResourceLeakTest extends TestSuiteBase { - private static final int TIMEOUT = 240000; + private static final int TIMEOUT = 2400000; private static final int MAX_NUMBER = 1000; - private Builder clientBuilder; - private AsyncDocumentClient client; + private CosmosClientBuilder clientBuilder; + private CosmosClient client; - private Database createdDatabase; - private DocumentCollection createdCollection; + private CosmosDatabase createdDatabase; + private CosmosContainer createdCollection; @Factory(dataProvider = "simpleClientBuildersWithDirect") - public DocumentClientResourceLeakTest(Builder clientBuilder) { + public DocumentClientResourceLeakTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } + //TODO : FIX tests @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void resourceLeak() throws Exception { //TODO FIXME DANOBLE this test doesn't pass on RNTBD - if (clientBuilder.configs.getProtocol() == Protocol.Tcp) { + if (clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { throw new SkipException("RNTBD"); } System.gc(); @@ -64,11 +66,11 @@ public void resourceLeak() throws Exception { for (int i = 0; i < MAX_NUMBER; i++) { - logger.info("client {}", i); client = clientBuilder.build(); + logger.info("client {}", i); try { logger.info("creating doc..."); - createDocument(client, createdDatabase.getId(), createdCollection.getId(), getDocumentDefinition()); + createDocument(client.getDatabase(createdDatabase.getId()).getContainer(createdCollection.getId()), getDocumentDefinition()); } finally { logger.info("closing client..."); client.close(); @@ -83,13 +85,14 @@ public void resourceLeak() throws Exception { @BeforeClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; + client = clientBuilder.build(); + createdDatabase = getSharedCosmosDatabase(client); + createdCollection = getSharedMultiPartitionCosmosContainer(client); } - private Document getDocumentDefinition() { + private CosmosItemSettings getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " + CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java index 6c995e8682e53..7ac50af7f425b 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java @@ -1,435 +1,395 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx; - -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import org.apache.commons.lang3.StringUtils; -import org.testng.SkipException; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; -import rx.Observable; - -import java.time.OffsetDateTime; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import static org.apache.commons.io.FileUtils.ONE_MB; -import static org.assertj.core.api.Assertions.assertThat; - -public class DocumentCrudTest extends TestSuiteBase { - - private Database createdDatabase; - private DocumentCollection createdCollection; - - private AsyncDocumentClient client; - - @Factory(dataProvider = "clientBuildersWithDirect") - public DocumentCrudTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; - } - - @DataProvider(name = "documentCrudArgProvider") - public Object[][] documentCrudArgProvider() { - return new Object[][] { - // collection name, is name base - {UUID.randomUUID().toString(), false } , - {UUID.randomUUID().toString(), true } , - - // with special characters in the name. - {"+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~", true } , - }; - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void createDocument(String documentId, boolean isNameBased) { - Document docDefinition = getDocumentDefinition(documentId); - - Observable> createObservable = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); - - validateSuccess(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void createLargeDocument(String documentId, boolean isNameBased) { - Document docDefinition = getDocumentDefinition(documentId); - - //Keep size as ~ 1.5MB to account for size of other props - int size = (int) (ONE_MB * 1.5); - docDefinition.set("largeString", StringUtils.repeat("x", size)); - - Observable> createObservable = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); - - validateSuccess(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void createDocumentWithVeryLargePartitionKey(String documentId, boolean isNameBased) { - Document docDefinition = getDocumentDefinition(documentId); - StringBuilder sb = new StringBuilder(); - for(int i = 0; i < 100; i++) { - sb.append(i).append("x"); - } - docDefinition.set("mypk", sb.toString()); - - Observable> createObservable = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(docDefinition.getId()) - .withProperty("mypk", sb.toString()) - .build(); - validateSuccess(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void readDocumentWithVeryLargePartitionKey(String documentId, boolean isNameBased) { - Document docDefinition = getDocumentDefinition(documentId); - StringBuilder sb = new StringBuilder(); - for(int i = 0; i < 100; i++) { - sb.append(i).append("x"); - } - docDefinition.set("mypk", sb.toString()); - - Document createdDocument = TestSuiteBase.createDocument(client, createdDatabase.getId(), createdCollection.getId(), docDefinition); - - waitIfNeededForReplicasToCatchUp(clientBuilder); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(sb.toString())); - Observable> readObservable = client.readDocument(getDocumentLink(createdDocument, isNameBased), options); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(docDefinition.getId()) - .withProperty("mypk", sb.toString()) - .build(); - validateSuccess(readObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void createDocument_AlreadyExists(String documentId, boolean isNameBased) { - Document docDefinition = getDocumentDefinition(documentId); - - client.createDocument(getCollectionLink(isNameBased), docDefinition, null, false).toBlocking().single().getResource(); - - Observable> createObservable = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false); - - FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); - validateFailure(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void createDocumentTimeout(String documentId, boolean isNameBased) { - Document docDefinition = getDocumentDefinition(documentId); - - Observable> createObservable = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false) - .timeout(1, TimeUnit.MILLISECONDS); - - FailureValidator validator = new FailureValidator.Builder().instanceOf(TimeoutException.class).build(); - - validateFailure(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void readDocument(String documentId, boolean isNameBased) { - Document docDefinition = getDocumentDefinition(documentId); - - Document document = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false).toBlocking().single().getResource(); - - waitIfNeededForReplicasToCatchUp(clientBuilder); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(document.get("mypk"))); - Observable> readObservable = client.readDocument(getDocumentLink(document, isNameBased), options); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(document.getId()) - .build(); - validateSuccess(readObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void timestamp(String documentId, boolean isNameBased) throws Exception { - OffsetDateTime before = OffsetDateTime.now(); - Document docDefinition = getDocumentDefinition(documentId); - Thread.sleep(1000); - Document document = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false).toBlocking().single().getResource(); - - waitIfNeededForReplicasToCatchUp(clientBuilder); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(document.get("mypk"))); - Observable> readObservable = client.readDocument(getDocumentLink(document, isNameBased), options); - Document readDocument = readObservable.toBlocking().single().getResource(); - Thread.sleep(1000); - OffsetDateTime after = OffsetDateTime.now(); - - assertThat(readDocument.getTimestamp()).isAfterOrEqualTo(before); - assertThat(readDocument.getTimestamp()).isBeforeOrEqualTo(after); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void readDocument_DoesntExist(String documentId, boolean isNameBased) { - Document docDefinition = getDocumentDefinition(documentId); - - Document document = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false).toBlocking().single().getResource(); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(document.get("mypk"))); - client.deleteDocument(getDocumentLink(document, isNameBased), options).toBlocking().first(); - - waitIfNeededForReplicasToCatchUp(clientBuilder); - - options.setPartitionKey(new PartitionKey("looloo")); - Observable> readObservable = client.readDocument(getDocumentLink(document, isNameBased), options); - - FailureValidator validator = new FailureValidator.Builder().instanceOf(DocumentClientException.class) - .statusCode(404).build(); - validateFailure(readObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void deleteDocument(String documentId, boolean isNameBased) { - Document docDefinition = getDocumentDefinition(documentId); - - Document document = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false).toBlocking().single().getResource(); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(document.get("mypk"))); - Observable> deleteObservable = client.deleteDocument(getDocumentLink(document, isNameBased), options); - - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .nullResource().build(); - validateSuccess(deleteObservable, validator); - - // attempt to read document which was deleted - waitIfNeededForReplicasToCatchUp(clientBuilder); - - Observable> readObservable = client.readDocument(getDocumentLink(document, isNameBased), options); - FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(readObservable, notFoundValidator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void deleteDocument_undefinedPK(String documentId, boolean isNameBased) { - Document docDefinition = new Document(); - docDefinition.setId(documentId); - - Document document = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false).toBlocking().single().getResource(); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(Undefined.Value())); - Observable> deleteObservable = client.deleteDocument(getDocumentLink(document, isNameBased), options); - - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .nullResource().build(); - validateSuccess(deleteObservable, validator); - - // attempt to read document which was deleted - waitIfNeededForReplicasToCatchUp(clientBuilder); - - Observable> readObservable = client.readDocument(getDocumentLink(document, isNameBased), options); - FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(readObservable, notFoundValidator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void deleteDocument_DoesntExist(String documentId, boolean isNameBased) { - Document docDefinition = getDocumentDefinition(documentId); - - Document document = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false).toBlocking().single().getResource(); - - RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(document.get("mypk"))); - client.deleteDocument(getDocumentLink(document, isNameBased), options).toBlocking().single(); - - // delete again - Observable> deleteObservable = client.deleteDocument(getDocumentLink(document, isNameBased), options); - - FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(deleteObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void replaceDocument(String documentId, boolean isNameBased) { - // create a document - Document docDefinition = getDocumentDefinition(documentId); - - Document document = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false).toBlocking().single().getResource(); - - String newPropValue = UUID.randomUUID().toString(); - document.set("newProp", newPropValue); - - // replace document - Observable> readObservable = client.replaceDocument(document, null); - - // validate - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withProperty("newProp", newPropValue).build(); - validateSuccess(readObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void replaceDocument_UsingDocumentLink(String documentId, boolean isNameBased) { - // create a document - Document docDefinition = getDocumentDefinition(documentId); - - Document document = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false).toBlocking().single().getResource(); - - String newPropValue = UUID.randomUUID().toString(); - document.set("newProp", newPropValue); - - // replace document - Observable> readObservable = client.replaceDocument(getDocumentLink(document, isNameBased), document, null); - - // validate - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withProperty("newProp", newPropValue).build(); - validateSuccess(readObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void upsertDocument_CreateDocument(String documentId, boolean isNameBased) { - // create a document - Document docDefinition = getDocumentDefinition(documentId); - - - // replace document - Observable> upsertObservable = client.upsertDocument(getCollectionLink(isNameBased), - docDefinition, null, false); - - // validate - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(docDefinition.getId()).build(); - try { - validateSuccess(upsertObservable, validator); - } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void upsertDocument_ReplaceDocument(String documentId, boolean isNameBased) { - // create a document - Document docDefinition = getDocumentDefinition(documentId); - - Document document = client - .createDocument(getCollectionLink(isNameBased), docDefinition, null, false).toBlocking().single().getResource(); - - String newPropValue = UUID.randomUUID().toString(); - document.set("newProp", newPropValue); - - // replace document - Observable> readObservable = client.upsertDocument - (getCollectionLink(isNameBased), document, null, true); - - // validate - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withProperty("newProp", newPropValue).build(); - try { - validateSuccess(readObservable, validator); - } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } - } - - @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; - } - - @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeClose(client); - } - - @BeforeMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) - public void beforeMethod() { - safeClose(client); - client = clientBuilder.build(); - } - - private String getCollectionLink(boolean isNameBased) { - return isNameBased ? "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId() : createdCollection.getSelfLink(); - } - - private String getDocumentLink(Document doc, boolean isNameBased) { - return isNameBased ? "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId() + "/docs/" + doc.getId() : - "dbs/" + createdDatabase.getResourceId() + "/colls/" + createdCollection.getResourceId() + "/docs/" + doc.getResourceId(); - } - - private Document getDocumentDefinition(String documentId) { - String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " - + "\"id\": \"%s\", " - + "\"mypk\": \"%s\", " - + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" - + "}" - , documentId, uuid)); - return doc; - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmosdb.rx; + +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemResponse; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; + +import reactor.core.publisher.Mono; + +import org.apache.commons.lang3.StringUtils; +import org.testng.SkipException; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.util.concurrent.TimeoutException; + +import static org.apache.commons.io.FileUtils.ONE_MB; +import static org.assertj.core.api.Assertions.assertThat; + +public class DocumentCrudTest extends TestSuiteBase { + + private CosmosContainer createdCollection; + + private CosmosClient client; + + @Factory(dataProvider = "clientBuildersWithDirect") + public DocumentCrudTest(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; + } + + @DataProvider(name = "documentCrudArgProvider") + public Object[][] documentCrudArgProvider() { + return new Object[][] { + // collection name, is name base + {UUID.randomUUID().toString()} , + + // with special characters in the name. + {"+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~"} , + }; + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void createDocument(String documentId) throws InterruptedException { + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(docDefinition.getId()) + .build(); + + validateSuccess(createObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void createLargeDocument(String documentId) throws InterruptedException { + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + //Keep size as ~ 1.5MB to account for size of other props + int size = (int) (ONE_MB * 1.5); + docDefinition.set("largeString", StringUtils.repeat("x", size)); + + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(docDefinition.getId()) + .build(); + + validateSuccess(createObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void createDocumentWithVeryLargePartitionKey(String documentId) throws InterruptedException { + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + StringBuilder sb = new StringBuilder(); + for(int i = 0; i < 100; i++) { + sb.append(i).append("x"); + } + docDefinition.set("mypk", sb.toString()); + + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(docDefinition.getId()) + .withProperty("mypk", sb.toString()) + .build(); + validateSuccess(createObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void readDocumentWithVeryLargePartitionKey(String documentId) throws InterruptedException { + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + StringBuilder sb = new StringBuilder(); + for(int i = 0; i < 100; i++) { + sb.append(i).append("x"); + } + docDefinition.set("mypk", sb.toString()); + + CosmosItem createdDocument = TestSuiteBase.createDocument(createdCollection, docDefinition); + + waitIfNeededForReplicasToCatchUp(clientBuilder); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(new PartitionKey(sb.toString())); + Mono readObservable = createdDocument.read(options); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(docDefinition.getId()) + .withProperty("mypk", sb.toString()) + .build(); + validateSuccess(readObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void createDocument_AlreadyExists(String documentId) throws InterruptedException { + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block(); + + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + + FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); + validateFailure(createObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void createDocumentTimeout(String documentId) throws InterruptedException { + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()) + .timeout(Duration.ofMillis(1)); + + FailureValidator validator = new FailureValidator.Builder().instanceOf(TimeoutException.class).build(); + + validateFailure(createObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void readDocument(String documentId) throws InterruptedException { + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); + waitIfNeededForReplicasToCatchUp(clientBuilder); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); + Mono readObservable = document.read(options); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(document.getId()) + .build(); + validateSuccess(readObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void timestamp(String documentId, boolean isNameBased) throws Exception { + OffsetDateTime before = OffsetDateTime.now(); + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + Thread.sleep(1000); + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); + + waitIfNeededForReplicasToCatchUp(clientBuilder); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); + CosmosItemSettings readDocument = document.read(options).block().getCosmosItemSettings(); + Thread.sleep(1000); + OffsetDateTime after = OffsetDateTime.now(); + + assertThat(readDocument.getTimestamp()).isAfterOrEqualTo(before); + assertThat(readDocument.getTimestamp()).isBeforeOrEqualTo(after); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void readDocument_DoesntExist(String documentId) throws InterruptedException { + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); + document.delete(options).block(); + + waitIfNeededForReplicasToCatchUp(clientBuilder); + + options.setPartitionKey(new PartitionKey("looloo")); + Mono readObservable = document.read(options); + + FailureValidator validator = new FailureValidator.Builder().instanceOf(DocumentClientException.class) + .statusCode(404).build(); + validateFailure(readObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void deleteDocument(String documentId) throws InterruptedException { + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); + Mono deleteObservable = document.delete(options); + + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteObservable, validator); + + // attempt to read document which was deleted + waitIfNeededForReplicasToCatchUp(clientBuilder); + + Mono readObservable = document.read(options); + FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(readObservable, notFoundValidator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void deleteDocument_undefinedPK(String documentId) throws InterruptedException { + Document docDefinition = new Document(); + docDefinition.setId(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(PartitionKey.None); + Mono deleteObservable = document.delete(options); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteObservable, validator); + + // attempt to read document which was deleted + waitIfNeededForReplicasToCatchUp(clientBuilder); + + Mono readObservable = document.read(options); + FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(readObservable, notFoundValidator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void deleteDocument_DoesntExist(String documentId) throws InterruptedException { + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); + document.delete(options).block(); + + // delete again + Mono deleteObservable = document.delete(options); + + FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(deleteObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void replaceDocument(String documentId) throws InterruptedException { + // create a document + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); + + String newPropValue = UUID.randomUUID().toString(); + docDefinition.set("newProp", newPropValue); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); + // replace document + Mono replaceObservable = document.replace(docDefinition, options); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withProperty("newProp", newPropValue).build(); + validateSuccess(replaceObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void upsertDocument_CreateDocument(String documentId) throws Throwable { + // create a document + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + + // replace document + Mono upsertObservable = createdCollection.upsertItem(docDefinition, new CosmosItemRequestOptions()); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(docDefinition.getId()).build(); + try { + validateSuccess(upsertObservable, validator); + } catch (Throwable error) { + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + logger.info(message, error); + throw new SkipException(message, error); + } + throw error; + } + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT * 100, dataProvider = "documentCrudArgProvider") + public void upsertDocument_ReplaceDocument(String documentId) throws Throwable { + // create a document + CosmosItemSettings docDefinition = getDocumentDefinition(documentId); + + docDefinition = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItemSettings(); + + String newPropValue = UUID.randomUUID().toString(); + docDefinition.set("newProp", newPropValue); + + // replace document + Mono readObservable = createdCollection.upsertItem(docDefinition, new CosmosItemRequestOptions()); + System.out.println(docDefinition); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withProperty("newProp", newPropValue).build(); + try { + validateSuccess(readObservable, validator); + } catch (Throwable error) { + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + logger.info(message, error); + throw new SkipException(message, error); + } + throw error; + } + } + + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) + public void beforeClass() { + client = clientBuilder.build(); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + } + + @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeClose(client); + } + + @BeforeMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) + public void beforeMethod() { + safeClose(client); + client = clientBuilder.build(); + } + + private CosmosItemSettings getDocumentDefinition(String documentId) { + String uuid = UUID.randomUUID().toString(); + CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + + "\"id\": \"%s\", " + + "\"mypk\": \"%s\", " + + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + + "}" + , documentId, uuid)); + return doc; + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/LogLevelTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/LogLevelTest.java index c2ace6ab65969..8decf192dce3b 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/LogLevelTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/LogLevelTest.java @@ -35,19 +35,18 @@ import org.apache.log4j.WriterAppender; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; -import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemResponse; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.CosmosResponseValidator; -import rx.Observable; +import reactor.core.publisher.Mono; import static org.assertj.core.api.Assertions.assertThat; @@ -59,8 +58,8 @@ public class LogLevelTest extends TestSuiteBase { public final static String LOG_PATTERN_3 = "USER_EVENT: SslHandshakeCompletionEvent(SUCCESS)"; public final static String LOG_PATTERN_4 = "CONNECT: "; - private static Database createdDatabase; - private static DocumentCollection createdCollection; + private static CosmosContainer createdCollection; + private static CosmosClient client; public LogLevelTest() { this.clientBuilder = createGatewayRxDocumentClient(); @@ -68,8 +67,8 @@ public LogLevelTest() { @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; + client = clientBuilder.build(); + createdCollection = getSharedMultiPartitionCosmosContainer(client); } /** @@ -84,12 +83,11 @@ public void createDocumentWithDebugLevel() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); LogManager.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - AsyncDocumentClient client = clientBuilder.build(); + CosmosClient client = clientBuilder.build(); try { - Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client - .createDocument(getCollectionLink(), docDefinition, null, false); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosItemSettings docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.getId()) .build(); validateSuccess(createObservable, validator); @@ -114,12 +112,11 @@ public void createDocumentWithWarningLevel() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - AsyncDocumentClient client = clientBuilder.build(); + CosmosClient client = clientBuilder.build(); try { - Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client - .createDocument(getCollectionLink(), docDefinition, null, false); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosItemSettings docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.getId()) .build(); validateSuccess(createObservable, validator); @@ -143,12 +140,11 @@ public void createDocumentWithTraceLevel() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - AsyncDocumentClient client = clientBuilder.build(); + CosmosClient client = clientBuilder.build(); try { - Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client - .createDocument(getCollectionLink(), docDefinition, null, false); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosItemSettings docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.getId()) .build(); validateSuccess(createObservable, validator); @@ -171,12 +167,11 @@ public void createDocumentWithTraceLevelAtRoot() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - AsyncDocumentClient client = clientBuilder.build(); + CosmosClient client = clientBuilder.build(); try { - Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client - .createDocument(getCollectionLink(), docDefinition, null, false); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosItemSettings docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.getId()) .build(); validateSuccess(createObservable, validator); @@ -198,12 +193,11 @@ public void createDocumentWithDebugLevelAtRoot() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - AsyncDocumentClient client = clientBuilder.build(); + CosmosClient client = clientBuilder.build(); try { - Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client - .createDocument(getCollectionLink(), docDefinition, null, false); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosItemSettings docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.getId()) .build(); validateSuccess(createObservable, validator); @@ -227,12 +221,11 @@ public void createDocumentWithErrorClient() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - AsyncDocumentClient client = clientBuilder.build(); + CosmosClient client = clientBuilder.build(); try { - Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client - .createDocument(getCollectionLink(), docDefinition, null, false); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosItemSettings docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.getId()) .build(); validateSuccess(createObservable, validator); @@ -256,12 +249,11 @@ public void createDocumentWithInfoLevel() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - AsyncDocumentClient client = clientBuilder.build(); + CosmosClient client = clientBuilder.build(); try { - Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client - .createDocument(getCollectionLink(), docDefinition, null, false); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosItemSettings docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.getId()) .build(); validateSuccess(createObservable, validator); @@ -272,9 +264,9 @@ public void createDocumentWithInfoLevel() throws Exception { } } - private Document getDocumentDefinition() { + private CosmosItemSettings getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " + CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" @@ -301,8 +293,4 @@ public void afterClass() { LogManager.resetConfiguration(); PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties")); } - - private String getCollectionLink() { - return createdCollection.getSelfLink(); - } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiMasterConflictResolutionTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiMasterConflictResolutionTest.java index 05ce9cee9b9fb..a9f73ec834136 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiMasterConflictResolutionTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiMasterConflictResolutionTest.java @@ -1,214 +1,215 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx; - -import com.microsoft.azure.cosmosdb.BridgeUtils; -import com.microsoft.azure.cosmosdb.ConflictResolutionMode; -import com.microsoft.azure.cosmosdb.ConflictResolutionPolicy; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; -import rx.Observable; - -import javax.net.ssl.SSLException; -import java.util.UUID; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - -// assumes multi master is enabled in endpoint -public class MultiMasterConflictResolutionTest extends TestSuiteBase { - private static final int TIMEOUT = 40000; - - private final String databaseId = DatabaseForTest.generateId(); - - private AsyncDocumentClient client; - private Database database; - - @Factory(dataProvider = "clientBuilders") - public MultiMasterConflictResolutionTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; - } - - @Test(groups = "multi-master", timeOut = TIMEOUT) - public void conflictResolutionPolicyCRUD() { - - // default last writer wins, path _ts - DocumentCollection collection = new DocumentCollection(); - collection.setId(UUID.randomUUID().toString()); - collection = getResource(client.createCollection(getDatabaseLink(database), collection, null)); - - assertThat(collection.getConflictResolutionPolicy().getConflictResolutionMode()).isEqualTo(ConflictResolutionMode.LastWriterWins); - - // LWW without path specified, should default to _ts - collection.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy()); - collection = getResource(client.replaceCollection(collection, null)); - - - assertThat(collection.getConflictResolutionPolicy().getConflictResolutionMode()).isEqualTo(ConflictResolutionMode.LastWriterWins); - assertThat(collection.getConflictResolutionPolicy().getConflictResolutionPath()).isEqualTo("/_ts"); - - // Tests the following scenarios - // 1. LWW with valid path - // 2. LWW with null path, should default to _ts - // 3. LWW with empty path, should default to _ts - testConflictResolutionPolicyRequiringPath(ConflictResolutionMode.LastWriterWins, - new String[] { "/a", null, "" }, new String[] { "/a", "/_ts", "/_ts" }); - - // LWW invalid path - collection.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy("/a/b")); - - try { - collection = getResource(client.replaceCollection(collection, null)); - fail("Expected exception on invalid path."); - } catch (Exception e) { - - // when (e.StatusCode == HttpStatusCode.BadRequest) - DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e.getCause(), DocumentClientException.class); - if (dce != null && dce.getStatusCode() == 400) { - assertThat(dce.getMessage()).contains("Invalid path '\\/a\\/b' for last writer wins conflict resolution"); - } else { - throw e; - } - } - - // LWW invalid path - - collection.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy("someText")); - - try { - collection = getResource(client.replaceCollection(collection, null)); - fail("Expected exception on invalid path."); - } catch (Exception e) { - // when (e.StatusCode == HttpStatusCode.BadRequest) - DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e.getCause(), DocumentClientException.class); - if (dce != null && dce.getStatusCode() == 400) { - assertThat(dce.getMessage()).contains("Invalid path 'someText' for last writer wins conflict resolution"); - } else { - throw e; - } - } - - // Tests the following scenarios - // 1. Custom with valid sprocLink - // 2. Custom with null sprocLink, should default to empty string - // 3. Custom with empty sprocLink, should default to empty string - testConflictResolutionPolicyRequiringPath(ConflictResolutionMode.Custom, - new String[] { "randomSprocName", null, "" }, new String[] { "randomSprocName", "", "" }); - } - - private void testConflictResolutionPolicyRequiringPath(ConflictResolutionMode conflictResolutionMode, - String[] paths, String[] expectedPaths) { - for (int i = 0; i < paths.length; i++) { - DocumentCollection collection = new DocumentCollection(); - collection.setId(UUID.randomUUID().toString()); - - if (conflictResolutionMode == ConflictResolutionMode.LastWriterWins) { - collection.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy(paths[i])); - } else { - collection.setConflictResolutionPolicy(ConflictResolutionPolicy.createCustomPolicy(paths[i])); - } - collection = getResource(client.createCollection("dbs/" + database.getId(), collection, null)); - assertThat(collection.getConflictResolutionPolicy().getConflictResolutionMode()).isEqualTo(conflictResolutionMode); - - if (conflictResolutionMode == ConflictResolutionMode.LastWriterWins) { - assertThat(collection.getConflictResolutionPolicy().getConflictResolutionPath()).isEqualTo(expectedPaths[i]); - } else { - assertThat(collection.getConflictResolutionPolicy().getConflictResolutionProcedure()).isEqualTo(expectedPaths[i]); - } - } - } - - @Test(groups = "multi-master", timeOut = TIMEOUT) - public void invalidConflictResolutionPolicy_LastWriterWinsWithStoredProc() throws Exception { - DocumentCollection collection = new DocumentCollection(); - collection.setId(UUID.randomUUID().toString()); - - // LWW without path specified, should default to _ts - ConflictResolutionPolicy policy = BridgeUtils.createConflictResolutionPolicy(); - BridgeUtils.setMode(policy, ConflictResolutionMode.LastWriterWins); - BridgeUtils.setStoredProc(policy,"randomSprocName"); - collection.setConflictResolutionPolicy(policy); - - Observable> createObservable = client.createCollection( - getDatabaseLink(database), - collection, - null); - - FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) - .statusCode(400) - .errorMessageContains("LastWriterWins conflict resolution mode should not have conflict resolution procedure set.") - .build(); - validateFailure(createObservable, validator); - } - - @Test(groups = "multi-master", timeOut = TIMEOUT) - public void invalidConflictResolutionPolicy_CustomWithPath() throws Exception { - DocumentCollection collection = new DocumentCollection(); - collection.setId(UUID.randomUUID().toString()); - - // LWW without path specified, should default to _ts - ConflictResolutionPolicy policy = BridgeUtils.createConflictResolutionPolicy(); - BridgeUtils.setMode(policy, ConflictResolutionMode.Custom); - BridgeUtils.setPath(policy,"/mypath"); - collection.setConflictResolutionPolicy(policy); - - Observable> createObservable = client.createCollection( - getDatabaseLink(database), - collection, - null); - - FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) - .statusCode(400) - .errorMessageContains("Custom conflict resolution mode should not have conflict resolution path set.") - .build(); - validateFailure(createObservable, validator); - } - - @BeforeClass(groups = {"multi-master"}, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - // set up the client - - client = clientBuilder.build(); - database = createDatabase(client, databaseId); - } - - private T getResource(Observable> obs) { - return obs.toBlocking().single().getResource(); - } - - @AfterClass(groups = {"multi-master"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeDeleteDatabase(client, database); - safeClose(client); - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmosdb.rx; + +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerResponse; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; +import com.microsoft.azure.cosmosdb.BridgeUtils; +import com.microsoft.azure.cosmosdb.ConflictResolutionMode; +import com.microsoft.azure.cosmosdb.ConflictResolutionPolicy; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; + +import reactor.core.publisher.Mono; + +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +// assumes multi master is enabled in endpoint +public class MultiMasterConflictResolutionTest extends TestSuiteBase { + private static final int TIMEOUT = 40000; + + private final String databaseId = CosmosDatabaseForTest.generateId(); + + private PartitionKeyDefinition partitionKeyDef; + private CosmosClient client; + private CosmosDatabase database; + + @Factory(dataProvider = "clientBuilders") + public MultiMasterConflictResolutionTest(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; + } + + @Test(groups = "multi-master", timeOut = 10 * TIMEOUT) + public void conflictResolutionPolicyCRUD() { + + // default last writer wins, path _ts + CosmosContainerSettings collectionSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainer collection = database.createContainer(collectionSettings, new CosmosContainerRequestOptions()).block().getContainer(); + collectionSettings = collection.read().block().getCosmosContainerSettings(); + + assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionMode()).isEqualTo(ConflictResolutionMode.LastWriterWins); + + // LWW without path specified, should default to _ts + collectionSettings.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy()); + collectionSettings = collection.replace(collectionSettings, null).block().getCosmosContainerSettings(); + + assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionMode()).isEqualTo(ConflictResolutionMode.LastWriterWins); + assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionPath()).isEqualTo("/_ts"); + + // Tests the following scenarios + // 1. LWW with valid path + // 2. LWW with null path, should default to _ts + // 3. LWW with empty path, should default to _ts + testConflictResolutionPolicyRequiringPath(ConflictResolutionMode.LastWriterWins, + new String[] { "/a", null, "" }, new String[] { "/a", "/_ts", "/_ts" }); + + // LWW invalid path + collectionSettings.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy("/a/b")); + + try { + collectionSettings = collection.replace(collectionSettings, null).block().getCosmosContainerSettings(); + fail("Expected exception on invalid path."); + } catch (Exception e) { + + // when (e.StatusCode == HttpStatusCode.BadRequest) + DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e.getCause(), DocumentClientException.class); + if (dce != null && dce.getStatusCode() == 400) { + assertThat(dce.getMessage()).contains("Invalid path '\\/a\\/b' for last writer wins conflict resolution"); + } else { + throw e; + } + } + + // LWW invalid path + + collectionSettings.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy("someText")); + + try { + collectionSettings = collection.replace(collectionSettings, null).block().getCosmosContainerSettings(); + fail("Expected exception on invalid path."); + } catch (Exception e) { + // when (e.StatusCode == HttpStatusCode.BadRequest) + DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e.getCause(), DocumentClientException.class); + if (dce != null && dce.getStatusCode() == 400) { + assertThat(dce.getMessage()).contains("Invalid path 'someText' for last writer wins conflict resolution"); + } else { + throw e; + } + } + + // Tests the following scenarios + // 1. Custom with valid sprocLink + // 2. Custom with null sprocLink, should default to empty string + // 3. Custom with empty sprocLink, should default to empty string + testConflictResolutionPolicyRequiringPath(ConflictResolutionMode.Custom, + new String[] { "randomSprocName", null, "" }, new String[] { "randomSprocName", "", "" }); + } + + private void testConflictResolutionPolicyRequiringPath(ConflictResolutionMode conflictResolutionMode, + String[] paths, String[] expectedPaths) { + for (int i = 0; i < paths.length; i++) { + CosmosContainerSettings collectionSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + + if (conflictResolutionMode == ConflictResolutionMode.LastWriterWins) { + collectionSettings.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy(paths[i])); + } else { + collectionSettings.setConflictResolutionPolicy(ConflictResolutionPolicy.createCustomPolicy(paths[i])); + } + collectionSettings = database.createContainer(collectionSettings, new CosmosContainerRequestOptions()).block().getCosmosContainerSettings(); + assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionMode()).isEqualTo(conflictResolutionMode); + + if (conflictResolutionMode == ConflictResolutionMode.LastWriterWins) { + assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionPath()).isEqualTo(expectedPaths[i]); + } else { + assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionProcedure()).isEqualTo(expectedPaths[i]); + } + } + } + + @Test(groups = "multi-master", timeOut = TIMEOUT) + public void invalidConflictResolutionPolicy_LastWriterWinsWithStoredProc() throws Exception { + CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + + // LWW without path specified, should default to _ts + ConflictResolutionPolicy policy = BridgeUtils.createConflictResolutionPolicy(); + BridgeUtils.setMode(policy, ConflictResolutionMode.LastWriterWins); + BridgeUtils.setStoredProc(policy,"randomSprocName"); + collection.setConflictResolutionPolicy(policy); + + Mono createObservable = database.createContainer( + collection, + new CosmosContainerRequestOptions()); + + FailureValidator validator = new FailureValidator.Builder() + .instanceOf(DocumentClientException.class) + .statusCode(400) + .errorMessageContains("LastWriterWins conflict resolution mode should not have conflict resolution procedure set.") + .build(); + validateFailure(createObservable, validator); + } + + @Test(groups = "multi-master", timeOut = TIMEOUT) + public void invalidConflictResolutionPolicy_CustomWithPath() throws Exception { + CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + + // LWW without path specified, should default to _ts + ConflictResolutionPolicy policy = BridgeUtils.createConflictResolutionPolicy(); + BridgeUtils.setMode(policy, ConflictResolutionMode.Custom); + BridgeUtils.setPath(policy,"/mypath"); + collection.setConflictResolutionPolicy(policy); + + Mono createObservable = database.createContainer( + collection, + new CosmosContainerRequestOptions()); + + FailureValidator validator = new FailureValidator.Builder() + .instanceOf(DocumentClientException.class) + .statusCode(400) + .errorMessageContains("Custom conflict resolution mode should not have conflict resolution path set.") + .build(); + validateFailure(createObservable, validator); + } + + @BeforeClass(groups = {"multi-master"}, timeOut = SETUP_TIMEOUT) + public void beforeClass() { + // set up the client + + client = clientBuilder.build(); + database = createDatabase(client, databaseId); + partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + } + + @AfterClass(groups = {"multi-master"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeDeleteDatabase(database); + safeClose(client); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiOrderByQueryTests.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiOrderByQueryTests.java index 9734948d38e35..38d551d1cac8e 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiOrderByQueryTests.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiOrderByQueryTests.java @@ -32,22 +32,26 @@ import java.util.Random; import java.util.UUID; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.apache.commons.collections4.ComparatorUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; - -import rx.Observable; - import com.fasterxml.jackson.databind.ObjectMapper; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.CompositePath; import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; + +import reactor.core.publisher.Flux; + import com.microsoft.azure.cosmosdb.CompositePathSortOrder; import com.microsoft.azure.cosmosdb.Document; @@ -66,12 +70,12 @@ public class MultiOrderByQueryTests extends TestSuiteBase { private static final String MEDIUM_STRING_FIELD = "mediumStringField"; private static final String LONG_STRING_FIELD = "longStringField"; private static final String PARTITION_KEY = "pk"; - private ArrayList documents = new ArrayList(); - private DocumentCollection documentCollection; - private Builder clientBuilder; - private AsyncDocumentClient client; + private ArrayList documents = new ArrayList(); + private CosmosContainer documentCollection; + private CosmosClientBuilder clientBuilder; + private CosmosClient client; - class CustomComparator implements Comparator { + class CustomComparator implements Comparator { String path; CompositePathSortOrder order; boolean isNumericPath = false; @@ -94,7 +98,7 @@ public CustomComparator(String path, CompositePathSortOrder order) { } @Override - public int compare(Document doc1, Document doc2) { + public int compare(CosmosItemSettings doc1, CosmosItemSettings doc2) { boolean isAsc = order == CompositePathSortOrder.Ascending; if (isNumericPath) { if (doc1.getInt(path) < doc2.getInt(path)) @@ -105,7 +109,7 @@ else if (doc1.getInt(path) > doc2.getInt(path)) return 0; } else if (isStringPath) { if (!isAsc) { - Document temp = doc1; + CosmosItemSettings temp = doc1; doc1 = doc2; doc2 = temp; } @@ -127,7 +131,7 @@ else if (doc1.getBoolean(path) == true && doc2.getBoolean(path) == false) } @Factory(dataProvider = "clientBuilders") - public MultiOrderByQueryTests(Builder clientBuilder) { + public MultiOrderByQueryTests(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -139,8 +143,8 @@ public void afterClass() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - documentCollection = SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES; - truncateCollection(SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES); + documentCollection = getSharedMultiPartitionCosmosContainerWithCompositeAndSpatialIndexes(client); + truncateCollection(documentCollection); int numberOfDocuments = 4; @@ -152,35 +156,35 @@ public void beforeClass() throws Exception { for (int j = 0; j < numberOfDuplicates; j++) { // Add the document itself for exact duplicates - Document initialDocument = new Document(multiOrderByDocumentString); + CosmosItemSettings initialDocument = new CosmosItemSettings(multiOrderByDocumentString); initialDocument.setId(UUID.randomUUID().toString()); this.documents.add(initialDocument); // Permute all the fields so that there are duplicates with tie breaks - Document numberClone = new Document(multiOrderByDocumentString); + CosmosItemSettings numberClone = new CosmosItemSettings(multiOrderByDocumentString); numberClone.set(NUMBER_FIELD, random.nextInt(5)); numberClone.setId(UUID.randomUUID().toString()); this.documents.add(numberClone); - Document stringClone = new Document(multiOrderByDocumentString); + CosmosItemSettings stringClone = new CosmosItemSettings(multiOrderByDocumentString); stringClone.set(STRING_FIELD, Integer.toString(random.nextInt(5))); stringClone.setId(UUID.randomUUID().toString()); this.documents.add(stringClone); - Document boolClone = new Document(multiOrderByDocumentString); + CosmosItemSettings boolClone = new CosmosItemSettings(multiOrderByDocumentString); boolClone.set(BOOL_FIELD, random.nextInt(2) % 2 == 0); boolClone.setId(UUID.randomUUID().toString()); this.documents.add(boolClone); // Also fuzz what partition it goes to - Document partitionClone = new Document(multiOrderByDocumentString); + CosmosItemSettings partitionClone = new CosmosItemSettings(multiOrderByDocumentString); partitionClone.set(PARTITION_KEY, random.nextInt(5)); partitionClone.setId(UUID.randomUUID().toString()); this.documents.add(partitionClone); } } - bulkInsertBlocking(client, documentCollection.getSelfLink(), documents); + bulkInsertBlocking(documentCollection, documents); waitIfNeededForReplicasToCatchUp(clientBuilder); } @@ -210,7 +214,8 @@ public void queryDocumentsWithMultiOrder() throws DocumentClientException, Inter feedOptions.setEnableCrossPartitionQuery(true); boolean[] booleanValues = new boolean[] {true, false}; - Iterator> compositeIndexesIterator = documentCollection.getIndexingPolicy().getCompositeIndexes().iterator(); + CosmosContainerSettings containerSettings = documentCollection.read().block().getCosmosContainerSettings(); + Iterator> compositeIndexesIterator = containerSettings.getIndexingPolicy().getCompositeIndexes().iterator(); while (compositeIndexesIterator.hasNext()) { ArrayList compositeIndex = compositeIndexesIterator.next(); // for every order @@ -260,13 +265,12 @@ public void queryDocumentsWithMultiOrder() throws DocumentClientException, Inter "FROM root " + whereString + " " + "ORDER BY " + orderByItemStringBuilder.toString(); - ArrayList expectedOrderedList = top(sort(filter(this.documents, hasFilter), compositeIndex, invert), hasTop, topCount) ; + ArrayList expectedOrderedList = top(sort(filter(this.documents, hasFilter), compositeIndex, invert), hasTop, topCount) ; - Observable> queryObservable = client - .queryDocuments(documentCollection.getSelfLink(), query, feedOptions); + Flux> queryObservable = documentCollection.queryItems(query, feedOptions); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .withOrderedResults(expectedOrderedList, compositeIndex) .build(); @@ -280,10 +284,9 @@ public void queryDocumentsWithMultiOrder() throws DocumentClientException, Inter // This query would then be invalid. Document documentWithEmptyField = generateMultiOrderByDocument(); documentWithEmptyField.remove(NUMBER_FIELD); - client.createDocument(documentCollection.getSelfLink(), documentWithEmptyField, null, false).toBlocking().single(); + documentCollection.createItem(documentWithEmptyField, new CosmosItemRequestOptions()).block(); String query = "SELECT [root." + NUMBER_FIELD + ",root." + STRING_FIELD + "] FROM root ORDER BY root." + NUMBER_FIELD + " ASC ,root." + STRING_FIELD + " DESC"; - Observable> queryObservable = client - .queryDocuments(documentCollection.getSelfLink(), query, feedOptions); + Flux> queryObservable = documentCollection.queryItems(query, feedOptions); FailureValidator validator = new FailureValidator.Builder() .instanceOf(UnsupportedOperationException.class) @@ -292,23 +295,23 @@ public void queryDocumentsWithMultiOrder() throws DocumentClientException, Inter validateQueryFailure(queryObservable, validator); } - private ArrayList top(ArrayList documents, boolean hasTop, int topCount) { - ArrayList result = new ArrayList(); + private ArrayList top(ArrayList arrayList, boolean hasTop, int topCount) { + ArrayList result = new ArrayList(); int counter = 0; if (hasTop) { - while (counter < topCount && counter < documents.size()) { - result.add(documents.get(counter)); + while (counter < topCount && counter < arrayList.size()) { + result.add(arrayList.get(counter)); counter++; } } else { - result.addAll(documents); + result.addAll(arrayList); } return result; } - private ArrayList sort(ArrayList documents, ArrayList compositeIndex, + private ArrayList sort(ArrayList arrayList, ArrayList compositeIndex, boolean invert) { - Collection> comparators = new ArrayList>(); + Collection> comparators = new ArrayList>(); Iterator compositeIndexIterator = compositeIndex.iterator(); while (compositeIndexIterator.hasNext()) { CompositePath compositePath = compositeIndexIterator.next(); @@ -323,20 +326,20 @@ private ArrayList sort(ArrayList documents, ArrayList filter(ArrayList documents, boolean hasFilter) { - ArrayList result = new ArrayList(); + private ArrayList filter(ArrayList cosmosItemSettings, boolean hasFilter) { + ArrayList result = new ArrayList(); if (hasFilter) { - for (Document document : documents) { + for (CosmosItemSettings document : cosmosItemSettings) { if (document.getInt(NUMBER_FIELD) % 2 == 0) { result.add(document); } } } else { - result.addAll(documents); + result.addAll(cosmosItemSettings); } return result; } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferQueryTest.java index 5554c8c1ee7ad..aa9a329faaa37 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferQueryTest.java @@ -29,7 +29,6 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DatabaseForTest; import org.assertj.core.util.Strings; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -37,14 +36,18 @@ import org.testng.annotations.Test; import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.DatabaseForTest; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.Offer; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import rx.Observable; +//TODO: change to use external TestSuiteBase public class OfferQueryTest extends TestSuiteBase { public final static int SETUP_TIMEOUT = 40000; @@ -147,6 +150,13 @@ public void beforeClass() throws Exception { for(int i = 0; i < 3; i++) { DocumentCollection collection = new DocumentCollection(); collection.setId(UUID.randomUUID().toString()); + + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + collection.setPartitionKey(partitionKeyDef); + createdCollections.add(createCollection(client, databaseId, collection)); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferReadReplaceTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferReadReplaceTest.java index 6a5d9e9fdfd06..de3715f02152a 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferReadReplaceTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferReadReplaceTest.java @@ -24,21 +24,21 @@ import java.util.List; -import com.microsoft.azure.cosmosdb.DatabaseForTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.DatabaseForTest; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.Offer; import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import rx.Observable; -import javax.net.ssl.SSLException; - +//TODO: change to use external TestSuiteBase public class OfferReadReplaceTest extends TestSuiteBase { public final String databaseId = DatabaseForTest.generateId(); @@ -112,5 +112,4 @@ public void afterClass() { safeDeleteDatabase(client, createdDatabase); safeClose(client); } - } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java index 21829fd366f87..d54f7ffba7d2a 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java @@ -35,6 +35,7 @@ import java.util.function.Function; import java.util.stream.Collectors; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import com.microsoft.azure.cosmosdb.RetryAnalyzer; import org.apache.commons.lang3.StringUtils; @@ -46,42 +47,44 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmos.CosmosBridgeInternal; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.ResourceResponse; import com.microsoft.azure.cosmosdb.internal.query.QueryItem; import com.microsoft.azure.cosmosdb.internal.routing.Range; import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; import com.microsoft.azure.cosmosdb.rx.internal.query.CompositeContinuationToken; import com.microsoft.azure.cosmosdb.rx.internal.query.OrderByContinuationToken; +import io.reactivex.subscribers.TestSubscriber; +import reactor.core.publisher.Flux; import rx.Observable; -import rx.observers.TestSubscriber; public class OrderbyDocumentQueryTest extends TestSuiteBase { private final double minQueryRequestChargePerPartition = 2.0; - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdDocuments = new ArrayList<>(); - - private AsyncDocumentClient client; + private CosmosClient client; + private CosmosContainer createdCollection; + private CosmosDatabase createdDatabase; + private List createdDocuments = new ArrayList<>(); private int numberOfPartitions; @Factory(dataProvider = "clientBuildersWithDirect") - public OrderbyDocumentQueryTest(AsyncDocumentClient.Builder clientBuilder) { + public OrderbyDocumentQueryTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocumentsValidateContent(boolean qmEnabled) throws Exception { - Document expectedDocument = createdDocuments.get(0); + CosmosItemSettings expectedDocument = createdDocuments.get(0); String query = String.format("SELECT * from root r where r.propStr = '%s'" + " ORDER BY r.propInt" @@ -91,22 +94,22 @@ public void queryDocumentsValidateContent(boolean qmEnabled) throws Exception { options.setEnableCrossPartitionQuery(true); options.setPopulateQueryMetrics(qmEnabled); - Observable> queryObservable = client.queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); List expectedResourceIds = new ArrayList<>(); expectedResourceIds.add(expectedDocument.getResourceId()); - Map> resourceIDToValidator = new HashMap<>(); + Map> resourceIDToValidator = new HashMap<>(); resourceIDToValidator.put(expectedDocument.getResourceId(), - new ResourceValidator.Builder().areEqual(expectedDocument).build()); + new ResourceValidator.Builder().areEqual(expectedDocument).build()); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .numberOfPages(1) .containsExactly(expectedResourceIds) .validateAllResources(resourceIDToValidator) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) - .allPagesSatisfy(new FeedResponseValidator.Builder().hasRequestChargeHeader().build()) + .allPagesSatisfy(new FeedResponseValidator.Builder().hasRequestChargeHeader().build()) .hasValidQueryMetrics(qmEnabled) .build(); @@ -116,9 +119,9 @@ public void queryDocumentsValidateContent(boolean qmEnabled) throws Exception { // TODO: DANOBLE: report this detailed information in all failures produced by TestSuiteBase classes // work item: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/370015 String message = String.format("%s %s mode with %s consistency test failure", - this.clientBuilder.connectionPolicy.getConnectionMode(), - this.clientBuilder.configs.getProtocol(), - this.clientBuilder.desiredConsistencyLevel); + this.clientBuilder.getConnectionPolicy().getConnectionMode(), + this.clientBuilder.getConfigs().getProtocol(), + this.clientBuilder.getDesiredConsistencyLevel()); throw new AssertionError(message, error); } } @@ -128,14 +131,13 @@ public void queryDocuments_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2' ORDER BY r.propInt"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .hasRequestChargeHeader().build()) .build(); @@ -154,8 +156,7 @@ public void queryOrderBy(String sortOrder) throws Exception { options.setEnableCrossPartitionQuery(true); int pageSize = 3; options.setMaxItemCount(pageSize); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); Comparator validatorComparator = Comparator.nullsFirst(Comparator.naturalOrder()); List expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); @@ -165,10 +166,10 @@ public void queryOrderBy(String sortOrder) throws Exception { int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); @@ -183,17 +184,16 @@ public void queryOrderByInt() throws Exception { options.setEnableCrossPartitionQuery(true); int pageSize = 3; options.setMaxItemCount(pageSize); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); Comparator validatorComparator = Comparator.nullsFirst(Comparator.naturalOrder()); List expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); @@ -208,17 +208,16 @@ public void queryOrderByString() throws Exception { options.setEnableCrossPartitionQuery(true); int pageSize = 3; options.setMaxItemCount(pageSize); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); Comparator validatorComparator = Comparator.nullsFirst(Comparator.naturalOrder()); List expectedResourceIds = sortDocumentsAndCollectResourceIds("propStr", d -> d.getString("propStr"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); @@ -239,8 +238,7 @@ public void queryOrderWithTop(int topValue) throws Exception { options.setEnableCrossPartitionQuery(true); int pageSize = 3; options.setMaxItemCount(pageSize); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); Comparator validatorComparator = Comparator.nullsFirst(Comparator.naturalOrder()); @@ -250,10 +248,10 @@ public void queryOrderWithTop(int topValue) throws Exception { int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * (topValue > 0 ? minQueryRequestChargePerPartition : 1)) .build(); @@ -261,7 +259,7 @@ public void queryOrderWithTop(int topValue) throws Exception { validateQuerySuccess(queryObservable, validator); } - private List sortDocumentsAndCollectResourceIds(String propName, Function extractProp, Comparator comparer) { + private List sortDocumentsAndCollectResourceIds(String propName, Function extractProp, Comparator comparer) { return createdDocuments.stream() .filter(d -> d.getHashMap().containsKey(propName)) // removes undefined .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) @@ -272,8 +270,7 @@ private List sortDocumentsAndCollectResourceIds(String propName, Fun public void crossPartitionQueryNotEnabled() throws Exception { String query = "SELECT * FROM r ORDER BY r.propInt"; FeedOptions options = new FeedOptions(); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(DocumentClientException.class) @@ -288,43 +285,39 @@ public void queryScopedToSinglePartition_StartWithContinuationToken() throws Exc FeedOptions options = new FeedOptions(); options.setPartitionKey(new PartitionKey("duplicateParitionKeyValue")); options.setMaxItemCount(3); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); - + Flux> queryObservable = createdCollection.queryItems(query, options); - TestSubscriber> subscriber = new TestSubscriber<>(); - queryObservable.first().subscribe(subscriber); + TestSubscriber> subscriber = new TestSubscriber<>(); + queryObservable.take(1).subscribe(subscriber); subscriber.awaitTerminalEvent(); - subscriber.assertCompleted(); + subscriber.assertComplete(); subscriber.assertNoErrors(); - assertThat(subscriber.getValueCount()).isEqualTo(1); - FeedResponse page = subscriber.getOnNextEvents().get(0); + assertThat(subscriber.valueCount()).isEqualTo(1); + FeedResponse page = (FeedResponse) subscriber.getEvents().get(0).get(0); assertThat(page.getResults()).hasSize(3); assertThat(page.getResponseContinuation()).isNotEmpty(); options.setRequestContinuation(page.getResponseContinuation()); - queryObservable = client - .queryDocuments(getCollectionLink(), query, options); - + queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments.stream() + List expectedDocs = createdDocuments.stream() .filter(d -> (StringUtils.equals("duplicateParitionKeyValue", d.getString("mypk")))) .filter(d -> (d.getInt("propScopedPartitionInt") > 2)).collect(Collectors.toList()); int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); assertThat(expectedDocs).hasSize(10 - 3); - FeedResponseListValidator validator = null; + FeedResponseListValidator validator = null; - validator = new FeedResponseListValidator.Builder() + validator = new FeedResponseListValidator.Builder() .containsExactly(expectedDocs.stream() .sorted((e1, e2) -> Integer.compare(e1.getInt("propScopedPartitionInt"), e2.getInt("propScopedPartitionInt"))) .map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -417,27 +410,22 @@ public void queryDocumentsWithInvalidOrderByContinuationTokensString(String sort this.assertInvalidContinuationToken(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds); } - public Document createDocument(AsyncDocumentClient client, Map keyValueProps) + public CosmosItemSettings createDocument(CosmosContainer cosmosContainer, Map keyValueProps) throws DocumentClientException { - Document docDefinition = getDocumentDefinition(keyValueProps); - return client.createDocument(getCollectionLink(), docDefinition, null, false) - .toBlocking().single() - .getResource(); + CosmosItemSettings docDefinition = getDocumentDefinition(keyValueProps); + return cosmosContainer.createItem(docDefinition, new CosmosItemSettings()).block().getCosmosItemSettings(); } - public List bulkInsert(AsyncDocumentClient client, List> keyValuePropsList) { + public List bulkInsert(CosmosContainer cosmosContainer, List> keyValuePropsList) { - ArrayList>> result = new ArrayList>>(); + ArrayList result = new ArrayList(); for(Map keyValueProps: keyValuePropsList) { - Document docDefinition = getDocumentDefinition(keyValueProps); - Observable> obs = client.createDocument(getCollectionLink(), docDefinition, null, false); - result.add(obs); + CosmosItemSettings docDefinition = getDocumentDefinition(keyValueProps); + result.add(docDefinition); } - return Observable.merge(result, 100). - map(resp -> resp.getResource()) - .toList().toBlocking().single(); + return bulkInsertBlocking(cosmosContainer, result); } @BeforeMethod(groups = { "simple" }) @@ -449,9 +437,9 @@ public void beforeMethod() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; - truncateCollection(SHARED_MULTI_PARTITION_COLLECTION); + createdDatabase = getSharedCosmosDatabase(client); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); List> keyValuePropsList = new ArrayList<>(); Map props; @@ -467,17 +455,20 @@ public void beforeClass() throws Exception { props = new HashMap<>(); keyValuePropsList.add(props); - createdDocuments = bulkInsert(client, keyValuePropsList); + createdDocuments = bulkInsert(createdCollection, keyValuePropsList); for(int i = 0; i < 10; i++) { Map p = new HashMap<>(); p.put("propScopedPartitionInt", i); - Document doc = getDocumentDefinition("duplicateParitionKeyValue", UUID.randomUUID().toString(), p); - createdDocuments.add(client.createDocument(getCollectionLink(), doc, null, false).toBlocking().single().getResource()); + CosmosItemSettings doc = getDocumentDefinition("duplicateParitionKeyValue", UUID.randomUUID().toString(), p); + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(new PartitionKey(doc.get("mypk"))); + createdDocuments.add(createDocument(createdCollection, doc).read(options).block().getCosmosItemSettings()); } - numberOfPartitions = client - .readPartitionKeyRanges(getCollectionLink(), null) + + numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client) + .readPartitionKeyRanges("dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(), null) .flatMap(p -> Observable.from(p.getResults())).toList().toBlocking().single().size(); waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -503,12 +494,12 @@ private void assertInvalidContinuationToken(String query, int[] pageSize, List> queryObservable = client.queryDocuments(getCollectionLink(), query, + Flux> queryObservable = createdCollection.queryItems(query, options); - Observable> firstPageObservable = queryObservable.first(); - TestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - firstPageObservable.subscribe(testSubscriber); + //Observable> firstPageObservable = queryObservable.first(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); + queryObservable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertError(DocumentClientException.class); } while (requestContinuation != null); @@ -516,9 +507,9 @@ private void assertInvalidContinuationToken(String query, int[] pageSize, List expectedIds) { for (int pageSize : pageSizes) { - List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); + List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); List actualIds = new ArrayList(); - for (Document document : receivedDocuments) { + for (CosmosItemSettings document : receivedDocuments) { actualIds.add(document.getResourceId()); } @@ -526,27 +517,27 @@ private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSiz } } - private List queryWithContinuationTokens(String query, int pageSize) { + private List queryWithContinuationTokens(String query, int pageSize) { String requestContinuation = null; List continuationTokens = new ArrayList(); - List receivedDocuments = new ArrayList(); + List receivedDocuments = new ArrayList(); do { FeedOptions options = new FeedOptions(); options.setMaxItemCount(pageSize); options.setEnableCrossPartitionQuery(true); options.setMaxDegreeOfParallelism(2); options.setRequestContinuation(requestContinuation); - Observable> queryObservable = client.queryDocuments(getCollectionLink(), query, + Flux> queryObservable = createdCollection.queryItems(query, options); - Observable> firstPageObservable = queryObservable.first(); - TestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - firstPageObservable.subscribe(testSubscriber); + //Observable> firstPageObservable = queryObservable.first(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); + queryObservable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); - FeedResponse firstPage = testSubscriber.getOnNextEvents().get(0); + FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getResponseContinuation(); receivedDocuments.addAll(firstPage.getResults()); continuationTokens.add(requestContinuation); @@ -555,7 +546,7 @@ private List queryWithContinuationTokens(String query, int pageSize) { return receivedDocuments; } - private static Document getDocumentDefinition(String partitionKey, String id, Map keyValuePair) { + private static CosmosItemSettings getDocumentDefinition(String partitionKey, String id, Map keyValuePair) { StringBuilder sb = new StringBuilder(); sb.append("{\n"); @@ -575,18 +566,14 @@ private static Document getDocumentDefinition(String partitionKey, String id, Ma sb.append(String.format(" \"mypk\": \"%s\"\n", partitionKey)); sb.append("}"); - return new Document(sb.toString()); + return new CosmosItemSettings(sb.toString()); } - private static Document getDocumentDefinition(Map keyValuePair) { + private static CosmosItemSettings getDocumentDefinition(Map keyValuePair) { String uuid = UUID.randomUUID().toString(); return getDocumentDefinition(uuid, uuid, keyValuePair); } - public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); - } - private static String toJson(Object object){ try { return com.microsoft.azure.cosmosdb.internal.Utils.getSimpleObjectMapper().writeValueAsString(object); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParallelDocumentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParallelDocumentQueryTest.java index 14aacf69af53e..8f2a8b749c6b7 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParallelDocumentQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParallelDocumentQueryTest.java @@ -22,6 +22,12 @@ */ package com.microsoft.azure.cosmosdb.rx; +import com.microsoft.azure.cosmos.CosmosBridgeInternal; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.BridgeInternal; import static org.assertj.core.api.Assertions.assertThat; @@ -36,10 +42,7 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.QueryMetrics; @@ -48,28 +51,28 @@ import org.testng.SkipException; import org.testng.annotations.DataProvider; import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; import com.microsoft.azure.cosmosdb.rx.internal.query.CompositeContinuationToken; +import io.reactivex.subscribers.TestSubscriber; +import reactor.core.publisher.Flux; import rx.Observable; -import rx.observers.TestSubscriber; import java.util.Map; public class ParallelDocumentQueryTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdDocuments; + private CosmosDatabase createdDatabase; + private CosmosContainer createdCollection; + private List createdDocuments; - private AsyncDocumentClient client; + private CosmosClient client; public String getCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); } @Factory(dataProvider = "clientBuildersWithDirect") - public ParallelDocumentQueryTest(AsyncDocumentClient.Builder clientBuilder) { + public ParallelDocumentQueryTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -89,16 +92,15 @@ public void queryDocuments(boolean qmEnabled) { options.setEnableCrossPartitionQuery(true); options.setPopulateQueryMetrics(qmEnabled); options.setMaxDegreeOfParallelism(2); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments.stream().filter(d -> 99 == d.getInt("prop") ).collect(Collectors.toList()); + List expectedDocs = createdDocuments.stream().filter(d -> 99 == d.getInt("prop") ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .hasValidQueryMetrics(qmEnabled) .build(); @@ -106,8 +108,8 @@ public void queryDocuments(boolean qmEnabled) { try { validateQuerySuccess(queryObservable, validator, TIMEOUT); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format(String.format("Direct TCP test failure: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel)); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format(String.format("Direct TCP test failure: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel())); logger.info(message, error); throw new SkipException(message, error); } @@ -124,14 +126,12 @@ public void queryMetricEquality() throws Exception { options.setPopulateQueryMetrics(true); options.setMaxDegreeOfParallelism(0); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); - List> resultList1 = queryObservable.toList().toBlocking().single(); + Flux> queryObservable = createdCollection.queryItems(query, options); + List> resultList1 = queryObservable.collectList().block(); options.setMaxDegreeOfParallelism(4); - Observable> threadedQueryObs = client.queryDocuments(getCollectionLink(), query, - options); - List> resultList2 = threadedQueryObs.toList().toBlocking().single(); + Flux> threadedQueryObs = createdCollection.queryItems(query, options); + List> resultList2 = threadedQueryObs.collectList().block(); assertThat(resultList1.size()).isEqualTo(resultList2.size()); for(int i = 0; i < resultList1.size(); i++){ @@ -157,13 +157,12 @@ public void queryDocuments_NoResults() { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPagesIsGreaterThanOrEqualTo(1) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .pageSizeIsLessThanOrEqualTo(0) .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -181,20 +180,19 @@ public void queryDocumentsWithPageSize() { options.setMaxItemCount(pageSize); options.setMaxDegreeOfParallelism(-1); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments; + List expectedDocs = createdDocuments; assertThat(expectedDocs).isNotEmpty(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() .map(d -> d.getResourceId()) .collect(Collectors.toList())) .numberOfPagesIsGreaterThanOrEqualTo((expectedDocs.size() + 1) / 3) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0) .pageSizeIsLessThanOrEqualTo(pageSize) .build()) @@ -202,8 +200,8 @@ public void queryDocumentsWithPageSize() { try { validateQuerySuccess(queryObservable, validator, 2 * subscriberValidationTimeout); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -216,8 +214,7 @@ public void invalidQuerySyntax() { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(DocumentClientException.class) @@ -231,8 +228,7 @@ public void invalidQuerySyntax() { public void crossPartitionQueryNotEnabled() { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(DocumentClientException.class) @@ -249,22 +245,21 @@ public void crossPartitionQueryNotEnabled() { public void partitionKeyRangeId() { int sum = 0; try { - for (String partitionKeyRangeId : client.readPartitionKeyRanges(getCollectionLink(), null) + for (String partitionKeyRangeId : CosmosBridgeInternal.getAsyncDocumentClient(client).readPartitionKeyRanges(getCollectionLink(), null) .flatMap(p -> Observable.from(p.getResults())) .map(pkr -> pkr.getId()).toList().toBlocking().single()) { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); options.setPartitionKeyRangeIdInternal(partitionKeyRangeId); - int queryResultCount = client - .queryDocuments(getCollectionLink(), query, options) - .flatMap(p -> Observable.from(p.getResults())) - .toList().toBlocking().single().size(); + int queryResultCount = createdCollection.queryItems(query, options) + .flatMap(p -> Flux.fromIterable(p.getResults())) + .collectList().block().size(); sum += queryResultCount; } } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -315,7 +310,7 @@ public void queryDocumentsWithCompositeContinuationTokens() throws Exception { String query = "SELECT * FROM c"; // Get Expected - List expectedDocs = createdDocuments + List expectedDocs = createdDocuments .stream() .collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); @@ -335,10 +330,10 @@ public void queryDocumentsWithCompositeContinuationTokens() throws Exception { @BeforeClass(groups = { "simple", "non-emulator" }, timeOut = 2 * SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; - truncateCollection(SHARED_MULTI_PARTITION_COLLECTION); - List docDefList = new ArrayList<>(); + createdDatabase = getSharedCosmosDatabase(client); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); + List docDefList = new ArrayList<>(); for(int i = 0; i < 13; i++) { docDefList.add(getDocumentDefinition(i)); } @@ -347,7 +342,7 @@ public void beforeClass() { docDefList.add(getDocumentDefinition(99)); } - createdDocuments = bulkInsertBlocking(client, getCollectionLink(), docDefList); + createdDocuments = bulkInsertBlocking(createdCollection, docDefList); waitIfNeededForReplicasToCatchUp(clientBuilder); } @@ -357,9 +352,9 @@ public void afterClass() { safeClose(client); } - private static Document getDocumentDefinition(int cnt) { + private static CosmosItemSettings getDocumentDefinition(int cnt) { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " + CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + "\"id\": \"%s\", " + "\"prop\" : %d, " + "\"mypk\": \"%s\", " @@ -375,31 +370,30 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client.queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); FailureValidator validator = new FailureValidator.Builder().instanceOf(DocumentClientException.class) .statusCode(400).notNullActivityId().build(); validateQueryFailure(queryObservable, validator); } - public Document createDocument(AsyncDocumentClient client, int cnt) throws DocumentClientException { + public CosmosItemSettings createDocument(CosmosContainer cosmosContainer, int cnt) throws DocumentClientException { - Document docDefinition = getDocumentDefinition(cnt); + CosmosItemSettings docDefinition = getDocumentDefinition(cnt); - return client.createDocument(getCollectionLink(), docDefinition, null, false).toBlocking().single() - .getResource(); + return cosmosContainer.createItem(docDefinition, new CosmosItemSettings()).block().getCosmosItemSettings(); } - private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, List expectedDocs) { + private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, List expectedDocs) { for (int pageSize : pageSizes) { - List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); + List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); List actualIds = new ArrayList(); - for (Document document : receivedDocuments) { + for (CosmosItemSettings document : receivedDocuments) { actualIds.add(document.getResourceId()); } List expectedIds = new ArrayList(); - for (Document document : expectedDocs) { + for (CosmosItemSettings document : expectedDocs) { expectedIds.add(document.getResourceId()); } @@ -407,27 +401,25 @@ private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSiz } } - private List queryWithContinuationTokens(String query, int pageSize) { + private List queryWithContinuationTokens(String query, int pageSize) { String requestContinuation = null; List continuationTokens = new ArrayList(); - List receivedDocuments = new ArrayList(); + List receivedDocuments = new ArrayList(); do { FeedOptions options = new FeedOptions(); options.setMaxItemCount(pageSize); options.setEnableCrossPartitionQuery(true); options.setMaxDegreeOfParallelism(2); options.setRequestContinuation(requestContinuation); - Observable> queryObservable = client.queryDocuments(getCollectionLink(), query, - options); + Flux> queryObservable = createdCollection.queryItems(query, options); - Observable> firstPageObservable = queryObservable.first(); - TestSubscriber> testSubscriber = new TestSubscriber<>(); - firstPageObservable.subscribe(testSubscriber); + TestSubscriber> testSubscriber = new TestSubscriber<>(); + queryObservable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); - FeedResponse firstPage = testSubscriber.getOnNextEvents().get(0); + FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getResponseContinuation(); receivedDocuments.addAll(firstPage.getResults()); continuationTokens.add(requestContinuation); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionCrudTest.java index 45c5132499c7b..bbc3ad2c18494 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionCrudTest.java @@ -36,11 +36,13 @@ import com.microsoft.azure.cosmosdb.ResourceResponse; import com.microsoft.azure.cosmosdb.User; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import rx.Observable; import javax.net.ssl.SSLException; +//TODO: change to use external TestSuiteBase public class PermissionCrudTest extends TestSuiteBase { private Database createdDatabase; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionQueryTest.java index f53e7da02edec..ea87e18cdce0a 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionQueryTest.java @@ -29,13 +29,13 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DatabaseForTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.DatabaseForTest; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; @@ -43,11 +43,13 @@ import com.microsoft.azure.cosmosdb.Permission; import com.microsoft.azure.cosmosdb.PermissionMode; import com.microsoft.azure.cosmosdb.User; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import rx.Observable; import javax.net.ssl.SSLException; +//TODO: change to use external TestSuiteBase public class PermissionQueryTest extends TestSuiteBase { public final String databaseId = DatabaseForTest.generateId(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ProxyHostTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ProxyHostTest.java index f982df926d244..79e9a38e23252 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ProxyHostTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ProxyHostTest.java @@ -33,29 +33,25 @@ import org.apache.log4j.PatternLayout; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.WriterAppender; -import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; -import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Factory; import org.testng.annotations.Test; import com.microsoft.azure.cosmosdb.rx.proxy.HttpProxyServer; -import io.netty.handler.logging.LogLevel; -import io.netty.handler.logging.LoggingHandler; +import reactor.core.publisher.Mono; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemResponse; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.CosmosResponseValidator; import com.microsoft.azure.cosmosdb.ConnectionPolicy; import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; - -import rx.Observable; import static org.assertj.core.api.Assertions.assertThat; @@ -67,10 +63,10 @@ */ public class ProxyHostTest extends TestSuiteBase { - private static Database createdDatabase; - private static DocumentCollection createdCollection; + private static CosmosDatabase createdDatabase; + private static CosmosContainer createdCollection; - private AsyncDocumentClient client; + private CosmosClient client; private final String PROXY_HOST = "localhost"; private final int PROXY_PORT = 8080; private HttpProxyServer httpProxyServer; @@ -82,8 +78,8 @@ public ProxyHostTest() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION; + createdDatabase = getSharedCosmosDatabase(client); + createdCollection = getSharedMultiPartitionCosmosContainer(client); httpProxyServer = new HttpProxyServer(); httpProxyServer.start(); // wait for proxy server to be ready @@ -97,18 +93,18 @@ public void beforeClass() throws Exception { */ @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createDocumentWithValidHttpProxy() throws Exception { - AsyncDocumentClient clientWithRightProxy = null; + CosmosClient clientWithRightProxy = null; try { ConnectionPolicy connectionPolicy =new ConnectionPolicy(); connectionPolicy.setProxy(PROXY_HOST, PROXY_PORT); - clientWithRightProxy = new Builder().withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session).build(); - Document docDefinition = getDocumentDefinition(); - Observable> createObservable = clientWithRightProxy - .createDocument(getCollectionLink(), docDefinition, null, false); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + clientWithRightProxy = CosmosClient.builder().endpoint(TestConfigurations.HOST) + .key(TestConfigurations.MASTER_KEY) + .connectionPolicy(connectionPolicy) + .consistencyLevel(ConsistencyLevel.Session).build(); + CosmosItemSettings docDefinition = getDocumentDefinition(); + Mono createObservable = clientWithRightProxy.getDatabase(createdDatabase.getId()).getContainer(createdCollection.getId()) + .createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.getId()) .build(); validateSuccess(createObservable, validator); @@ -126,7 +122,7 @@ public void createDocumentWithValidHttpProxy() throws Exception { public void createDocumentWithValidHttpProxyWithNettyWireLogging() throws Exception { LogManager.getRootLogger().setLevel(Level.INFO); LogManager.getLogger(LogLevelTest.NETWORK_LOGGING_CATEGORY).setLevel(Level.TRACE); - AsyncDocumentClient clientWithRightProxy = null; + CosmosClient clientWithRightProxy = null; try { StringWriter consoleWriter = new StringWriter(); WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); @@ -134,14 +130,14 @@ public void createDocumentWithValidHttpProxyWithNettyWireLogging() throws Except ConnectionPolicy connectionPolicy =new ConnectionPolicy(); connectionPolicy.setProxy(PROXY_HOST, PROXY_PORT); - clientWithRightProxy = new Builder().withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session).build(); - Document docDefinition = getDocumentDefinition(); - Observable> createObservable = clientWithRightProxy - .createDocument(getCollectionLink(), docDefinition, null, false); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + clientWithRightProxy = CosmosClient.builder().endpoint(TestConfigurations.HOST) + .key(TestConfigurations.MASTER_KEY) + .connectionPolicy(connectionPolicy) + .consistencyLevel(ConsistencyLevel.Session).build(); + CosmosItemSettings docDefinition = getDocumentDefinition(); + Mono createObservable = clientWithRightProxy.getDatabase(createdDatabase.getId()).getContainer(createdCollection.getId()) + .createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.getId()) .build(); validateSuccess(createObservable, validator); @@ -178,13 +174,9 @@ public void afterMethod(Method method) { PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties")); } - private String getCollectionLink() { - return createdCollection.getSelfLink(); - } - - private Document getDocumentDefinition() { + private CosmosItemSettings getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " + CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedAttachmentsTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedAttachmentsTest.java deleted file mode 100644 index bf61c7d7414ae..0000000000000 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedAttachmentsTest.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import org.apache.commons.io.IOUtils; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import com.microsoft.azure.cosmosdb.Attachment; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.MediaOptions; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; - -import rx.Observable; -import rx.observers.TestSubscriber; - -import javax.net.ssl.SSLException; - -public class ReadFeedAttachmentsTest extends TestSuiteBase { - - private Database createdDatabase; - private DocumentCollection createdCollection; - private Document createdDocument; - - private AsyncDocumentClient client; - - private PartitionKey pk; - @Factory(dataProvider = "clientBuildersWithDirect") - public ReadFeedAttachmentsTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; - } - - @Test(groups = { "simple" }, timeOut = 30000000) - public void readExternalAttachments() throws Exception { - createdDocument = createDocument(client, createdDatabase.getId(), - createdCollection.getId(), getDocumentDefinition()); - - List createdAttachments = new ArrayList<>(); - for(int i = 0; i < 5; i++) { - createdAttachments.add(createAttachments(client)); - } - waitIfNeededForReplicasToCatchUp(clientBuilder); - - FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); - options.setPartitionKey(pk); - - Observable> feedObservable = client.readAttachments(getDocumentLink(), options); - - int expectedPageSize = (createdAttachments.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() - .totalSize(createdAttachments.size()) - .exactlyContainsInAnyOrder(createdAttachments - .stream() - .map(d -> d.getResourceId()) - .collect(Collectors.toList())) - .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() - .requestChargeGreaterThanOrEqualTo(1.0).build()) - .build(); - validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); - } - - //@Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) - public void readAndUpdateEmbededAttachments() throws Exception { - createdDocument = createDocument(client, createdDatabase.getId(), - createdCollection.getId(), getDocumentDefinition()); - - FeedOptions feedOptions = new FeedOptions(); - feedOptions.setMaxItemCount(1); - feedOptions.setPartitionKey(pk); - String documentLink = "dbs/" + getDatabaseId() + "/colls/" + getCollectionId() + "/docs/" + getDocumentId(); - - MediaOptions options = new MediaOptions(); - options.setContentType("application/octet-stream"); - - RequestOptions reqOptions = new RequestOptions(); - reqOptions.setPartitionKey(pk); - - - try(InputStream ipStream = getMedia1Stream()) { - TestSubscriber> subscriber = new TestSubscriber<>(); - client.createAttachment(documentLink, ipStream, options, reqOptions) - .toBlocking() - .subscribe(subscriber); - subscriber.assertNoErrors(); - } - - try(InputStream ipStream = getMedia1Stream()) { - validateReadEmbededAttachment(documentLink, ipStream, feedOptions); - } - - validateUpdateEmbededAttachment(documentLink, options, feedOptions); - } - - @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION; - } - - @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeClose(client); - } - - private void validateUpdateEmbededAttachment(String documentLink, MediaOptions mediaOptions, FeedOptions feedOptions) throws Exception { - String mediaLink = client.readAttachments(documentLink, feedOptions) - .map( response -> response.getResults().iterator().next().getMediaLink()) - .toBlocking() - .first(); - - try (InputStream ipStream = getMedia2Stream()) { - client.updateMedia(mediaLink, ipStream, mediaOptions) - .toBlocking().first(); - } - - try (InputStream ipStream = getMedia2Stream()) { - validateReadEmbededAttachment(documentLink, ipStream, feedOptions); - } - } - - private void validateReadEmbededAttachment(String documentLink, InputStream ipStream, FeedOptions feedOptions) { - TestSubscriber subscriber = new TestSubscriber<>(); - client.readAttachments(documentLink, feedOptions) - .map( response -> response.getResults().iterator().next().getMediaLink()) - .flatMap(mediaLink -> client.readMedia(mediaLink)) - .map(mediaResponse -> { - - try(InputStream responseMediaStream = mediaResponse.getMedia()) { - return IOUtils.contentEquals(ipStream, responseMediaStream); - } catch (IOException e) { - return false; - } - }) - .filter(x -> x) // Filter only right extractions back - .toBlocking() - .subscribe(subscriber); - - subscriber.assertNoErrors(); - subscriber.assertCompleted(); - subscriber.assertValueCount(1); - } - - private InputStream getMedia1Stream() - { - return this.getClass().getResourceAsStream("/cosmosdb-1.png"); - } - - private InputStream getMedia2Stream() - { - return this.getClass().getResourceAsStream("/Microsoft.jpg"); - } - - private String getCollectionId() { - return createdCollection.getId(); - } - - private String getDatabaseId() { - return createdDatabase.getId(); - } - - private String getDocumentId() { - return createdDocument.getId(); - } - - public Attachment createAttachments(AsyncDocumentClient client) { - Attachment attachment = getAttachmentDefinition(); - RequestOptions options = new RequestOptions(); - options.setPartitionKey(pk); - return client.createAttachment(getDocumentLink(), attachment, options).toBlocking().single().getResource(); - } - - public String getDocumentLink() { - return "dbs/" + getDatabaseId() + "/colls/" + getCollectionId() + "/docs/" + getDocumentId(); - } - - private Document getDocumentDefinition() { - String uuid = UUID.randomUUID().toString(); - pk = new PartitionKey(uuid); - Document doc = new Document(String.format("{ " - + "\"id\": \"%s\", " - + "\"mypk\": \"%s\", " - + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" - + "}" - , uuid, uuid)); - return doc; - } - - private static Attachment getAttachmentDefinition() { - String uuid = UUID.randomUUID().toString(); - String type = "application/text"; - return new Attachment(String.format( - "{" + - " 'id': '%s'," + - " 'media': 'http://xstore.'," + - " 'MediaType': 'Book'," + - " 'Author': 'My Book Author'," + - " 'Title': 'My Book Title'," + - " 'contentType': '%s'" + - "}", uuid, type)); - } -} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedCollectionsTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedCollectionsTest.java index fb3c735ea8677..54982a098e6fe 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedCollectionsTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedCollectionsTest.java @@ -27,21 +27,23 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DatabaseForTest; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import rx.Observable; - -import javax.net.ssl.SSLException; +import reactor.core.publisher.Flux; public class ReadFeedCollectionsTest extends TestSuiteBase { @@ -49,15 +51,15 @@ public class ReadFeedCollectionsTest extends TestSuiteBase { protected static final int SETUP_TIMEOUT = 60000; protected static final int SHUTDOWN_TIMEOUT = 20000; - public final String databaseId = DatabaseForTest.generateId(); + public final String databaseId = CosmosDatabaseForTest.generateId(); - private Database createdDatabase; - private List createdCollections = new ArrayList<>(); + private CosmosDatabase createdDatabase; + private List createdCollections = new ArrayList<>(); - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuilders") - public ReadFeedCollectionsTest(AsyncDocumentClient.Builder clientBuilder) { + public ReadFeedCollectionsTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -67,15 +69,15 @@ public void readCollections() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - Observable> feedObservable = client.readCollections(getDatabaseLink(), options); + Flux> feedObservable = createdDatabase.listContainers(options); int expectedPageSize = (createdCollections.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdCollections.size()) - .exactlyContainsInAnyOrder(createdCollections.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(createdCollections.stream().map(d -> d.read().block().getCosmosContainerSettings().getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -89,23 +91,22 @@ public void beforeClass() { createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 3; i++) { - createdCollections.add(createCollections(client)); + createdCollections.add(createCollections(createdDatabase)); } } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteDatabase(client, createdDatabase); + safeDeleteDatabase(createdDatabase); safeClose(client); } - public DocumentCollection createCollections(AsyncDocumentClient client) { - DocumentCollection collection = new DocumentCollection(); - collection.setId(UUID.randomUUID().toString()); - return client.createCollection(getDatabaseLink(), collection, null).toBlocking().single().getResource(); - } - - private String getDatabaseLink() { - return "dbs/" + createdDatabase.getId(); + public CosmosContainer createCollections(CosmosDatabase database) { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + return database.createContainer(collection, new CosmosContainerRequestOptions()).block().getContainer(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDatabasesTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDatabasesTest.java index 823118868ec5e..74e01f247ef94 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDatabasesTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDatabasesTest.java @@ -28,30 +28,29 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DatabaseForTest; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosDatabaseRequestOptions; +import com.microsoft.azure.cosmos.CosmosDatabaseSettings; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import rx.Observable; - -import javax.net.ssl.SSLException; +import reactor.core.publisher.Flux; public class ReadFeedDatabasesTest extends TestSuiteBase { - private List createdDatabases = new ArrayList<>(); - private List allDatabases = new ArrayList<>(); + private List createdDatabases = new ArrayList<>(); + private List allDatabases = new ArrayList<>(); - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuilders") - public ReadFeedDatabasesTest(AsyncDocumentClient.Builder clientBuilder) { + public ReadFeedDatabasesTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -61,14 +60,14 @@ public void readDatabases() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - Observable> feedObservable = client.readDatabases(options); + Flux> feedObservable = client.listDatabases(options); int expectedPageSize = (allDatabases.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(allDatabases.size()) .exactlyContainsInAnyOrder(allDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -78,28 +77,26 @@ public void readDatabases() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws URISyntaxException { client = clientBuilder.build(); - allDatabases = client.readDatabases(null) + allDatabases = client.listDatabases(null) .map(frp -> frp.getResults()) - .toList() + .collectList() .map(list -> list.stream().flatMap(x -> x.stream()).collect(Collectors.toList())) - .toBlocking() - .single(); + .block(); for(int i = 0; i < 5; i++) { createdDatabases.add(createDatabase(client)); } allDatabases.addAll(createdDatabases); } - public Database createDatabase(AsyncDocumentClient client) { - Database db = new Database(); - db.setId(UUID.randomUUID().toString()); - return client.createDatabase(db, null).toBlocking().single().getResource(); + public CosmosDatabaseSettings createDatabase(CosmosClient client) { + CosmosDatabaseSettings db = new CosmosDatabaseSettings(UUID.randomUUID().toString()); + return client.createDatabase(db, new CosmosDatabaseRequestOptions()).block().getCosmosDatabaseSettings(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { for (int i = 0; i < 5; i ++) { - safeDeleteDatabase(client, createdDatabases.get(i).getId()); + safeDeleteDatabase(client.getDatabase(createdDatabases.get(i).getId())); } safeClose(client); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDocumentsTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDocumentsTest.java index fd59b372ffe66..83620644114ac 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDocumentsTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDocumentsTest.java @@ -22,17 +22,21 @@ */ package com.microsoft.azure.cosmosdb.rx; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; + +import reactor.core.publisher.Flux; + import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; import java.util.ArrayList; import java.util.List; @@ -41,14 +45,14 @@ public class ReadFeedDocumentsTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdDocuments; + private CosmosDatabase createdDatabase; + private CosmosContainer createdCollection; + private List createdDocuments; - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public ReadFeedDocumentsTest(AsyncDocumentClient.Builder clientBuilder) { + public ReadFeedDocumentsTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -58,12 +62,12 @@ public void readDocuments() { options.setEnableCrossPartitionQuery(true); options.setMaxItemCount(2); - Observable> feedObservable = client.readDocuments(getCollectionLink(), options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + Flux> feedObservable = createdCollection.listItems(options); + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdDocuments.size()) .numberOfPagesIsGreaterThanOrEqualTo(1) .exactlyContainsInAnyOrder(createdDocuments.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0) .pageSizeIsLessThanOrEqualTo(options.getMaxItemCount()) .build()) @@ -76,7 +80,7 @@ public void readDocuments_withoutEnableCrossPartitionQuery() { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - Observable> feedObservable = client.readDocuments(getCollectionLink(), options); + Flux> feedObservable = createdCollection.listItems(options); FailureValidator validator = FailureValidator.builder().instanceOf(DocumentClientException.class) .statusCode(400) .errorMessageContains("Cross partition query is required but disabled." + @@ -90,17 +94,16 @@ public void readDocuments_withoutEnableCrossPartitionQuery() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT, alwaysRun = true) public void beforeClass() { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); - truncateCollection(SHARED_MULTI_PARTITION_COLLECTION); - List docDefList = new ArrayList<>(); + List docDefList = new ArrayList<>(); for(int i = 0; i < 100; i++) { docDefList.add(getDocumentDefinition()); } - createdDocuments = bulkInsertBlocking(client, getCollectionLink(), docDefList); + createdDocuments = bulkInsertBlocking(createdCollection, docDefList); waitIfNeededForReplicasToCatchUp(clientBuilder); } @@ -109,9 +112,9 @@ public void afterClass() { safeClose(client); } - private Document getDocumentDefinition() { + private CosmosItemSettings getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " + CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedExceptionHandlingTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedExceptionHandlingTest.java index 044d2a6e9910c..e6e8327b81146 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedExceptionHandlingTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedExceptionHandlingTest.java @@ -25,84 +25,57 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; -import java.util.concurrent.CountDownLatch; -import com.microsoft.azure.cosmosdb.BridgeInternal; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.mockito.Mockito; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.BridgeUtils; -import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosDatabaseSettings; +import com.microsoft.azure.cosmosdb.BridgeInternal; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.FeedResponse; -import rx.Observable; -import rx.Subscriber; - +import io.reactivex.subscribers.TestSubscriber; +import reactor.core.publisher.Flux; public class ReadFeedExceptionHandlingTest extends TestSuiteBase { - public class ExceptionSubscriber extends Subscriber> { - - public int onNextCount; - CountDownLatch latch = new CountDownLatch(1); - public ExceptionSubscriber() { - onNextCount = 0; - } - - @Override - public void onCompleted() { - latch.countDown(); - } - - @Override - public void onError(Throwable e) { - DocumentClientException exception = (DocumentClientException) e; - assertThat(exception).isNotNull(); - assertThat(exception.getStatusCode()).isEqualTo(0); - latch.countDown(); - } - - @Override - public void onNext(FeedResponse page) { - assertThat(page.getResults().size()).isEqualTo(2); - onNextCount ++; - } - } - - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public ReadFeedExceptionHandlingTest(AsyncDocumentClient.Builder clientBuilder) { + public ReadFeedExceptionHandlingTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readFeedException() throws Exception { - ArrayList dbs = new ArrayList(); - dbs.add(new Database()); - dbs.add(new Database()); + ArrayList dbs = new ArrayList(); + dbs.add(new CosmosDatabaseSettings("db1")); + dbs.add(new CosmosDatabaseSettings("db2")); - ArrayList> frps = new ArrayList>(); + ArrayList> frps = new ArrayList>(); frps.add(BridgeInternal.createFeedResponse(dbs, null)); frps.add(BridgeInternal.createFeedResponse(dbs, null)); - Observable> response = Observable.from(frps) - .concatWith(Observable.error(new DocumentClientException(0))) - .concatWith(Observable.from(frps)); - - final AsyncDocumentClient mockClient = Mockito.spy(client); - Mockito.when(mockClient.readDatabases(null)).thenReturn(response); - ExceptionSubscriber subscriber = new ExceptionSubscriber(); - mockClient.readDatabases(null).subscribe(subscriber); - subscriber.latch.await(); - assertThat(subscriber.onNextCount).isEqualTo(2); + Flux> response = Flux.merge(Flux.fromIterable(frps)) + .mergeWith(Flux.error(new DocumentClientException(0))) + .mergeWith(Flux.fromIterable(frps)); + + final CosmosClient mockClient = Mockito.spy(client); + Mockito.when(mockClient.listDatabases(null)).thenReturn(response); + TestSubscriber> subscriber = new TestSubscriber>(); + mockClient.listDatabases(null).subscribe(subscriber); + assertThat(subscriber.valueCount()).isEqualTo(2); + assertThat(subscriber.assertNotComplete()); + assertThat(subscriber.assertTerminated()); + assertThat(subscriber.errorCount()).isEqualTo(1); } - + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedOffersTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedOffersTest.java index 7b7e46d9dd01d..f4f54e27647a6 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedOffersTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedOffersTest.java @@ -27,23 +27,26 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DatabaseForTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.DatabaseForTest; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.Offer; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import rx.Observable; import javax.net.ssl.SSLException; +//TODO: change to use external TestSuiteBase public class ReadFeedOffersTest extends TestSuiteBase { protected static final int FEED_TIMEOUT = 60000; @@ -108,6 +111,13 @@ public void afterClass() { public DocumentCollection createCollections(AsyncDocumentClient client) { DocumentCollection collection = new DocumentCollection(); collection.setId(UUID.randomUUID().toString()); + + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + collection.setPartitionKey(partitionKeyDef); + return client.createCollection(getDatabaseLink(), collection, null).toBlocking().single().getResource(); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPermissionsTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPermissionsTest.java index 6959a305bd5c0..3fcab18c1e425 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPermissionsTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPermissionsTest.java @@ -27,25 +27,23 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DatabaseForTest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.DatabaseForTest; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.Permission; import com.microsoft.azure.cosmosdb.PermissionMode; import com.microsoft.azure.cosmosdb.User; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import rx.Observable; -import javax.net.ssl.SSLException; - +//TODO: change to use external TestSuiteBase public class ReadFeedPermissionsTest extends TestSuiteBase { public final String databaseId = DatabaseForTest.generateId(); @@ -109,8 +107,6 @@ private static User getUserDefinition() { } public Permission createPermissions(AsyncDocumentClient client, int index) { - DocumentCollection collection = new DocumentCollection(); - collection.setId(UUID.randomUUID().toString()); Permission permission = new Permission(); permission.setId(UUID.randomUUID().toString()); permission.setPermissionMode(PermissionMode.Read); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPkrTests.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPkrTests.java index 6fbd5e74ad5a1..e9207e83b3d87 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPkrTests.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPkrTests.java @@ -22,15 +22,16 @@ */ package com.microsoft.azure.cosmosdb.rx; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import javax.net.ssl.SSLException; - -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmos.CosmosBridgeInternal; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosDatabase; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.PartitionKeyRange; @@ -39,13 +40,13 @@ public class ReadFeedPkrTests extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; + private CosmosDatabase createdDatabase; + private CosmosContainer createdCollection; private AsyncDocumentClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public ReadFeedPkrTests(AsyncDocumentClient.Builder clientBuilder) { + public ReadFeedPkrTests(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -66,17 +67,17 @@ public void readPartitionKeyRanges() throws Exception { @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - createdDatabase = SHARED_DATABASE; - createdCollection = createCollection(createdDatabase.getId(), + client = CosmosBridgeInternal.getAsyncDocumentClient(clientBuilder.build()); + createdDatabase = getSharedCosmosDatabase(clientBuilder.build()); + createdCollection = createCollection(createdDatabase, getCollectionDefinition(), - null); - client = clientBuilder.build(); + new CosmosContainerRequestOptions()); } @AfterClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteCollection(client, createdCollection); - safeClose(client); + safeDeleteCollection(createdCollection); + client.close(); } private String getCollectionLink() { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedStoredProceduresTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedStoredProceduresTest.java index 0f7d2aa156ea3..e0b46a7d8476b 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedStoredProceduresTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedStoredProceduresTest.java @@ -27,32 +27,30 @@ import java.util.UUID; import java.util.stream.Collectors; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosStoredProcedureRequestOptions; +import com.microsoft.azure.cosmos.CosmosStoredProcedureSettings; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import rx.Observable; - -import javax.net.ssl.SSLException; +import reactor.core.publisher.Flux; public class ReadFeedStoredProceduresTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdStoredProcedures = new ArrayList<>(); + private CosmosContainer createdCollection; + private List createdStoredProcedures = new ArrayList<>(); - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public ReadFeedStoredProceduresTest(AsyncDocumentClient.Builder clientBuilder) { + public ReadFeedStoredProceduresTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -62,19 +60,19 @@ public void readStoredProcedures() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - Observable> feedObservable = client.readStoredProcedures(getCollectionLink(), options); + Flux> feedObservable = createdCollection.listStoredProcedures(options); int expectedPageSize = (createdStoredProcedures.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .totalSize(createdStoredProcedures.size()) .exactlyContainsInAnyOrder(createdStoredProcedures .stream() .map(d -> d.getResourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -83,12 +81,11 @@ public void readStoredProcedures() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); for(int i = 0; i < 5; i++) { - createdStoredProcedures.add(createStoredProcedures(client)); + createdStoredProcedures.add(createStoredProcedures(createdCollection)); } waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -99,22 +96,10 @@ public void afterClass() { safeClose(client); } - public StoredProcedure createStoredProcedures(AsyncDocumentClient client) { - StoredProcedure sproc = new StoredProcedure(); + public CosmosStoredProcedureSettings createStoredProcedures(CosmosContainer cosmosContainer) { + CosmosStoredProcedureSettings sproc = new CosmosStoredProcedureSettings(); sproc.setId(UUID.randomUUID().toString()); sproc.setBody("function() {var x = 10;}"); - return client.createStoredProcedure(getCollectionLink(), sproc, null).toBlocking().single().getResource(); - } - - private String getCollectionLink() { - return "dbs/" + getDatabaseId() + "/colls/" + getCollectionId(); - } - - private String getCollectionId() { - return createdCollection.getId(); - } - - private String getDatabaseId() { - return createdDatabase.getId(); + return cosmosContainer.createStoredProcedure(sproc, new CosmosStoredProcedureRequestOptions()).block().getStoredProcedureSettings(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedTriggersTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedTriggersTest.java index 2b2c407807182..406f3033b186f 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedTriggersTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedTriggersTest.java @@ -27,32 +27,32 @@ import java.util.UUID; import java.util.stream.Collectors; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosRequestOptions; +import com.microsoft.azure.cosmos.CosmosTriggerSettings; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Trigger; import com.microsoft.azure.cosmosdb.TriggerOperation; import com.microsoft.azure.cosmosdb.TriggerType; -import rx.Observable; +import reactor.core.publisher.Flux; public class ReadFeedTriggersTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdTriggers = new ArrayList<>(); + private CosmosContainer createdCollection; + private List createdTriggers = new ArrayList<>(); - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public ReadFeedTriggersTest(AsyncDocumentClient.Builder clientBuilder) { + public ReadFeedTriggersTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -62,19 +62,19 @@ public void readTriggers() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - Observable> feedObservable = client.readTriggers(getCollectionLink(), options); + Flux> feedObservable = createdCollection.listTriggers(options); int expectedPageSize = (createdTriggers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .totalSize(createdTriggers.size()) .exactlyContainsInAnyOrder(createdTriggers .stream() .map(d -> d.getResourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -82,17 +82,15 @@ public void readTriggers() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - - this.client = clientBuilder.build(); - this.createdDatabase = SHARED_DATABASE; - this.createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - this.truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + client = clientBuilder.build(); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); for(int i = 0; i < 5; i++) { - this.createdTriggers.add(this.createTriggers(client)); + this.createdTriggers.add(this.createTriggers(createdCollection)); } - this.waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) @@ -100,24 +98,12 @@ public void afterClass() { safeClose(client); } - public Trigger createTriggers(AsyncDocumentClient client) { - Trigger trigger = new Trigger(); + public CosmosTriggerSettings createTriggers(CosmosContainer cosmosContainer) { + CosmosTriggerSettings trigger = new CosmosTriggerSettings(); trigger.setId(UUID.randomUUID().toString()); trigger.setBody("function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.Create); trigger.setTriggerType(TriggerType.Pre); - return client.createTrigger(getCollectionLink(), trigger, null).toBlocking().single().getResource(); - } - - private String getCollectionLink() { - return "dbs/" + getDatabaseId() + "/colls/" + getCollectionId(); - } - - private String getCollectionId() { - return createdCollection.getId(); - } - - private String getDatabaseId() { - return createdDatabase.getId(); + return cosmosContainer.createTrigger(trigger, new CosmosRequestOptions()).block().getCosmosTriggerSettings(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUdfsTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUdfsTest.java index 4bd2ccbbbfdec..9e5fe1c2a5de1 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUdfsTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUdfsTest.java @@ -27,32 +27,32 @@ import java.util.UUID; import java.util.stream.Collectors; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosRequestOptions; +import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionSettings; import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import rx.Observable; - -import javax.net.ssl.SSLException; +import reactor.core.publisher.Flux; public class ReadFeedUdfsTest extends TestSuiteBase { private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdUserDefinedFunctions = new ArrayList<>(); + private CosmosContainer createdCollection; + private List createdUserDefinedFunctions = new ArrayList<>(); - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public ReadFeedUdfsTest(AsyncDocumentClient.Builder clientBuilder) { + public ReadFeedUdfsTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -62,19 +62,19 @@ public void readUserDefinedFunctions() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - Observable> feedObservable = client.readUserDefinedFunctions(getCollectionLink(), options); + Flux> feedObservable = createdCollection.listUserDefinedFunctions(options); int expectedPageSize = (createdUserDefinedFunctions.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .totalSize(createdUserDefinedFunctions.size()) .exactlyContainsInAnyOrder(createdUserDefinedFunctions .stream() .map(d -> d.getResourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -83,12 +83,11 @@ public void readUserDefinedFunctions() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); for(int i = 0; i < 5; i++) { - createdUserDefinedFunctions.add(createUserDefinedFunctions(client)); + createdUserDefinedFunctions.add(createUserDefinedFunctions(createdCollection)); } waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -99,11 +98,11 @@ public void afterClass() { safeClose(client); } - public UserDefinedFunction createUserDefinedFunctions(AsyncDocumentClient client) { - UserDefinedFunction udf = new UserDefinedFunction(); + public CosmosUserDefinedFunctionSettings createUserDefinedFunctions(CosmosContainer cosmosContainer) { + CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); - return client.createUserDefinedFunction(getCollectionLink(), udf, null).toBlocking().single().getResource(); + return cosmosContainer.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().getCosmosUserDefinedFunctionSettings(); } private String getCollectionLink() { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUsersTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUsersTest.java index 68186ec977d5c..f7e62b47932d7 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUsersTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUsersTest.java @@ -27,32 +27,32 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DatabaseForTest; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosUserSettings; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.User; +import com.microsoft.azure.cosmosdb.RequestOptions; -import rx.Observable; - -import javax.net.ssl.SSLException; +import reactor.core.publisher.Flux; public class ReadFeedUsersTest extends TestSuiteBase { - public final String databaseId = DatabaseForTest.generateId(); - private Database createdDatabase; + public final String databaseId = CosmosDatabaseForTest.generateId(); + private CosmosDatabase createdDatabase; - private AsyncDocumentClient client; - private List createdUsers = new ArrayList<>(); + private CosmosClient client; + private List createdUsers = new ArrayList<>(); @Factory(dataProvider = "clientBuilders") - public ReadFeedUsersTest(AsyncDocumentClient.Builder clientBuilder) { + public ReadFeedUsersTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -62,15 +62,15 @@ public void readUsers() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); - Observable> feedObservable = client.readUsers(getDatabaseLink(), options); + Flux> feedObservable = createdDatabase.listUsers(options); int expectedPageSize = (createdUsers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdUsers.size()) .exactlyContainsInAnyOrder(createdUsers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -79,12 +79,10 @@ public void readUsers() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - Database d = new Database(); - d.setId(databaseId); - createdDatabase = createDatabase(client, d); + createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { - createdUsers.add(createUsers(client)); + createdUsers.add(createUsers(createdDatabase)); } waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -92,17 +90,13 @@ public void beforeClass() { @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteDatabase(client, createdDatabase.getId()); + safeDeleteDatabase(createdDatabase); safeClose(client); } - public User createUsers(AsyncDocumentClient client) { - User user = new User(); + public CosmosUserSettings createUsers(CosmosDatabase cosmosDatabase) { + CosmosUserSettings user = new CosmosUserSettings(); user.setId(UUID.randomUUID().toString()); - return client.createUser(getDatabaseLink(), user, null).toBlocking().single().getResource(); - } - - private String getDatabaseLink() { - return "dbs/" + createdDatabase.getId(); + return cosmosDatabase.createUser(user, new RequestOptions()).block().getCosmosUserSettings(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ResourceTokenTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ResourceTokenTest.java index c5587f7b74820..83c94f829934e 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ResourceTokenTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ResourceTokenTest.java @@ -47,6 +47,7 @@ import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.ResourceResponse; import com.microsoft.azure.cosmosdb.User; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import rx.Observable; @@ -55,6 +56,8 @@ * resources from resource token directly or via permission feed . * */ + +// TODO: change to use external TestSuiteBase public class ResourceTokenTest extends TestSuiteBase { public final String databaseId = DatabaseForTest.generateId(); @@ -84,7 +87,8 @@ public class ResourceTokenTest extends TestSuiteBase { private final static String DOCUMENT_DEFINITION = "{ 'id': 'doc%d', 'counter': '%d'}"; private final static String DOCUMENT_DEFINITION_WITH_PERMISSION_KEY = "{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}"; - private final static String PARTITION_KEY_PATH = "/mypk"; + private final static String PARTITION_KEY_PATH_1 = "/mypk"; + private final static String PARTITION_KEY_PATH_2 = "/mypk2"; private static final String PARTITION_KEY_VALUE = "1"; private static final String PARTITION_KEY_VALUE_2 = "2"; @@ -110,11 +114,11 @@ public void beforeClass() throws Exception { d.setId(databaseId); createdDatabase = createDatabase(client, d); // Create collection - createdCollection = createCollection(client, createdDatabase.getId(), getCollectionDefinition()); + createdCollection = createCollection(client, createdDatabase.getId(), getCollectionDefinitionWithPartitionKey(PARTITION_KEY_PATH_2)); // Create document createdDocument = createDocument(client, createdDatabase.getId(),createdCollection.getId(), getDocument()); // Create collection with partition key - createdCollectionWithPartitionKey = createCollection(client, createdDatabase.getId(), getCollectionDefinitionWithPartitionKey()); + createdCollectionWithPartitionKey = createCollection(client, createdDatabase.getId(), getCollectionDefinitionWithPartitionKey(PARTITION_KEY_PATH_1)); // Create document with partition key createdDocumentWithPartitionKey = createDocument(client, createdDatabase.getId(), createdCollectionWithPartitionKey.getId(), getDocumentDefinitionWithPartitionKey()); @@ -281,10 +285,11 @@ public void readDocumentFromPermissionFeed(String documentUrl, Permission permis asyncClientResourceToken = new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withPermissionFeed(permissionFeed).withConnectionPolicy(ConnectionPolicy.GetDefault()) .withConsistencyLevel(ConsistencyLevel.Session).build(); - RequestOptions options = null; - if(StringUtils.isNotEmpty(partitionKey)) { - options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(partitionKey)); + RequestOptions options = new RequestOptions(); + if (StringUtils.isNotEmpty(partitionKey)) { + options.setPartitionKey(new PartitionKey((String)partitionKey)); + } else { + options.setPartitionKey(PartitionKey.None); } Observable> readObservable = asyncClientResourceToken .readDocument(documentUrl, options); @@ -309,8 +314,10 @@ public void readDocumentFromResouceToken(String resourceToken) throws Exception .withMasterKeyOrResourceToken(resourceToken) .withConnectionPolicy(ConnectionPolicy.GetDefault()).withConsistencyLevel(ConsistencyLevel.Session) .build(); + RequestOptions options = new RequestOptions(); + options.setPartitionKey(PartitionKey.None); Observable> readObservable = asyncClientResourceToken - .readDocument(createdDocument.getSelfLink(), null); + .readDocument(createdDocument.getSelfLink(), options); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .withId(createdDocument.getId()).build(); validateSuccess(readObservable, validator); @@ -515,12 +522,6 @@ private String getUserLink() { return createdUser.getSelfLink(); } - static protected DocumentCollection getCollectionDefinition() { - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); - return collectionDefinition; - } - private Document getDocumentDefinitionWithPartitionKey() { String uuid = UUID.randomUUID().toString(); Document doc = new Document(String.format(DOCUMENT_DEFINITION_WITH_PERMISSION_KEY, uuid, PARTITION_KEY_VALUE)); @@ -532,10 +533,10 @@ private Document getDocumentDefinitionWithPartitionKey2() { return doc; } - private DocumentCollection getCollectionDefinitionWithPartitionKey() { + private DocumentCollection getCollectionDefinitionWithPartitionKey(String pkDefPath) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); - paths.add(PARTITION_KEY_PATH); + paths.add(pkDefPath); partitionKeyDef.setPaths(paths); DocumentCollection collectionDefinition = new DocumentCollection(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SimpleSerializationTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SimpleSerializationTest.java index 338f5b7004c70..18ae2b0e59784 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SimpleSerializationTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SimpleSerializationTest.java @@ -24,31 +24,29 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmos.CosmosContainer; + import org.apache.commons.lang3.NotImplementedException; +import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; -import java.io.IOException; -import java.time.Instant; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; public class SimpleSerializationTest extends TestSuiteBase { - private DocumentCollection createdCollection; - private AsyncDocumentClient client; + private CosmosContainer createdCollection; + private CosmosClient client; private static class TestObject { public static class BadSerializer extends JsonSerializer { @@ -70,39 +68,35 @@ public void serialize(String value, JsonGenerator gen, SerializerProvider serial } @Factory(dataProvider = "clientBuildersWithDirect") - public SimpleSerializationTest(Builder clientBuilder) { + public SimpleSerializationTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @Test(groups = {"simple"}, timeOut = TIMEOUT) - public void createDocument() { + public void createDocument() throws InterruptedException { TestObject testObject = new TestObject(); testObject.id = UUID.randomUUID().toString(); testObject.mypk = UUID.randomUUID().toString(); testObject.prop = UUID.randomUUID().toString(); - Observable> createObservable = client - .createDocument(getCollectionLink(), testObject, null, false); - - FailureValidator failureValidator = FailureValidator.builder().instanceOf(IllegalArgumentException.class) - .causeOfCauseInstanceOf(NotImplementedException.class) - .errorMessageContains("Can't serialize the object into the json string").build(); - - validateFailure(createObservable, failureValidator); + try { + createdCollection.createItem(testObject); + Assert.fail(); + } catch (IllegalArgumentException e) { + assertThat(e.getMessage()).contains("Can't serialize the object into the json string"); + assertThat(e.getCause()).isInstanceOf(JsonMappingException.class); + assertThat(e.getCause().getMessage()).contains("bad"); + } } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; client = clientBuilder.build(); + createdCollection = getSharedMultiPartitionCosmosContainer(client); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } - - private String getCollectionLink() { - return createdCollection.getSelfLink(); - } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionDocumentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionDocumentQueryTest.java index fdca1855021f9..e2b5e4fa43d46 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionDocumentQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionDocumentQueryTest.java @@ -25,49 +25,48 @@ import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import com.microsoft.azure.cosmosdb.SqlParameter; import com.microsoft.azure.cosmosdb.SqlParameterCollection; import com.microsoft.azure.cosmosdb.SqlQuerySpec; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; + +import io.reactivex.subscribers.TestSubscriber; +import reactor.core.publisher.Flux; + import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; - -import rx.Observable; -import rx.observers.TestSubscriber; - public class SinglePartitionDocumentQueryTest extends TestSuiteBase { private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdDocuments = new ArrayList<>(); + private CosmosContainer createdCollection; + private List createdDocuments = new ArrayList<>(); - private AsyncDocumentClient client; + private CosmosClient client; public String getCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); } @Factory(dataProvider = "clientBuildersWithDirect") - public SinglePartitionDocumentQueryTest(Builder clientBuilder) { + public SinglePartitionDocumentQueryTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -78,20 +77,20 @@ public void queryDocuments(boolean queryMetricsEnabled) throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(5); + options.setEnableCrossPartitionQuery(true); options.setPopulateQueryMetrics(queryMetricsEnabled); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments.stream().filter(d -> 99 == d.getInt("prop") ).collect(Collectors.toList()); + List expectedDocs = createdDocuments.stream().filter(d -> 99 == d.getInt("prop") ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .hasValidQueryMetrics(queryMetricsEnabled) .build(); @@ -99,8 +98,8 @@ public void queryDocuments(boolean queryMetricsEnabled) throws Exception { try { validateQuerySuccess(queryObservable, validator, 10000); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -116,27 +115,27 @@ public void queryDocuments_ParameterizedQueryWithInClause() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(5); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), sqs, options); + options.setEnableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(sqs, options); - List expectedDocs = createdDocuments.stream().filter(d -> (3 == d.getInt("prop") || 4 == d.getInt("prop"))).collect(Collectors.toList()); + List expectedDocs = createdDocuments.stream().filter(d -> (3 == d.getInt("prop") || 4 == d.getInt("prop"))).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); try { validateQuerySuccess(queryObservable, validator, 10000); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -152,27 +151,27 @@ public void queryDocuments_ParameterizedQuery() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(5); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), sqs, options); + options.setEnableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(sqs, options); - List expectedDocs = createdDocuments.stream().filter(d -> 3 == d.getInt("prop")).collect(Collectors.toList()); + List expectedDocs = createdDocuments.stream().filter(d -> 3 == d.getInt("prop")).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); try { validateQuerySuccess(queryObservable, validator, 10000); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -186,13 +185,12 @@ public void queryDocuments_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -205,28 +203,27 @@ public void queryDocumentsWithPageSize() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(3); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments; + List expectedDocs = createdDocuments; int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .exactlyContainsInAnyOrder(createdDocuments .stream() .map(d -> d.getResourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); try { validateQuerySuccess(queryObservable, validator); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -241,26 +238,25 @@ public void queryOrderBy() throws Exception { FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); options.setMaxItemCount(3); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments; + List expectedDocs = createdDocuments; int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(createdDocuments.stream() .sorted((e1, e2) -> Integer.compare(e1.getInt("prop"), e2.getInt("prop"))) .map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); try { validateQuerySuccess(queryObservable, validator); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -274,39 +270,35 @@ public void continuationToken() throws Exception { FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); options.setMaxItemCount(3); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); - + Flux> queryObservable = createdCollection.queryItems(query, options); - TestSubscriber> subscriber = new TestSubscriber<>(); - queryObservable.first().subscribe(subscriber); + TestSubscriber> subscriber = new TestSubscriber<>(); + queryObservable.take(1).subscribe(subscriber); subscriber.awaitTerminalEvent(); - subscriber.assertCompleted(); + subscriber.assertComplete(); subscriber.assertNoErrors(); - assertThat(subscriber.getValueCount()).isEqualTo(1); - FeedResponse page = subscriber.getOnNextEvents().get(0); + assertThat(subscriber.valueCount()).isEqualTo(1); + FeedResponse page = ((FeedResponse) subscriber.getEvents().get(0).get(0)); assertThat(page.getResults()).hasSize(3); assertThat(page.getResponseContinuation()).isNotEmpty(); options.setRequestContinuation(page.getResponseContinuation()); - queryObservable = client - .queryDocuments(getCollectionLink(), query, options); - + queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments.stream().filter(d -> (d.getInt("prop") > 2)).collect(Collectors.toList()); + List expectedDocs = createdDocuments.stream().filter(d -> (d.getInt("prop") > 2)).collect(Collectors.toList()); int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); assertThat(expectedDocs).hasSize(createdDocuments.size() -3); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(expectedDocs.stream() .sorted((e1, e2) -> Integer.compare(e1.getInt("prop"), e2.getInt("prop"))) .map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -317,8 +309,7 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryDocuments(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(DocumentClientException.class) @@ -328,24 +319,23 @@ public void invalidQuerySytax() throws Exception { validateQueryFailure(queryObservable, validator); } - public Document createDocument(AsyncDocumentClient client, int cnt) { - Document docDefinition = getDocumentDefinition(cnt); - return client.createDocument(getCollectionLink(), docDefinition, null, false).toBlocking().single().getResource(); + public CosmosItemSettings createDocument(CosmosContainer cosmosContainer, int cnt) { + CosmosItemSettings docDefinition = getDocumentDefinition(cnt); + return cosmosContainer.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItemSettings(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + createdCollection = getSharedSinglePartitionCosmosContainer(client); + truncateCollection(createdCollection); for(int i = 0; i < 5; i++) { - createdDocuments.add(createDocument(client, i)); + createdDocuments.add(createDocument(createdCollection, i)); } for(int i = 0; i < 8; i++) { - createdDocuments.add(createDocument(client, 99)); + createdDocuments.add(createDocument(createdCollection, 99)); } waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -356,9 +346,9 @@ public void afterClass() { safeClose(client); } - private static Document getDocumentDefinition(int cnt) { + private static CosmosItemSettings getDocumentDefinition(int cnt) { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " + CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + "\"id\": \"%s\", " + "\"prop\" : %d, " + "\"mypk\": \"%s\", " diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionReadFeedDocumentsTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionReadFeedDocumentsTest.java index 6ea1db1f0c3b1..df1d077dc382f 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionReadFeedDocumentsTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionReadFeedDocumentsTest.java @@ -22,16 +22,19 @@ */ package com.microsoft.azure.cosmosdb.rx; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; + +import reactor.core.publisher.Flux; + import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; import java.util.ArrayList; import java.util.List; @@ -39,29 +42,30 @@ import java.util.stream.Collectors; public class SinglePartitionReadFeedDocumentsTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdDocuments; - private AsyncDocumentClient client; + private CosmosContainer createdCollection; + private List createdDocuments; + + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public SinglePartitionReadFeedDocumentsTest(AsyncDocumentClient.Builder clientBuilder) { + public SinglePartitionReadFeedDocumentsTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) public void readDocuments() { final FeedOptions options = new FeedOptions(); + options.setEnableCrossPartitionQuery(true); options.setMaxItemCount(2); - final Observable> feedObservable = client.readDocuments(getCollectionLink(), options); + final Flux> feedObservable = createdCollection.listItems(options); final int expectedPageSize = (createdDocuments.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdDocuments.size()) .numberOfPages(expectedPageSize) .exactlyContainsInAnyOrder(createdDocuments.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -70,17 +74,16 @@ public void readDocuments() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + createdCollection = getSharedSinglePartitionCosmosContainer(client); + truncateCollection(createdCollection); - List docDefList = new ArrayList<>(); + List docDefList = new ArrayList<>(); for(int i = 0; i < 5; i++) { docDefList.add(getDocumentDefinition()); } - createdDocuments = bulkInsertBlocking(client, getCollectionLink(), docDefList); + createdDocuments = bulkInsertBlocking(createdCollection, docDefList); waitIfNeededForReplicasToCatchUp(clientBuilder); } @@ -89,9 +92,9 @@ public void afterClass() { safeClose(client); } - private Document getDocumentDefinition() { + private CosmosItemSettings getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " + CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" @@ -99,16 +102,4 @@ private Document getDocumentDefinition() { , uuid, uuid)); return doc; } - - public String getCollectionLink() { - return "dbs/" + getDatabaseId() + "/colls/" + getCollectionId(); - } - - private String getCollectionId() { - return createdCollection.getId(); - } - - private String getDatabaseId() { - return createdDatabase.getId(); - } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureCrudTest.java index e963d5322d5a9..df2b779d0a066 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureCrudTest.java @@ -24,28 +24,31 @@ import java.util.UUID; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.StoredProcedure; - -import rx.Observable; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosResponse; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmos.CosmosStoredProcedure; +import com.microsoft.azure.cosmos.CosmosStoredProcedureRequestOptions; +import com.microsoft.azure.cosmos.CosmosStoredProcedureResponse; +import com.microsoft.azure.cosmos.CosmosStoredProcedureSettings; +import reactor.core.publisher.Mono; public class StoredProcedureCrudTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; + private CosmosContainer createdCollection; - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public StoredProcedureCrudTest(AsyncDocumentClient.Builder clientBuilder) { + public StoredProcedureCrudTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -53,14 +56,14 @@ public StoredProcedureCrudTest(AsyncDocumentClient.Builder clientBuilder) { public void createStoredProcedure() throws Exception { // create a stored procedure - StoredProcedure storedProcedureDef = new StoredProcedure(); + CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); storedProcedureDef.setId(UUID.randomUUID().toString()); storedProcedureDef.setBody("function() {var x = 10;}"); - Observable> createObservable = client.createStoredProcedure(getCollectionLink(), storedProcedureDef, null); + Mono createObservable = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()); // validate stored procedure creation - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(storedProcedureDef.getId()) .withStoredProcedureBody("function() {var x = 10;}") .notNullEtag() @@ -71,16 +74,17 @@ public void createStoredProcedure() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readStoredProcedure() throws Exception { // create a stored procedure - StoredProcedure storedProcedureDef = new StoredProcedure(); + CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); storedProcedureDef.setId(UUID.randomUUID().toString()); storedProcedureDef.setBody("function() {var x = 10;}"); - StoredProcedure storedProcedure = client.createStoredProcedure(getCollectionLink(), storedProcedureDef, null).toBlocking().single().getResource(); + CosmosStoredProcedure storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()) + .block().getStoredProcedure(); // read stored procedure waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readStoredProcedure(storedProcedure.getSelfLink(), null); + Mono readObservable = storedProcedure.read(null); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(storedProcedureDef.getId()) .withStoredProcedureBody("function() {var x = 10;}") .notNullEtag() @@ -91,16 +95,17 @@ public void readStoredProcedure() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteStoredProcedure() throws Exception { // create a stored procedure - StoredProcedure storedProcedureDef = new StoredProcedure(); + CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); storedProcedureDef.setId(UUID.randomUUID().toString()); storedProcedureDef.setBody("function() {var x = 10;}"); - StoredProcedure storedProcedure = client.createStoredProcedure(getCollectionLink(), storedProcedureDef, null).toBlocking().single().getResource(); + CosmosStoredProcedure storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()) + .block().getStoredProcedure(); // delete - Observable> deleteObservable = client.deleteStoredProcedure(storedProcedure.getSelfLink(), null); + Mono deleteObservable = storedProcedure.delete(new CosmosStoredProcedureRequestOptions()); // validate - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .nullResource() .build(); validateSuccess(deleteObservable, validator); @@ -108,7 +113,7 @@ public void deleteStoredProcedure() throws Exception { // attempt to read stored procedure which was deleted waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readStoredProcedure(storedProcedure.getSelfLink(), null); + Mono readObservable = storedProcedure.read(null); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); validateFailure(readObservable, notFoundValidator); } @@ -116,16 +121,11 @@ public void deleteStoredProcedure() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION; + createdCollection = getSharedMultiPartitionCosmosContainer(client); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } - - private String getCollectionLink() { - return createdCollection.getSelfLink(); - } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureQueryTest.java index c10eb81aaf6e8..acdbdb61ebedc 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureQueryTest.java @@ -29,39 +29,33 @@ import java.util.UUID; import java.util.stream.Collectors; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; + +import reactor.core.publisher.Flux; + import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosStoredProcedureSettings; import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; - -import rx.Observable; - public class StoredProcedureQueryTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdStoredProcs = new ArrayList<>(); - - private AsyncDocumentClient client; + private CosmosContainer createdCollection; + private List createdStoredProcs = new ArrayList<>(); - public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); - } + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public StoredProcedureQueryTest(Builder clientBuilder) { + public StoredProcedureQueryTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -73,27 +67,26 @@ public void queryWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(5); - Observable> queryObservable = client - .queryStoredProcedures(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); - List expectedDocs = createdStoredProcs.stream().filter(sp -> filterId.equals(sp.getId()) ).collect(Collectors.toList()); + List expectedDocs = createdStoredProcs.stream().filter(sp -> filterId.equals(sp.getId()) ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); try { validateQuerySuccess(queryObservable, validator, 10000); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -107,13 +100,12 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryStoredProcedures(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -126,29 +118,28 @@ public void queryAll() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(3); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryStoredProcedures(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); - List expectedDocs = createdStoredProcs; + List expectedDocs = createdStoredProcs; int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() .map(d -> d.getResourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); try { validateQuerySuccess(queryObservable, validator); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -161,8 +152,7 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryStoredProcedures(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(DocumentClientException.class) @@ -172,20 +162,19 @@ public void invalidQuerySytax() throws Exception { validateQueryFailure(queryObservable, validator); } - public StoredProcedure createStoredProc(AsyncDocumentClient client) { - StoredProcedure storedProcedure = getStoredProcedureDef(); - return client.createStoredProcedure(getCollectionLink(), storedProcedure, null).toBlocking().single().getResource(); + public CosmosStoredProcedureSettings createStoredProc(CosmosContainer cosmosContainer) { + CosmosStoredProcedureSettings storedProcedure = getStoredProcedureDef(); + return cosmosContainer.createStoredProcedure(storedProcedure).block().getStoredProcedureSettings(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); for(int i = 0; i < 5; i++) { - createdStoredProcs.add(createStoredProc(client)); + createdStoredProcs.add(createStoredProc(createdCollection)); } waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -196,8 +185,8 @@ public void afterClass() { safeClose(client); } - private static StoredProcedure getStoredProcedureDef() { - StoredProcedure storedProcedureDef = new StoredProcedure(); + private static CosmosStoredProcedureSettings getStoredProcedureDef() { + CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); storedProcedureDef.setId(UUID.randomUUID().toString()); storedProcedureDef.setBody("function() {var x = 10;}"); return storedProcedureDef; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureUpsertReplaceTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureUpsertReplaceTest.java index 62870762d1b34..00fc53360ed12 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureUpsertReplaceTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureUpsertReplaceTest.java @@ -26,86 +26,53 @@ import java.util.UUID; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; + +import reactor.core.publisher.Mono; + import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; - -import rx.Observable; - -import javax.net.ssl.SSLException; - +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmos.CosmosStoredProcedure; +import com.microsoft.azure.cosmos.CosmosStoredProcedureRequestOptions; +import com.microsoft.azure.cosmos.CosmosStoredProcedureResponse; +import com.microsoft.azure.cosmos.CosmosStoredProcedureSettings; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.RequestOptions; public class StoredProcedureUpsertReplaceTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; + private CosmosContainer createdCollection; - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public StoredProcedureUpsertReplaceTest(AsyncDocumentClient.Builder clientBuilder) { + public StoredProcedureUpsertReplaceTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void upsertStoredProcedure() throws Exception { - - // create a stored procedure - StoredProcedure storedProcedureDef = new StoredProcedure(); - storedProcedureDef.setId(UUID.randomUUID().toString()); - storedProcedureDef.setBody("function() {var x = 10;}"); - StoredProcedure readBackSp = client.upsertStoredProcedure(getCollectionLink(), storedProcedureDef, null).toBlocking().single().getResource(); - - //read back stored procedure - waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readStoredProcedure(readBackSp.getSelfLink(), null); - - // validate stored procedure creation - ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() - .withId(readBackSp.getId()) - .withStoredProcedureBody("function() {var x = 10;}") - .notNullEtag() - .build(); - validateSuccess(readObservable, validatorForRead); - - //update stored procedure - readBackSp.setBody("function() {var x = 11;}"); - - Observable> updateObservable = client.upsertStoredProcedure(getCollectionLink(), readBackSp, null); - - // validate stored procedure update - ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() - .withId(readBackSp.getId()) - .withStoredProcedureBody("function() {var x = 11;}") - .notNullEtag() - .build(); - validateSuccess(updateObservable, validatorForUpdate); - } - @Test(groups = { "simple" }, timeOut = TIMEOUT) public void replaceStoredProcedure() throws Exception { // create a stored procedure - StoredProcedure storedProcedureDef = new StoredProcedure(); + CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); storedProcedureDef.setId(UUID.randomUUID().toString()); - storedProcedureDef.setBody("function() {var x = 10;}"); - StoredProcedure readBackSp = client.createStoredProcedure(getCollectionLink(), storedProcedureDef, null).toBlocking().single().getResource(); + storedProcedureDef.setBody("function() {var x = 10;}"); + CosmosStoredProcedureSettings readBackSp = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().getStoredProcedureSettings(); // read stored procedure to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readStoredProcedure(readBackSp.getSelfLink(), null); + Mono readObservable = createdCollection.getStoredProcedure(readBackSp.getId()).read(null); // validate stored procedure creation - ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() + CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() .withId(readBackSp.getId()) .withStoredProcedureBody("function() {var x = 10;}") .notNullEtag() @@ -115,10 +82,10 @@ public void replaceStoredProcedure() throws Exception { //update stored procedure readBackSp.setBody("function() {var x = 11;}"); - Observable> replaceObservable = client.replaceStoredProcedure(readBackSp, null); + Mono replaceObservable = createdCollection.getStoredProcedure(readBackSp.getId()).replace(readBackSp, new RequestOptions()); //validate stored procedure replace - ResourceResponseValidator validatorForReplace = new ResourceResponseValidator.Builder() + CosmosResponseValidator validatorForReplace = new CosmosResponseValidator.Builder() .withId(readBackSp.getId()) .withStoredProcedureBody("function() {var x = 11;}") .notNullEtag() @@ -129,7 +96,7 @@ public void replaceStoredProcedure() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void executeStoredProcedure() throws Exception { // create a stored procedure - StoredProcedure storedProcedureDef = new StoredProcedure( + CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings( "{" + " 'id': '" +UUID.randomUUID().toString() + "'," + " 'body':" + @@ -140,13 +107,13 @@ public void executeStoredProcedure() throws Exception { " }'" + "}"); - StoredProcedure storedProcedure = null; + CosmosStoredProcedure storedProcedure = null; try { - storedProcedure = client.createStoredProcedure(getCollectionLink(), storedProcedureDef, null).toBlocking().single().getResource(); + storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().getStoredProcedure(); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -156,10 +123,12 @@ public void executeStoredProcedure() throws Exception { String result = null; try { - result = client.executeStoredProcedure(storedProcedure.getSelfLink(), null).toBlocking().single().getResponseAsString(); + RequestOptions options = new RequestOptions(); + options.setPartitionKey(PartitionKey.None); + result = storedProcedure.execute(null, options).block().getResponseAsString(); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -172,17 +141,11 @@ public void executeStoredProcedure() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; + createdCollection = getSharedMultiPartitionCosmosContainer(client); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } - - private String getCollectionLink() { - return createdCollection.getSelfLink(); - } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java index 546061b827855..ceb94dabf8877 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java @@ -41,18 +41,23 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.DatabaseForTest; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.IncludedPath; import com.microsoft.azure.cosmosdb.Index; import com.microsoft.azure.cosmosdb.IndexingPolicy; import com.microsoft.azure.cosmosdb.RetryOptions; import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.Undefined; import com.microsoft.azure.cosmosdb.internal.PathParser; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; import com.microsoft.azure.cosmosdb.rx.internal.Configs; + +import io.reactivex.subscribers.TestSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import rx.Observable; + import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.mockito.stubbing.Answer; @@ -64,27 +69,35 @@ import org.testng.annotations.BeforeSuite; import org.testng.annotations.DataProvider; +import com.microsoft.azure.cosmos.CosmosBridgeInternal; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseResponse; +import com.microsoft.azure.cosmos.CosmosDatabaseSettings; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemSettings; +import com.microsoft.azure.cosmos.CosmosRequestOptions; +import com.microsoft.azure.cosmos.CosmosResponse; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmos.CosmosUser; +import com.microsoft.azure.cosmos.CosmosUserSettings; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; import com.microsoft.azure.cosmosdb.CompositePath; import com.microsoft.azure.cosmosdb.CompositePathSortOrder; import com.microsoft.azure.cosmosdb.ConnectionMode; import com.microsoft.azure.cosmosdb.ConnectionPolicy; import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.PartitionKey; import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.Resource; import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import org.testng.annotations.Test; -import rx.Observable; -import rx.observers.TestSubscriber; public class TestSuiteBase { private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; @@ -106,13 +119,28 @@ public class TestSuiteBase { private static final ImmutableList protocols; protected int subscriberValidationTimeout = TIMEOUT; - protected Builder clientBuilder; + protected CosmosClientBuilder clientBuilder; - protected static Database SHARED_DATABASE; - protected static DocumentCollection SHARED_MULTI_PARTITION_COLLECTION; - protected static DocumentCollection SHARED_SINGLE_PARTITION_COLLECTION; - protected static DocumentCollection SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - protected static DocumentCollection SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES; + private static CosmosDatabase SHARED_DATABASE; + private static CosmosContainer SHARED_MULTI_PARTITION_COLLECTION; + private static CosmosContainer SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES; + private static CosmosContainer SHARED_SINGLE_PARTITION_COLLECTION; + + protected static CosmosDatabase getSharedCosmosDatabase(CosmosClient client) { + return CosmosBridgeInternal.getCosmosDatabaseWithNewClient(SHARED_DATABASE, client); + } + + protected static CosmosContainer getSharedMultiPartitionCosmosContainer(CosmosClient client) { + return CosmosBridgeInternal.getCosmosContainerWithNewClient(SHARED_MULTI_PARTITION_COLLECTION, SHARED_DATABASE, client); + } + + protected static CosmosContainer getSharedMultiPartitionCosmosContainerWithCompositeAndSpatialIndexes(CosmosClient client) { + return CosmosBridgeInternal.getCosmosContainerWithNewClient(SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES, SHARED_DATABASE, client); + } + + protected static CosmosContainer getSharedSinglePartitionCosmosContainer(CosmosClient client) { + return CosmosBridgeInternal.getCosmosContainerWithNewClient(SHARED_SINGLE_PARTITION_COLLECTION, SHARED_DATABASE, client); + } static { accountConsistency = parseConsistency(TestConfigurations.CONSISTENCY); @@ -141,9 +169,9 @@ public void beforeMethod(Method method) { if (this.clientBuilder != null) { logger.info("Starting {}::{} using {} {} mode with {} consistency", method.getDeclaringClass().getSimpleName(), method.getName(), - this.clientBuilder.connectionPolicy.getConnectionMode(), - this.clientBuilder.configs.getProtocol(), - this.clientBuilder.desiredConsistencyLevel); + this.clientBuilder.getConnectionPolicy().getConnectionMode(), + this.clientBuilder.getConfigs().getProtocol(), + this.clientBuilder.getDesiredConsistencyLevel()); return; } logger.info("Starting {}::{}", method.getDeclaringClass().getSimpleName(), method.getName()); @@ -155,149 +183,142 @@ public void afterMethod(Method m) { logger.info("Finished {}:{}.", m.getDeclaringClass().getSimpleName(), m.getName()); } - private static class DatabaseManagerImpl implements DatabaseForTest.DatabaseManager { - public static DatabaseManagerImpl getInstance(AsyncDocumentClient client) { + private static class DatabaseManagerImpl implements CosmosDatabaseForTest.DatabaseManager { + public static DatabaseManagerImpl getInstance(CosmosClient client) { return new DatabaseManagerImpl(client); } - private final AsyncDocumentClient client; + private final CosmosClient client; - private DatabaseManagerImpl(AsyncDocumentClient client) { + private DatabaseManagerImpl(CosmosClient client) { this.client = client; } @Override - public Observable> queryDatabases(SqlQuerySpec query) { + public Flux> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override - public Observable> createDatabase(Database databaseDefinition) { - return client.createDatabase(databaseDefinition, null); + public Mono createDatabase(CosmosDatabaseSettings databaseDefinition) { + return client.createDatabase(databaseDefinition); } @Override - public Observable> deleteDatabase(String id) { - - return client.deleteDatabase("dbs/" + id, null); + public CosmosDatabase getDatabase(String id) { + return client.getDatabase(id); } } @BeforeSuite(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}, timeOut = SUITE_SETUP_TIMEOUT) public static void beforeSuite() { logger.info("beforeSuite Started"); - AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); - try { - DatabaseForTest dbForTest = DatabaseForTest.create(DatabaseManagerImpl.getInstance(houseKeepingClient)); - SHARED_DATABASE = dbForTest.createdDatabase; - RequestOptions options = new RequestOptions(); - options.setOfferThroughput(10100); - SHARED_MULTI_PARTITION_COLLECTION = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinitionWithRangeRangeIndex(), options); - SHARED_SINGLE_PARTITION_COLLECTION = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinition(), null); - SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinitionSinglePartitionWithoutPartitionKey()); - SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes(), options); - } finally { - houseKeepingClient.close(); - } + CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); + CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.create(DatabaseManagerImpl.getInstance(houseKeepingClient)); + SHARED_DATABASE = dbForTest.createdDatabase; + CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); + options.offerThroughput(10100); + SHARED_MULTI_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options); + SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES = createCollection(SHARED_DATABASE, getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes(), options); + options.offerThroughput(6000); + SHARED_SINGLE_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options); } @AfterSuite(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}, timeOut = SUITE_SHUTDOWN_TIMEOUT) public static void afterSuite() { logger.info("afterSuite Started"); - AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); + CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); try { - safeDeleteDatabase(houseKeepingClient, SHARED_DATABASE); - DatabaseForTest.cleanupStaleTestDatabases(DatabaseManagerImpl.getInstance(houseKeepingClient)); + safeDeleteDatabase(SHARED_DATABASE); + CosmosDatabaseForTest.cleanupStaleTestDatabases(DatabaseManagerImpl.getInstance(houseKeepingClient)); } finally { safeClose(houseKeepingClient); } } - protected static void truncateCollection(DocumentCollection collection) { - logger.info("Truncating collection {} ...", collection.getId()); - AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); + protected static void truncateCollection(CosmosContainer cosmosContainer) { + CosmosContainerSettings cosmosContainerSettings = cosmosContainer.read().block().getCosmosContainerSettings(); + String cosmosContainerId = cosmosContainerSettings.getId(); + logger.info("Truncating collection {} ...", cosmosContainerId); + CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); try { - List paths = collection.getPartitionKey().getPaths(); - + List paths = cosmosContainerSettings.getPartitionKey().getPaths(); FeedOptions options = new FeedOptions(); options.setMaxDegreeOfParallelism(-1); options.setEnableCrossPartitionQuery(true); options.setMaxItemCount(100); - logger.info("Truncating collection {} documents ...", collection.getId()); + logger.info("Truncating collection {} documents ...", cosmosContainer.getId()); - houseKeepingClient.queryDocuments(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) + cosmosContainer.queryItems("SELECT * FROM root", options) + .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(doc -> { - RequestOptions requestOptions = new RequestOptions(); - + + Object propertyValue = null; if (paths != null && !paths.isEmpty()) { List pkPath = PathParser.getPathParts(paths.get(0)); - Object propertyValue = doc.getObjectByPath(pkPath); + propertyValue = doc.getObjectByPath(pkPath); if (propertyValue == null) { - propertyValue = Undefined.Value(); + propertyValue = PartitionKey.None; } - requestOptions.setPartitionKey(new PartitionKey(propertyValue)); } + return cosmosContainer.getItem(doc.getId(), propertyValue).delete(); + }).collectList().block(); + logger.info("Truncating collection {} triggers ...", cosmosContainerId); - return houseKeepingClient.deleteDocument(doc.getSelfLink(), requestOptions); - }).toCompletable().await(); - - logger.info("Truncating collection {} triggers ...", collection.getId()); - - houseKeepingClient.queryTriggers(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) + cosmosContainer.queryTriggers("SELECT * FROM root", options) + .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(trigger -> { - RequestOptions requestOptions = new RequestOptions(); + CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = trigger.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.setPartitionKey(new PartitionKey(propertyValue)); // } - return houseKeepingClient.deleteTrigger(trigger.getSelfLink(), requestOptions); - }).toCompletable().await(); + return cosmosContainer.getTrigger(trigger.getId()).delete(requestOptions); + }).collectList().block(); - logger.info("Truncating collection {} storedProcedures ...", collection.getId()); + logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); - houseKeepingClient.queryStoredProcedures(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) + cosmosContainer.queryStoredProcedures("SELECT * FROM root", options) + .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(storedProcedure -> { - RequestOptions requestOptions = new RequestOptions(); + CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = storedProcedure.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.setPartitionKey(new PartitionKey(propertyValue)); // } - return houseKeepingClient.deleteStoredProcedure(storedProcedure.getSelfLink(), requestOptions); - }).toCompletable().await(); + return cosmosContainer.getStoredProcedure(storedProcedure.getId()).delete(requestOptions); + }).collectList().block(); - logger.info("Truncating collection {} udfs ...", collection.getId()); + logger.info("Truncating collection {} udfs ...", cosmosContainerId); - houseKeepingClient.queryUserDefinedFunctions(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) + cosmosContainer.queryUserDefinedFunctions("SELECT * FROM root", options) + .flatMap(page -> Flux.fromIterable(page.getResults())) .flatMap(udf -> { - RequestOptions requestOptions = new RequestOptions(); + CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = udf.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.setPartitionKey(new PartitionKey(propertyValue)); // } - return houseKeepingClient.deleteUserDefinedFunction(udf.getSelfLink(), requestOptions); - }).toCompletable().await(); + return cosmosContainer.getUserDefinedFunction(udf.getId()).delete(requestOptions); + }).collectList().block(); } finally { houseKeepingClient.close(); } - logger.info("Finished truncating collection {}.", collection.getId()); + logger.info("Finished truncating collection {}.", cosmosContainerId); } - protected static void waitIfNeededForReplicasToCatchUp(Builder clientBuilder) { - switch (clientBuilder.desiredConsistencyLevel) { + protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { + switch (clientBuilder.getDesiredConsistencyLevel()) { case Eventual: case ConsistentPrefix: logger.info(" additional wait in Eventual mode so the replica catch up"); @@ -316,36 +337,12 @@ protected static void waitIfNeededForReplicasToCatchUp(Builder clientBuilder) { } } - private static DocumentCollection getCollectionDefinitionSinglePartitionWithoutPartitionKey() { - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); - - return collectionDefinition; + public static CosmosContainer createCollection(CosmosDatabase database, CosmosContainerSettings cosmosContainerSettings, + CosmosContainerRequestOptions options) { + return database.createContainer(cosmosContainerSettings, options).block().getContainer(); } - - public static DocumentCollection createCollection(String databaseId, - DocumentCollection collection, - RequestOptions options) { - AsyncDocumentClient client = createGatewayHouseKeepingDocumentClient().build(); - try { - return client.createCollection("dbs/" + databaseId, collection, options).toBlocking().single().getResource(); - } finally { - client.close(); - } - } - - public static DocumentCollection createCollection(AsyncDocumentClient client, String databaseId, - DocumentCollection collection, RequestOptions options) { - return client.createCollection("dbs/" + databaseId, collection, options).toBlocking().single().getResource(); - } - - public static DocumentCollection createCollection(AsyncDocumentClient client, String databaseId, - DocumentCollection collection) { - return client.createCollection("dbs/" + databaseId, collection, null).toBlocking().single().getResource(); - } - - private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { + private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { final String NUMBER_FIELD = "numberField"; final String STRING_FIELD = "stringField"; final String NUMBER_FIELD_2 = "numberField2"; @@ -359,7 +356,12 @@ private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompo final String LONG_STRING_FIELD = "longStringField"; final String PARTITION_KEY = "pk"; - DocumentCollection documentCollection = new DocumentCollection(); + PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); + ArrayList partitionKeyPaths = new ArrayList(); + partitionKeyPaths.add("/" + PARTITION_KEY); + partitionKeyDefinition.setPaths(partitionKeyPaths); + + CosmosContainerSettings cosmosContainerSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDefinition); IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection> compositeIndexes = new ArrayList>(); @@ -448,91 +450,83 @@ private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompo compositeIndexes.add(compositeIndexLongStrings); indexingPolicy.setCompositeIndexes(compositeIndexes); - documentCollection.setIndexingPolicy(indexingPolicy); + cosmosContainerSettings.setIndexingPolicy(indexingPolicy); - PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); - ArrayList partitionKeyPaths = new ArrayList(); - partitionKeyPaths.add("/" + PARTITION_KEY); - partitionKeyDefinition.setPaths(partitionKeyPaths); - documentCollection.setPartitionKey(partitionKeyDefinition); - - documentCollection.setId(UUID.randomUUID().toString()); + return cosmosContainerSettings; + } - return documentCollection; + public static CosmosContainer createCollection(CosmosClient client, String dbId, CosmosContainerSettings collectionDefinition) { + return client.getDatabase(dbId).createContainer(collectionDefinition).block().getContainer(); } - public static Document createDocument(AsyncDocumentClient client, String databaseId, String collectionId, Document document) { - return createDocument(client, databaseId, collectionId, document, null); + public static void deleteCollection(CosmosClient client, String dbId, String collectionId) { + client.getDatabase(dbId).getContainer(collectionId).delete().block(); } - public static Document createDocument(AsyncDocumentClient client, String databaseId, String collectionId, Document document, RequestOptions options) { - return client.createDocument(Utils.getCollectionNameLink(databaseId, collectionId), document, options, false).toBlocking().single().getResource(); + public static CosmosItem createDocument(CosmosContainer cosmosContainer, CosmosItemSettings item) { + return cosmosContainer.createItem(item).block().getCosmosItem(); } - public Observable> bulkInsert(AsyncDocumentClient client, - String collectionLink, - List documentDefinitionList, + /* + // TODO: respect concurrencyLevel; + public Flux bulkInsert(CosmosContainer cosmosContainer, + List documentDefinitionList, int concurrencyLevel) { - ArrayList>> result = new ArrayList>>(documentDefinitionList.size()); - for (Document docDef : documentDefinitionList) { - result.add(client.createDocument(collectionLink, docDef, null, false)); + CosmosItemSettings first = documentDefinitionList.remove(0); + Flux result = Flux.from(cosmosContainer.createItem(first)); + for (CosmosItemSettings docDef : documentDefinitionList) { + result.concatWith(cosmosContainer.createItem(docDef)); } - return Observable.merge(result, concurrencyLevel); + return result; } - - public Observable> bulkInsert(AsyncDocumentClient client, - String collectionLink, - List documentDefinitionList) { - return bulkInsert(client, collectionLink, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL); - } - - public List bulkInsertBlocking(AsyncDocumentClient client, - String collectionLink, - List documentDefinitionList) { - return bulkInsert(client, collectionLink, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) - .map(ResourceResponse::getResource) - .toList() - .toBlocking() - .single(); +*/ + public List bulkInsertBlocking(CosmosContainer cosmosContainer, + List documentDefinitionList) { + /* + return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) + .parallel() + .runOn(Schedulers.parallel()) + .map(CosmosItemResponse::getCosmosItemSettings) + .sequential() + .collectList() + .block(); + */ + return Flux.merge(documentDefinitionList.stream() + .map(d -> cosmosContainer.createItem(d).map(response -> response.getCosmosItemSettings())) + .collect(Collectors.toList())).collectList().block(); } - public static ConsistencyLevel getAccountDefaultConsistencyLevel(AsyncDocumentClient client) { - return client.getDatabaseAccount().toBlocking().single().getConsistencyPolicy().getDefaultConsistencyLevel(); + public static ConsistencyLevel getAccountDefaultConsistencyLevel(CosmosClient client) { + return CosmosBridgeInternal.getDatabaseAccount(client).block().getConsistencyPolicy().getDefaultConsistencyLevel(); } - public static User createUser(AsyncDocumentClient client, String databaseId, User user) { - return client.createUser("dbs/" + databaseId, user, null).toBlocking().single().getResource(); + public static CosmosUser createUser(CosmosClient client, String databaseId, CosmosUserSettings userSettings) { + return client.getDatabase(databaseId).read().block().getDatabase().createUser(userSettings).block().getUser(); } - public static User safeCreateUser(AsyncDocumentClient client, String databaseId, User user) { + public static CosmosUser safeCreateUser(CosmosClient client, String databaseId, CosmosUserSettings user) { deleteUserIfExists(client, databaseId, user.getId()); return createUser(client, databaseId, user); } - private static DocumentCollection safeCreateCollection(AsyncDocumentClient client, String databaseId, DocumentCollection collection, RequestOptions options) { + private static CosmosContainer safeCreateCollection(CosmosClient client, String databaseId, CosmosContainerSettings collection, CosmosContainerRequestOptions options) { deleteCollectionIfExists(client, databaseId, collection.getId()); - return createCollection(client, databaseId, collection, options); + return createCollection(client.getDatabase(databaseId), collection, options); } - public static String getCollectionLink(DocumentCollection collection) { - return collection.getSelfLink(); - } - - static protected DocumentCollection getCollectionDefinition() { + static protected CosmosContainerSettings getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); partitionKeyDef.setPaths(paths); - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); - collectionDefinition.setPartitionKey(partitionKeyDef); + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } - static protected DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { + static protected CosmosContainerSettings getCollectionDefinitionWithRangeRangeIndex() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); @@ -553,42 +547,50 @@ static protected DocumentCollection getCollectionDefinitionWithRangeRangeIndex() includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setIndexingPolicy(indexingPolicy); - collectionDefinition.setId(UUID.randomUUID().toString()); - collectionDefinition.setPartitionKey(partitionKeyDef); + CosmosContainerSettings cosmosContainerSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + cosmosContainerSettings.setIndexingPolicy(indexingPolicy); - return collectionDefinition; + return cosmosContainerSettings; } - public static void deleteCollectionIfExists(AsyncDocumentClient client, String databaseId, String collectionId) { - List res = client.queryCollections("dbs/" + databaseId, - String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null).toBlocking().single() - .getResults(); + public static void deleteCollectionIfExists(CosmosClient client, String databaseId, String collectionId) { + CosmosDatabase database = client.getDatabase(databaseId).read().block().getDatabase(); + List res = database.queryContainers(String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null) + .flatMap(page -> Flux.fromIterable(page.getResults())) + .collectList() + .block(); + if (!res.isEmpty()) { - deleteCollection(client, Utils.getCollectionNameLink(databaseId, collectionId)); + deleteCollection(database, collectionId); } } - public static void deleteCollection(AsyncDocumentClient client, String collectionLink) { - client.deleteCollection(collectionLink, null).toBlocking().single(); + public static void deleteCollection(CosmosDatabase cosmosDatabase, String collectionId) { + cosmosDatabase.getContainer(collectionId).delete().block(); + } + + public static void deleteCollection(CosmosContainer cosmosContainer) { + cosmosContainer.delete().block(); } - public static void deleteDocumentIfExists(AsyncDocumentClient client, String databaseId, String collectionId, String docId) { + public static void deleteDocumentIfExists(CosmosClient client, String databaseId, String collectionId, String docId) { FeedOptions options = new FeedOptions(); options.setPartitionKey(new PartitionKey(docId)); - List res = client - .queryDocuments(Utils.getCollectionNameLink(databaseId, collectionId), String.format("SELECT * FROM root r where r.id = '%s'", docId), options) - .toBlocking().single().getResults(); + CosmosContainer cosmosContainer = client.getDatabase(databaseId).read().block().getDatabase().getContainer(collectionId).read().block().getContainer(); + List res = cosmosContainer + .queryItems(String.format("SELECT * FROM root r where r.id = '%s'", docId), options) + .flatMap(page -> Flux.fromIterable(page.getResults())) + .collectList().block(); + if (!res.isEmpty()) { - deleteDocument(client, Utils.getDocumentNameLink(databaseId, collectionId, docId)); + deleteDocument(cosmosContainer, docId); } } - public static void safeDeleteDocument(AsyncDocumentClient client, String documentLink, RequestOptions options) { - if (client != null && documentLink != null) { + public static void safeDeleteDocument(CosmosContainer cosmosContainer, String documentId, Object partitionKey) { + if (cosmosContainer != null && documentId != null) { try { - client.deleteDocument(documentLink, options).toBlocking().single(); + cosmosContainer.getItem(documentId, partitionKey).read().block().getCosmosItem().delete().block(); } catch (Exception e) { DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e, DocumentClientException.class); if (dce == null || dce.getStatusCode() != 404) { @@ -598,103 +600,89 @@ public static void safeDeleteDocument(AsyncDocumentClient client, String documen } } - public static void deleteDocument(AsyncDocumentClient client, String documentLink) { - client.deleteDocument(documentLink, null).toBlocking().single(); + public static void deleteDocument(CosmosContainer cosmosContainer, String documentId) { + cosmosContainer.getItem(documentId, PartitionKey.None).read().block().getCosmosItem().delete(); } - public static void deleteUserIfExists(AsyncDocumentClient client, String databaseId, String userId) { - List res = client - .queryUsers("dbs/" + databaseId, String.format("SELECT * FROM root r where r.id = '%s'", userId), null) - .toBlocking().single().getResults(); + public static void deleteUserIfExists(CosmosClient client, String databaseId, String userId) { + CosmosDatabase database = client.getDatabase(databaseId).read().block().getDatabase(); + List res = database + .queryUsers(String.format("SELECT * FROM root r where r.id = '%s'", userId), null) + .flatMap(page -> Flux.fromIterable(page.getResults())) + .collectList().block(); if (!res.isEmpty()) { - deleteUser(client, Utils.getUserNameLink(databaseId, userId)); + deleteUser(database, userId); } } - public static void deleteUser(AsyncDocumentClient client, String userLink) { - client.deleteUser(userLink, null).toBlocking().single(); - } - - public static String getDatabaseLink(Database database) { - return database.getSelfLink(); + public static void deleteUser(CosmosDatabase database, String userId) { + database.getUser(userId).read().block().getUser().delete(null).block(); } - static private Database safeCreateDatabase(AsyncDocumentClient client, Database database) { - safeDeleteDatabase(client, database.getId()); - return createDatabase(client, database); + static private CosmosDatabase safeCreateDatabase(CosmosClient client, CosmosDatabaseSettings databaseSettings) { + safeDeleteDatabase(client.getDatabase(databaseSettings.getId())); + return client.createDatabase(databaseSettings).block().getDatabase(); } - static protected Database createDatabase(AsyncDocumentClient client, Database database) { - Observable> databaseObservable = client.createDatabase(database, null); - return databaseObservable.toBlocking().single().getResource(); - } - - static protected Database createDatabase(AsyncDocumentClient client, String databaseId) { - Database databaseDefinition = new Database(); - databaseDefinition.setId(databaseId); - return createDatabase(client, databaseDefinition); - } - - static protected Database createDatabaseIfNotExists(AsyncDocumentClient client, String databaseId) { - return client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null).flatMap(p -> Observable.from(p.getResults())).switchIfEmpty( - Observable.defer(() -> { - - Database databaseDefinition = new Database(); - databaseDefinition.setId(databaseId); - - return client.createDatabase(databaseDefinition, null).map(ResourceResponse::getResource); - }) - ).toBlocking().single(); + static protected CosmosDatabase createDatabase(CosmosClient client, String databaseId) { + CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings(databaseId); + return client.createDatabase(databaseSettings).block().getDatabase(); } - static protected void safeDeleteDatabase(AsyncDocumentClient client, Database database) { - if (database != null) { - safeDeleteDatabase(client, database.getId()); + static protected CosmosDatabase createDatabaseIfNotExists(CosmosClient client, String databaseId) { + List res = client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null) + .flatMap(p -> Flux.fromIterable(p.getResults())) + .collectList() + .block(); + if (res.size() != 0) { + return client.getDatabase(databaseId).read().block().getDatabase(); + } else { + CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings(databaseId); + return client.createDatabase(databaseSettings).block().getDatabase(); } } - static protected void safeDeleteDatabase(AsyncDocumentClient client, String databaseId) { - if (client != null) { + static protected void safeDeleteDatabase(CosmosDatabase database) { + if (database != null) { try { - client.deleteDatabase(Utils.getDatabaseNameLink(databaseId), null).toBlocking().single(); + database.delete().block(); } catch (Exception e) { } } } - static protected void safeDeleteAllCollections(AsyncDocumentClient client, Database database) { + static protected void safeDeleteAllCollections(CosmosDatabase database) { if (database != null) { - List collections = client.readCollections(database.getSelfLink(), null) - .flatMap(p -> Observable.from(p.getResults())) - .toList() - .toBlocking() - .single(); - - for (DocumentCollection collection : collections) { - client.deleteCollection(collection.getSelfLink(), null).toBlocking().single().getResource(); + List collections = database.listContainers() + .flatMap(p -> Flux.fromIterable(p.getResults())) + .collectList() + .block(); + + for(CosmosContainerSettings collection: collections) { + database.getContainer(collection.getId()).delete().block(); } } } - static protected void safeDeleteCollection(AsyncDocumentClient client, DocumentCollection collection) { - if (client != null && collection != null) { + static protected void safeDeleteCollection(CosmosContainer collection) { + if (collection != null) { try { - client.deleteCollection(collection.getSelfLink(), null).toBlocking().single(); + collection.delete().block(); } catch (Exception e) { } } } - static protected void safeDeleteCollection(AsyncDocumentClient client, String databaseId, String collectionId) { - if (client != null && databaseId != null && collectionId != null) { + static protected void safeDeleteCollection(CosmosDatabase database, String collectionId) { + if (database != null && collectionId != null) { try { - client.deleteCollection("/dbs/" + databaseId + "/colls/" + collectionId, null).toBlocking().single(); + database.getContainer(collectionId).read().block().getContainer().delete().block(); } catch (Exception e) { } } } - static protected void safeCloseAsync(AsyncDocumentClient client) { + static protected void safeCloseAsync(CosmosClient client) { if (client != null) { new Thread(() -> { try { @@ -706,7 +694,7 @@ static protected void safeCloseAsync(AsyncDocumentClient client) { } } - static protected void safeClose(AsyncDocumentClient client) { + static protected void safeClose(CosmosClient client) { if (client != null) { try { client.close(); @@ -717,12 +705,12 @@ static protected void safeClose(AsyncDocumentClient client) { } public void validateSuccess(Observable> observable, - ResourceResponseValidator validator) { + ResourceResponseValidator validator) { validateSuccess(observable, validator, subscriberValidationTimeout); } public static void validateSuccess(Observable> observable, - ResourceResponseValidator validator, long timeout) { + ResourceResponseValidator validator, long timeout) { VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); @@ -735,12 +723,12 @@ public static void validateSuccess(Observable void validateFailure(Observable> observable, - FailureValidator validator) { + FailureValidator validator) { validateFailure(observable, validator, subscriberValidationTimeout); } public static void validateFailure(Observable> observable, - FailureValidator validator, long timeout) { + FailureValidator validator, long timeout) { VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); @@ -753,12 +741,12 @@ public static void validateFailure(Observable void validateQuerySuccess(Observable> observable, - FeedResponseListValidator validator) { + FeedResponseListValidator validator) { validateQuerySuccess(observable, validator, subscriberValidationTimeout); } public static void validateQuerySuccess(Observable> observable, - FeedResponseListValidator validator, long timeout) { + FeedResponseListValidator validator, long timeout) { VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); @@ -770,12 +758,12 @@ public static void validateQuerySuccess(Observable void validateQueryFailure(Observable> observable, - FailureValidator validator) { + FailureValidator validator) { validateQueryFailure(observable, validator, subscriberValidationTimeout); } public static void validateQueryFailure(Observable> observable, - FailureValidator validator, long timeout) { + FailureValidator validator, long timeout) { VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); @@ -787,6 +775,77 @@ public static void validateQueryFailure(Observable void validateSuccess(Mono single, CosmosResponseValidator validator) + throws InterruptedException { + validateSuccess(single.flux(), validator, subscriberValidationTimeout); + } + + public static void validateSuccess(Flux flowable, + CosmosResponseValidator validator, long timeout) throws InterruptedException { + + TestSubscriber testSubscriber = new TestSubscriber<>(); + + flowable.subscribe(testSubscriber); + testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + testSubscriber.assertNoErrors(); + testSubscriber.assertComplete(); + testSubscriber.assertValueCount(1); + validator.validate(testSubscriber.values().get(0)); + } + + public void validateFailure(Mono mono, FailureValidator validator) + throws InterruptedException { + validateFailure(mono.flux(), validator, subscriberValidationTimeout); + } + + public static void validateFailure(Flux flowable, + FailureValidator validator, long timeout) throws InterruptedException { + + TestSubscriber testSubscriber = new TestSubscriber<>(); + + flowable.subscribe(testSubscriber); + testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + assertThat(testSubscriber.errors()).hasSize(1); + validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); + } + + public void validateQuerySuccess(Flux> flowable, + FeedResponseListValidator validator) { + validateQuerySuccess(flowable, validator, subscriberValidationTimeout); + } + + public static void validateQuerySuccess(Flux> flowable, + FeedResponseListValidator validator, long timeout) { + + TestSubscriber> testSubscriber = new TestSubscriber<>(); + + flowable.subscribe(testSubscriber); + testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + testSubscriber.assertNoErrors(); + testSubscriber.assertComplete(); + validator.validate(testSubscriber.getEvents().get(0).stream().map(object -> (FeedResponse) object) + .collect(Collectors.toList())); + } + + public void validateQueryFailure(Flux> flowable, FailureValidator validator) { + validateQueryFailure(flowable, validator, subscriberValidationTimeout); + } + + public static void validateQueryFailure(Flux> flowable, + FailureValidator validator, long timeout) { + + TestSubscriber> testSubscriber = new TestSubscriber<>(); + + flowable.subscribe(testSubscriber); + testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + assertThat(testSubscriber.getEvents().get(1)).hasSize(1); + validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); + } + @DataProvider public static Object[][] clientBuilders() { return new Object[][]{{createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null)}}; @@ -858,23 +917,23 @@ private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.Session; - List builders = new ArrayList<>(); - builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null)); + List cosmosConfigurations = new ArrayList<>(); + cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null)); for (Protocol protocol : protocols) { - testConsistencies.forEach(consistencyLevel -> builders.add(createDirectRxDocumentClient(consistencyLevel, + testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations))); } - builders.forEach(b -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", - b.connectionPolicy.getConnectionMode(), - b.desiredConsistencyLevel, - b.configs.getProtocol() + cosmosConfigurations.forEach(c -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", + c.getConnectionPolicy().getConnectionMode(), + c.getDesiredConsistencyLevel(), + c.getConfigs().getProtocol() )); - return builders.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); + return cosmosConfigurations.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); } @DataProvider @@ -924,6 +983,7 @@ static List parseDesiredConsistencies(String consistencies) { static List allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { List testConsistencies = new ArrayList<>(); switch (accountConsistency) { + case Strong: testConsistencies.add(ConsistencyLevel.Strong); case BoundedStaleness: @@ -944,53 +1004,53 @@ static List allEqualOrLowerConsistencies(ConsistencyLevel acco private static Object[][] clientBuildersWithDirect(List testConsistencies, Protocol... protocols) { boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.Session; - List builders = new ArrayList<>(); - builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, isMultiMasterEnabled, preferredLocations)); + List cosmosConfigurations = new ArrayList<>(); + cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, isMultiMasterEnabled, preferredLocations)); for (Protocol protocol : protocols) { - testConsistencies.forEach(consistencyLevel -> builders.add(createDirectRxDocumentClient(consistencyLevel, + testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, protocol, isMultiMasterEnabled, preferredLocations))); } - builders.forEach(b -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", - b.connectionPolicy.getConnectionMode(), - b.desiredConsistencyLevel, - b.configs.getProtocol() + cosmosConfigurations.forEach(c -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", + c.getConnectionPolicy().getConnectionMode(), + c.getDesiredConsistencyLevel(), + c.getConfigs().getProtocol() )); - return builders.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); + return cosmosConfigurations.stream().map(c -> new Object[]{c}).collect(Collectors.toList()).toArray(new Object[0][]); } - static protected Builder createGatewayHouseKeepingDocumentClient() { + static protected CosmosClientBuilder createGatewayHouseKeepingDocumentClient() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); connectionPolicy.setConnectionMode(ConnectionMode.Gateway); RetryOptions options = new RetryOptions(); options.setMaxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); connectionPolicy.setRetryOptions(options); - return new Builder().withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session); + return CosmosClient.builder().endpoint(TestConfigurations.HOST) + .key(TestConfigurations.MASTER_KEY) + .connectionPolicy(connectionPolicy) + .consistencyLevel(ConsistencyLevel.Session); } - static protected Builder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List preferredLocations) { + static protected CosmosClientBuilder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List preferredLocations) { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); connectionPolicy.setConnectionMode(ConnectionMode.Gateway); connectionPolicy.setUsingMultipleWriteLocations(multiMasterEnabled); connectionPolicy.setPreferredLocations(preferredLocations); - return new Builder().withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(consistencyLevel); + return CosmosClient.builder().endpoint(TestConfigurations.HOST) + .key(TestConfigurations.MASTER_KEY) + .connectionPolicy(connectionPolicy) + .consistencyLevel(consistencyLevel); } - static protected Builder createGatewayRxDocumentClient() { + static protected CosmosClientBuilder createGatewayRxDocumentClient() { return createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null); } - static protected Builder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, + static protected CosmosClientBuilder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, Protocol protocol, boolean multiMasterEnabled, List preferredLocations) { @@ -1008,11 +1068,11 @@ static protected Builder createDirectRxDocumentClient(ConsistencyLevel consisten Configs configs = spy(new Configs()); doAnswer((Answer)invocation -> protocol).when(configs).getProtocol(); - return new Builder().withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(consistencyLevel) - .withConfigs(configs); + return CosmosClient.builder().endpoint(TestConfigurations.HOST) + .key(TestConfigurations.MASTER_KEY) + .connectionPolicy(connectionPolicy) + .consistencyLevel(consistencyLevel) + .configs(configs); } protected int expectedNumberOfPages(int totalExpectedResult, int maxPageSize) { @@ -1027,7 +1087,7 @@ public Object[][] queryMetricsArgProvider() { }; } - public static class VerboseTestSubscriber extends TestSubscriber { + public static class VerboseTestSubscriber extends rx.observers.TestSubscriber { @Override public void assertNoErrors() { List onErrorEvents = getOnErrorEvents(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TokenResolverTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TokenResolverTest.java index cc9ea0fef0f8b..5877d771244f4 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TokenResolverTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TokenResolverTest.java @@ -45,6 +45,7 @@ import com.microsoft.azure.cosmosdb.TokenResolver; import com.microsoft.azure.cosmosdb.User; import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -63,6 +64,7 @@ import java.util.UUID; import java.util.Map; +//TODO: change to use external TestSuiteBase public class TokenResolverTest extends TestSuiteBase { private class UserClass { @@ -563,4 +565,4 @@ private TokenResolver getTokenResolverWithBlockList(PermissionMode permissionMod } }; } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java index b40b22609e7ea..de9569b2afe31 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java @@ -30,6 +30,7 @@ import java.util.Set; import java.util.concurrent.TimeUnit; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import com.microsoft.azure.cosmosdb.RetryAnalyzer; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; import org.testng.SkipException; @@ -38,36 +39,35 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.PartitionKey; import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; import com.microsoft.azure.cosmosdb.rx.internal.query.TakeContinuationToken; -import rx.Observable; +import io.reactivex.subscribers.TestSubscriber; +import reactor.core.publisher.Flux; public class TopQueryTests extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; - private ArrayList docs = new ArrayList(); + private CosmosContainer createdCollection; + private ArrayList docs = new ArrayList(); private String partitionKey = "mypk"; private int firstPk = 0; private int secondPk = 1; private String field = "field"; - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public TopQueryTests(AsyncDocumentClient.Builder clientBuilder) { + public TopQueryTests(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider", retryAnalyzer = RetryAnalyzer.class - ) + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider", retryAnalyzer = RetryAnalyzer.class) public void queryDocumentsWithTop(boolean qmEnabled) throws Exception { FeedOptions options = new FeedOptions(); @@ -81,36 +81,33 @@ public void queryDocumentsWithTop(boolean qmEnabled) throws Exception { int[] expectedPageLengths = new int[] { 9, 9, 2 }; for (int i = 0; i < 2; i++) { - Observable> queryObservable1 = client.queryDocuments(createdCollection.getSelfLink(), - "SELECT TOP 0 value AVG(c.field) from c", options); + Flux> queryObservable1 = createdCollection.queryItems("SELECT TOP 0 value AVG(c.field) from c", options); - FeedResponseListValidator validator1 = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator1 = new FeedResponseListValidator.Builder() .totalSize(0).build(); try { validateQuerySuccess(queryObservable1, validator1, TIMEOUT); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", - this.clientBuilder.desiredConsistencyLevel); + this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } throw error; } - Observable> queryObservable2 = client.queryDocuments(createdCollection.getSelfLink(), - "SELECT TOP 1 value AVG(c.field) from c", options); + Flux> queryObservable2 = createdCollection.queryItems("SELECT TOP 1 value AVG(c.field) from c", options); - FeedResponseListValidator validator2 = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator2 = new FeedResponseListValidator.Builder() .totalSize(1).build(); validateQuerySuccess(queryObservable2, validator2, TIMEOUT); - Observable> queryObservable3 = client.queryDocuments(createdCollection.getSelfLink(), - "SELECT TOP 20 * from c", options); + Flux> queryObservable3 = createdCollection.queryItems("SELECT TOP 20 * from c", options); - FeedResponseListValidator validator3 = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator3 = new FeedResponseListValidator.Builder() .totalSize(expectedTotalSize).numberOfPages(expectedNumberOfPages).pageLengths(expectedPageLengths) .hasValidQueryMetrics(qmEnabled).build(); @@ -160,9 +157,9 @@ public void queryDocumentsWithTopContinuationTokens() throws Exception { private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, int topCount) { for (int pageSize : pageSizes) { - List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); + List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); Set actualIds = new HashSet(); - for (Document document : receivedDocuments) { + for (CosmosItemSettings document : receivedDocuments) { actualIds.add(document.getResourceId()); } @@ -170,10 +167,10 @@ private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSiz } } - private List queryWithContinuationTokens(String query, int pageSize) { + private List queryWithContinuationTokens(String query, int pageSize) { String requestContinuation = null; List continuationTokens = new ArrayList(); - List receivedDocuments = new ArrayList(); + List receivedDocuments = new ArrayList(); do { FeedOptions options = new FeedOptions(); @@ -181,17 +178,16 @@ private List queryWithContinuationTokens(String query, int pageSize) { options.setEnableCrossPartitionQuery(true); options.setMaxDegreeOfParallelism(2); options.setRequestContinuation(requestContinuation); - Observable> queryObservable = client.queryDocuments(createdCollection.getSelfLink(), - query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); - Observable> firstPageObservable = queryObservable.first(); - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - firstPageObservable.subscribe(testSubscriber); + //Observable> firstPageObservable = queryObservable.first(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); + queryObservable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); - FeedResponse firstPage = testSubscriber.getOnNextEvents().get(0); + FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); requestContinuation = firstPage.getResponseContinuation(); receivedDocuments.addAll(firstPage.getResults()); continuationTokens.add(requestContinuation); @@ -200,18 +196,18 @@ private List queryWithContinuationTokens(String query, int pageSize) { return receivedDocuments; } - public void bulkInsert(AsyncDocumentClient client) { + public void bulkInsert(CosmosClient client) { generateTestData(); for (int i = 0; i < docs.size(); i++) { - createDocument(client, createdDatabase.getId(), createdCollection.getId(), docs.get(i)); + createDocument(createdCollection, docs.get(i)); } } public void generateTestData() { for (int i = 0; i < 10; i++) { - Document d = new Document(); + CosmosItemSettings d = new CosmosItemSettings(); d.setId(Integer.toString(i)); d.set(field, i); d.set(partitionKey, firstPk); @@ -219,7 +215,7 @@ public void generateTestData() { } for (int i = 10; i < 20; i++) { - Document d = new Document(); + CosmosItemSettings d = new CosmosItemSettings(); d.setId(Integer.toString(i)); d.set(field, i); d.set(partitionKey, secondPk); @@ -235,9 +231,8 @@ public void afterClass() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION); + createdCollection = getSharedSinglePartitionCosmosContainer(client); + truncateCollection(createdCollection); bulkInsert(client); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerCrudTest.java index 5a729f2ce4243..f9d4008fe70b9 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerCrudTest.java @@ -24,49 +24,50 @@ import java.util.UUID; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.Trigger; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosRequestOptions; +import com.microsoft.azure.cosmos.CosmosResponse; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmos.CosmosTrigger; +import com.microsoft.azure.cosmos.CosmosTriggerResponse; +import com.microsoft.azure.cosmos.CosmosTriggerSettings; +import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.TriggerOperation; import com.microsoft.azure.cosmosdb.TriggerType; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; - -import rx.Observable; - -import javax.net.ssl.SSLException; +import reactor.core.publisher.Mono; public class TriggerCrudTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; + private CosmosContainer createdCollection; - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public TriggerCrudTest(AsyncDocumentClient.Builder clientBuilder) { + public TriggerCrudTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } - @Test(groups = { "simple" }, timeOut = TIMEOUT) + @Test(groups = { "simple" }, timeOut = TIMEOUT * 100) public void createTrigger() throws Exception { // create a trigger - Trigger trigger = new Trigger(); + CosmosTriggerSettings trigger = new CosmosTriggerSettings(); trigger.setId(UUID.randomUUID().toString()); trigger.setBody("function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.Create); trigger.setTriggerType(TriggerType.Pre); - Observable> createObservable = client.createTrigger(getCollectionLink(), trigger, null); + Mono createObservable = createdCollection.createTrigger(trigger, new CosmosRequestOptions()); // validate trigger creation - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(trigger.getId()) .withTriggerBody("function() {var x = 10;}") .withTriggerInternals(TriggerType.Pre, TriggerOperation.Create) @@ -78,19 +79,19 @@ public void createTrigger() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readTrigger() throws Exception { // create a trigger - Trigger trigger = new Trigger(); + CosmosTriggerSettings trigger = new CosmosTriggerSettings(); trigger.setId(UUID.randomUUID().toString()); trigger.setBody("function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.Create); trigger.setTriggerType(TriggerType.Pre); - Trigger readBackTrigger = client.createTrigger(getCollectionLink(), trigger, null).toBlocking().single().getResource(); + CosmosTrigger readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().getCosmosTrigger(); // read trigger waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readTrigger(readBackTrigger.getSelfLink(), null); + Mono readObservable = readBackTrigger.read(new RequestOptions()); // validate read trigger - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(trigger.getId()) .withTriggerBody("function() {var x = 10;}") .withTriggerInternals(TriggerType.Pre, TriggerOperation.Create) @@ -102,18 +103,18 @@ public void readTrigger() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteTrigger() throws Exception { // create a trigger - Trigger trigger = new Trigger(); + CosmosTriggerSettings trigger = new CosmosTriggerSettings(); trigger.setId(UUID.randomUUID().toString()); trigger.setBody("function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.Create); trigger.setTriggerType(TriggerType.Pre); - Trigger readBackTrigger = client.createTrigger(getCollectionLink(), trigger, null).toBlocking().single().getResource(); + CosmosTrigger readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().getCosmosTrigger(); // delete trigger - Observable> deleteObservable = client.deleteTrigger(readBackTrigger.getSelfLink(), null); + Mono deleteObservable = readBackTrigger.delete(new CosmosRequestOptions()); // validate delete trigger - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .nullResource() .build(); validateSuccess(deleteObservable, validator); @@ -122,17 +123,11 @@ public void deleteTrigger() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; + createdCollection = getSharedMultiPartitionCosmosContainer(client); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } - - private String getCollectionLink() { - return createdCollection.getSelfLink(); - } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerQueryTest.java index af8ea0a1bdd4f..9bb191ec70133 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerQueryTest.java @@ -29,39 +29,34 @@ import java.util.UUID; import java.util.stream.Collectors; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosRequestOptions; +import com.microsoft.azure.cosmos.CosmosTriggerSettings; import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; import com.microsoft.azure.cosmosdb.Trigger; import com.microsoft.azure.cosmosdb.TriggerOperation; import com.microsoft.azure.cosmosdb.TriggerType; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; - -import rx.Observable; +import reactor.core.publisher.Flux; public class TriggerQueryTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdTriggers = new ArrayList<>(); - - private AsyncDocumentClient client; + private CosmosContainer createdCollection; + private List createdTriggers = new ArrayList<>(); - public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); - } + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public TriggerQueryTest(Builder clientBuilder) { + public TriggerQueryTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -73,19 +68,18 @@ public void queryWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(5); - Observable> queryObservable = client - .queryTriggers(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryTriggers(query, options); List expectedDocs = createdTriggers.stream().filter(sp -> filterId.equals(sp.getId()) ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -98,13 +92,12 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryTriggers(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryTriggers(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -117,21 +110,20 @@ public void queryAll() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(3); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryTriggers(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryTriggers(query, options); - List expectedDocs = createdTriggers; + List expectedDocs = createdTriggers; int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() .map(d -> d.getResourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -142,8 +134,7 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryTriggers(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryTriggers(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(DocumentClientException.class) @@ -153,20 +144,19 @@ public void invalidQuerySytax() throws Exception { validateQueryFailure(queryObservable, validator); } - public Trigger createTrigger(AsyncDocumentClient client) { - Trigger storedProcedure = getTriggerDef(); - return client.createTrigger(getCollectionLink(), storedProcedure, null).toBlocking().single().getResource(); + public CosmosTriggerSettings createTrigger(CosmosContainer cosmosContainer) { + CosmosTriggerSettings storedProcedure = getTriggerDef(); + return cosmosContainer.createTrigger(storedProcedure, new CosmosRequestOptions()).block().getCosmosTriggerSettings(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); for(int i = 0; i < 5; i++) { - createdTriggers.add(createTrigger(client)); + createdTriggers.add(createTrigger(createdCollection)); } waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -177,8 +167,8 @@ public void afterClass() { safeClose(client); } - private static Trigger getTriggerDef() { - Trigger trigger = new Trigger(); + private static CosmosTriggerSettings getTriggerDef() { + CosmosTriggerSettings trigger = new CosmosTriggerSettings(); trigger.setId(UUID.randomUUID().toString()); trigger.setBody("function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.Create); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerUpsertReplaceTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerUpsertReplaceTest.java index 7ef831e458eb6..fe2796bcef075 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerUpsertReplaceTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerUpsertReplaceTest.java @@ -24,92 +24,52 @@ import java.util.UUID; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.Trigger; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosRequestOptions; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmos.CosmosTriggerResponse; +import com.microsoft.azure.cosmos.CosmosTriggerSettings; +import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.TriggerOperation; import com.microsoft.azure.cosmosdb.TriggerType; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; - -import rx.Observable; - -import javax.net.ssl.SSLException; +import reactor.core.publisher.Mono; public class TriggerUpsertReplaceTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; + private CosmosContainer createdCollection; - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public TriggerUpsertReplaceTest(AsyncDocumentClient.Builder clientBuilder) { + public TriggerUpsertReplaceTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void upsertTrigger() throws Exception { - - // create a trigger - Trigger trigger = new Trigger(); - trigger.setId(UUID.randomUUID().toString()); - trigger.setBody("function() {var x = 10;}"); - trigger.setTriggerOperation(TriggerOperation.Create); - trigger.setTriggerType(TriggerType.Pre); - Trigger readBackTrigger = client.upsertTrigger(getCollectionLink(), trigger, null).toBlocking().single().getResource(); - - // read trigger to validate creation - waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readTrigger(readBackTrigger.getSelfLink(), null); - - // validate trigger creation - ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() - .withId(readBackTrigger.getId()) - .withTriggerBody("function() {var x = 10;}") - .withTriggerInternals(TriggerType.Pre, TriggerOperation.Create) - .notNullEtag() - .build(); - validateSuccess(readObservable, validatorForRead); - - //update trigger - readBackTrigger.setBody("function() {var x = 11;}"); - - Observable> updateObservable = client.upsertTrigger(getCollectionLink(), readBackTrigger, null); - - // validate trigger update - ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() - .withId(readBackTrigger.getId()) - .withTriggerBody("function() {var x = 11;}") - .withTriggerInternals(TriggerType.Pre, TriggerOperation.Create) - .notNullEtag() - .build(); - validateSuccess(updateObservable, validatorForUpdate); - } - @Test(groups = { "simple" }, timeOut = TIMEOUT) public void replaceTrigger() throws Exception { // create a trigger - Trigger trigger = new Trigger(); + CosmosTriggerSettings trigger = new CosmosTriggerSettings(); trigger.setId(UUID.randomUUID().toString()); trigger.setBody("function() {var x = 10;}"); trigger.setTriggerOperation(TriggerOperation.Create); trigger.setTriggerType(TriggerType.Pre); - Trigger readBackTrigger = client.createTrigger(getCollectionLink(), trigger, null).toBlocking().single().getResource(); + CosmosTriggerSettings readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().getCosmosTriggerSettings(); // read trigger to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readTrigger(readBackTrigger.getSelfLink(), null); + Mono readObservable = createdCollection.getTrigger(readBackTrigger.getId()).read(new RequestOptions()); // validate trigger creation - ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() + CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() .withId(readBackTrigger.getId()) .withTriggerBody("function() {var x = 10;}") .withTriggerInternals(TriggerType.Pre, TriggerOperation.Create) @@ -120,10 +80,10 @@ public void replaceTrigger() throws Exception { //update trigger readBackTrigger.setBody("function() {var x = 11;}"); - Observable> updateObservable = client.replaceTrigger(readBackTrigger, null); + Mono updateObservable = createdCollection.getTrigger(readBackTrigger.getId()).replace(readBackTrigger, new RequestOptions()); // validate trigger replace - ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() + CosmosResponseValidator validatorForUpdate = new CosmosResponseValidator.Builder() .withId(readBackTrigger.getId()) .withTriggerBody("function() {var x = 11;}") .withTriggerInternals(TriggerType.Pre, TriggerOperation.Create) @@ -135,17 +95,12 @@ public void replaceTrigger() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } - - private String getCollectionLink() { - return createdCollection.getSelfLink(); - } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UniqueIndexTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UniqueIndexTest.java index d6bd7f40c6b21..e95adb5735ce8 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UniqueIndexTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UniqueIndexTest.java @@ -25,59 +25,63 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; +import java.util.ArrayList; import java.util.Collections; import java.util.UUID; -import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -import javax.net.ssl.SSLException; - import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.fasterxml.jackson.databind.util.JSONPObject; -import com.microsoft.azure.cosmosdb.DatabaseForTest; + import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; +import com.microsoft.azure.cosmos.CosmosContainerSettings; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; +import com.microsoft.azure.cosmos.CosmosItem; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemSettings; import com.microsoft.azure.cosmosdb.ConnectionPolicy; import com.microsoft.azure.cosmosdb.ConsistencyLevel; import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.ExcludedPath; import com.microsoft.azure.cosmosdb.HashIndex; import com.microsoft.azure.cosmosdb.IncludedPath; import com.microsoft.azure.cosmosdb.IndexingMode; import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; import com.microsoft.azure.cosmosdb.UniqueKey; import com.microsoft.azure.cosmosdb.UniqueKeyPolicy; import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import rx.Observable; -import rx.observers.TestSubscriber; - public class UniqueIndexTest extends TestSuiteBase { protected static final int TIMEOUT = 30000; protected static final int SETUP_TIMEOUT = 20000; protected static final int SHUTDOWN_TIMEOUT = 20000; - private final String databaseId = DatabaseForTest.generateId(); - private AsyncDocumentClient client; - private Database database; + private final String databaseId = CosmosDatabaseForTest.generateId(); + private CosmosClient client; + private CosmosDatabase database; - private DocumentCollection collection; + private CosmosContainer collection; @Test(groups = { "long" }, timeOut = TIMEOUT) public void insertWithUniqueIndex() throws Exception { - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); @@ -98,59 +102,66 @@ public void insertWithUniqueIndex() throws Exception { includedPath2.setPath("/description/?"); includedPath2.setIndexes(Collections.singletonList(new HashIndex(DataType.String, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); + collectionDefinition.setIndexingPolicy(indexingPolicy); ObjectMapper om = new ObjectMapper(); - JsonNode doc1 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"poet\"}", JsonNode.class); - JsonNode doc2 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"playwright\"}", JsonNode.class); - JsonNode doc3 = om.readValue("{\"name\":\"حافظ شیرازی\",\"description\":\"poet\"}", JsonNode.class); + JsonNode doc1 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", JsonNode.class); + JsonNode doc2 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"playwright\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); + JsonNode doc3 = om.readValue("{\"name\":\"حافظ شیرازی\",\"description\":\"poet\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); - collection = client.createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single().getResource(); + collection = database.createContainer(collectionDefinition).block().getContainer(); - Document dd = client.createDocument(getCollectionLink(collection), doc1, null, false).toBlocking().single().getResource(); + CosmosItem item = collection.createItem(doc1).block().getCosmosItem(); - client.readDocument(dd.getSelfLink(), null).toBlocking().single(); + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.setPartitionKey(PartitionKey.None); + CosmosItemSettings itemSettings = item.read(options).block().getCosmosItemSettings(); + assertThat(itemSettings.getId()).isEqualTo(doc1.get("id").textValue()); try { - client.createDocument(getCollectionLink(collection), doc1, null, false).toBlocking().single(); + collection.createItem(doc1).block(); fail("Did not throw due to unique constraint (create)"); } catch (RuntimeException e) { assertThat(getDocumentClientException(e).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } - client.createDocument(getCollectionLink(collection), doc2, null, false).toBlocking().single(); - client.createDocument(getCollectionLink(collection), doc3, null, false).toBlocking().single(); + collection.createItem(doc2).block(); + collection.createItem(doc3).block(); } - @Test(groups = { "long" }, timeOut = TIMEOUT) + @Test(groups = { "long" }, timeOut = TIMEOUT * 1000) public void replaceAndDeleteWithUniqueIndex() throws Exception { - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); uniqueKeyPolicy.setUniqueKeys(Collections.singleton(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); - collection = client.createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single().getResource(); + collection = database.createContainer(collectionDefinition).block().getContainer(); ObjectMapper om = new ObjectMapper(); - ObjectNode doc1 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"poet\"}", ObjectNode.class); - ObjectNode doc3 = om.readValue("{\"name\":\"Rabindranath Tagore\",\"description\":\"poet\"}", ObjectNode.class); - ObjectNode doc2 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"mathematician\"}", ObjectNode.class); + ObjectNode doc1 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); + ObjectNode doc3 = om.readValue("{\"name\":\"Rabindranath Tagore\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); + ObjectNode doc2 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"mathematician\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); - Document doc1Inserted = client.createDocument( - getCollectionLink(collection), doc1, null, false).toBlocking().single().getResource(); + CosmosItemSettings doc1Inserted = collection.createItem(doc1, new CosmosItemRequestOptions()).block().getCosmosItemSettings(); - client.replaceDocument(doc1Inserted.getSelfLink(), doc1Inserted, null).toBlocking().single(); // Replace with same values -- OK. + collection.getItem(doc1.get("id").asText(), PartitionKey.None).replace(doc1Inserted, new CosmosItemRequestOptions()).block().getCosmosItemSettings(); // Replace with same values -- OK. - Document doc2Inserted = client.createDocument(getCollectionLink(collection), doc2, null, false).toBlocking().single().getResource(); - Document doc2Replacement = new Document(doc1Inserted.toJson()); + CosmosItemSettings doc2Inserted = collection.createItem(doc2, new CosmosItemRequestOptions()).block().getCosmosItemSettings(); + CosmosItemSettings doc2Replacement = new CosmosItemSettings(doc1Inserted.toJson()); doc2Replacement.setId( doc2Inserted.getId()); try { - client.replaceDocument(doc2Inserted.getSelfLink(), doc2Replacement, null).toBlocking().single(); // Replace doc2 with values from doc1 -- Conflict. + collection.getItem(doc2Inserted.getId(), PartitionKey.None).replace(doc2Replacement, new CosmosItemRequestOptions()).block(); // Replace doc2 with values from doc1 -- Conflict. fail("Did not throw due to unique constraint"); } catch (RuntimeException ex) { @@ -158,16 +169,20 @@ public void replaceAndDeleteWithUniqueIndex() throws Exception { } doc3.put("id", doc1Inserted.getId()); - client.replaceDocument(doc1Inserted.getSelfLink(), doc3, null).toBlocking().single(); // Replace with values from doc3 -- OK. + collection.getItem(doc1Inserted.getId(), PartitionKey.None).replace(doc3).block(); // Replace with values from doc3 -- OK. - client.deleteDocument(doc1Inserted.getSelfLink(), null).toBlocking().single(); - client.createDocument(getCollectionLink(collection), doc1, null, false).toBlocking().single(); + collection.getItem(doc1Inserted.getId(), PartitionKey.None).delete().block(); + collection.createItem(doc1, new CosmosItemRequestOptions()).block(); } @Test(groups = { "long" }, timeOut = TIMEOUT) public void uniqueKeySerializationDeserialization() { - DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.setPaths(ImmutableList.of("/name", "/description")); @@ -191,11 +206,9 @@ public void uniqueKeySerializationDeserialization() { collectionDefinition.setIndexingPolicy(indexingPolicy); - DocumentCollection createdCollection = client.createCollection(database.getSelfLink(), collectionDefinition, - null).toBlocking().single().getResource(); + CosmosContainer createdCollection = database.createContainer(collectionDefinition).block().getContainer(); - DocumentCollection collection = client.readCollection(getCollectionLink(createdCollection), null) - .toBlocking().single().getResource(); + CosmosContainerSettings collection = createdCollection.read().block().getCosmosContainerSettings(); assertThat(collection.getUniqueKeyPolicy()).isNotNull(); assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()).isNotNull(); @@ -213,29 +226,21 @@ private DocumentClientException getDocumentClientException(RuntimeException e) { return dce; } - private String getDatabaseLink() { - return database.getSelfLink(); - } - - public String getCollectionLink() { - return "dbs/" + database.getId() + "/colls/" + collection.getId(); - } - @BeforeClass(groups = { "long" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { // set up the client - client = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(ConnectionPolicy.GetDefault()) - .withConsistencyLevel(ConsistencyLevel.Session).build(); + client = CosmosClient.builder() + .endpoint(TestConfigurations.HOST) + .key(TestConfigurations.MASTER_KEY) + .connectionPolicy(ConnectionPolicy.GetDefault()) + .consistencyLevel(ConsistencyLevel.Session).build(); database = createDatabase(client, databaseId); } @AfterClass(groups = { "long" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteDatabase(client, databaseId); + safeDeleteDatabase(database); safeClose(client); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserCrudTest.java index ce47630b91ad7..2159a78724cea 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserCrudTest.java @@ -22,49 +22,48 @@ */ package com.microsoft.azure.cosmosdb.rx; -import static org.assertj.core.api.Assertions.assertThat; import java.util.UUID; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.Permission; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.User; - -import rx.Observable; - -import javax.net.ssl.SSLException; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmos.CosmosUser; +import com.microsoft.azure.cosmos.CosmosUserResponse; +import com.microsoft.azure.cosmos.CosmosUserSettings; +import reactor.core.publisher.Mono; public class UserCrudTest extends TestSuiteBase { - public final String databaseId = DatabaseForTest.generateId(); + public final String databaseId = CosmosDatabaseForTest.generateId(); - private Database createdDatabase; + private CosmosDatabase createdDatabase; - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuilders") - public UserCrudTest(AsyncDocumentClient.Builder clientBuilder) { + public UserCrudTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void createUser() throws Exception { //create user - User user = new User(); + CosmosUserSettings user = new CosmosUserSettings(); user.setId(UUID.randomUUID().toString()); - Observable> createObservable = client.createUser(getDatabaseLink(), user, null); + Mono createObservable = createdDatabase.createUser(user, null); // validate user creation - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(user.getId()) .notNullEtag() .build(); @@ -75,16 +74,16 @@ public void createUser() throws Exception { public void readUser() throws Exception { //create user - User user = new User(); + CosmosUserSettings user = new CosmosUserSettings(); user.setId(UUID.randomUUID().toString()); - User readBackUser = client.createUser(getDatabaseLink(), user, null).toBlocking().single().getResource(); + CosmosUser readBackUser = createdDatabase.createUser(user, null).block().getUser(); // read user - Observable> readObservable = client.readUser(readBackUser.getSelfLink(), null); + Mono readObservable = readBackUser.read(null); //validate user read - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(readBackUser.getId()) .notNullEtag() .build(); @@ -95,22 +94,22 @@ public void readUser() throws Exception { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void deleteUser() throws Exception { //create user - User user = new User(); + CosmosUserSettings user = new CosmosUserSettings(); user.setId(UUID.randomUUID().toString()); - User readBackUser = client.createUser(getDatabaseLink(), user, null).toBlocking().single().getResource(); + CosmosUser readBackUser = createdDatabase.createUser(user, null).block().getUser(); // delete user - Observable> deleteObservable = client.deleteUser(readBackUser.getSelfLink(), null); + Mono deleteObservable = readBackUser.delete(null); // validate user delete - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .nullResource() .build(); validateSuccess(deleteObservable, validator); // attempt to read the user which was deleted - Observable> readObservable = client.readUser(readBackUser.getSelfLink(), null); + Mono readObservable = readBackUser.read(null); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); validateFailure(readObservable, notFoundValidator); } @@ -119,76 +118,48 @@ public void deleteUser() throws Exception { public void upsertUser() throws Exception { //create user - User user = new User(); + CosmosUserSettings user = new CosmosUserSettings(); user.setId(UUID.randomUUID().toString()); - User readBackUser = client.upsertUser(getDatabaseLink(), user, null).toBlocking().single().getResource(); - - // read user to validate creation - Observable> readObservable = client.readUser(readBackUser.getSelfLink(), null); + Mono upsertObservable = createdDatabase.upsertUser(user, null); - //validate user read - ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() - .withId(readBackUser.getId()) + //validate user upsert + CosmosResponseValidator validatorForUpsert = new CosmosResponseValidator.Builder() + .withId(user.getId()) .notNullEtag() .build(); - validateSuccess(readObservable, validatorForRead); - - client.readUsers(getDatabaseLink(), null).toBlocking().subscribe(users -> { - try { - int initialNumberOfUsers = users.getResults().size(); - //update user - readBackUser.setId(UUID.randomUUID().toString()); - - Observable> updateObservable = client.upsertUser(getDatabaseLink(), readBackUser, null); - - // validate user upsert - ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() - .withId(readBackUser.getId()) - .notNullEtag() - .build(); - - validateSuccess(updateObservable, validatorForUpdate); - - //verify that new user is added due to upsert with changed id - client.readUsers(getDatabaseLink(), null).toBlocking().subscribe(newUsers ->{ - int finalNumberOfUsers = newUsers.getResults().size(); - assertThat(finalNumberOfUsers).isEqualTo(initialNumberOfUsers + 1); - }); - } catch (Exception e) { - e.printStackTrace(); - } - }); + validateSuccess(upsertObservable, validatorForUpsert); } - + @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void replaceUser() throws Exception { //create user - User user = new User(); + CosmosUserSettings user = new CosmosUserSettings(); user.setId(UUID.randomUUID().toString()); - User readBackUser = client.createUser(getDatabaseLink(), user, null).toBlocking().single().getResource(); + CosmosUserSettings readBackUser = createdDatabase.createUser(user, null).block().getCosmosUserSettings(); // read user to validate creation - Observable> readObservable = client.readUser(readBackUser.getSelfLink(), null); + Mono readObservable = createdDatabase.getUser(user.getId()).read(); //validate user read - ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() - .withId(readBackUser.getId()) + CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() + .withId(readBackUser.getId()) .notNullEtag() .build(); validateSuccess(readObservable, validatorForRead); //update user + String oldId = readBackUser.getId(); readBackUser.setId(UUID.randomUUID().toString()); - Observable> updateObservable = client.replaceUser(readBackUser, null); + Mono updateObservable = createdDatabase.getUser(oldId).replace(readBackUser, null); // validate user replace - ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() + CosmosResponseValidator validatorForUpdate = new CosmosResponseValidator.Builder() .withId(readBackUser.getId()) .notNullEtag() .build(); @@ -199,18 +170,12 @@ public void replaceUser() throws Exception { @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - Database d = new Database(); - d.setId(databaseId); - createdDatabase = createDatabase(client, d); + createdDatabase = createDatabase(client, databaseId); } @AfterClass(groups = { "emulator" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteDatabase(client, createdDatabase.getId()); + safeDeleteDatabase(createdDatabase); safeClose(client); } - - private String getDatabaseLink() { - return createdDatabase.getSelfLink(); - } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionCrudTest.java index ed03ec2026b2a..81f6109709890 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionCrudTest.java @@ -24,43 +24,44 @@ import java.util.UUID; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; - -import rx.Observable; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosRequestOptions; +import com.microsoft.azure.cosmos.CosmosResponse; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmos.CosmosUserDefinedFunction; +import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionResponse; +import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionSettings; +import reactor.core.publisher.Mono; public class UserDefinedFunctionCrudTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; - - private AsyncDocumentClient client; + private CosmosContainer createdCollection; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public UserDefinedFunctionCrudTest(AsyncDocumentClient.Builder clientBuilder) { + public UserDefinedFunctionCrudTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createUserDefinedFunction() throws Exception { // create udf - UserDefinedFunction udf = new UserDefinedFunction(); + CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); - Observable> createObservable = client.createUserDefinedFunction(getCollectionLink(), udf, null); + Mono createObservable = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()); // validate udf creation - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(udf.getId()) .withUserDefinedFunctionBody("function() {var x = 10;}") .notNullEtag() @@ -71,18 +72,17 @@ public void createUserDefinedFunction() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readUserDefinedFunction() throws Exception { // create a udf - UserDefinedFunction udf = new UserDefinedFunction(); + CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); - UserDefinedFunction readBackUdf = client.createUserDefinedFunction(getCollectionLink(), udf, null).toBlocking().single().getResource(); - + CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().getCosmosUserDefinedFunction(); // read udf waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readUserDefinedFunction(readBackUdf.getSelfLink(), null); + Mono readObservable = readBackUdf.read(null); //validate udf read - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(udf.getId()) .withUserDefinedFunctionBody("function() {var x = 10;}") .notNullEtag() @@ -93,16 +93,16 @@ public void readUserDefinedFunction() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteUserDefinedFunction() throws Exception { // create a udf - UserDefinedFunction udf = new UserDefinedFunction(); + CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); - UserDefinedFunction readBackUdf = client.createUserDefinedFunction(getCollectionLink(), udf, null).toBlocking().single().getResource(); + CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().getCosmosUserDefinedFunction(); // delete udf - Observable> deleteObservable = client.deleteUserDefinedFunction(readBackUdf.getSelfLink(), null); + Mono deleteObservable = readBackUdf.delete(new CosmosRequestOptions()); // validate udf delete - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .nullResource() .build(); validateSuccess(deleteObservable, validator); @@ -111,16 +111,12 @@ public void deleteUserDefinedFunction() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_MULTI_PARTITION_COLLECTION; + createdCollection = getSharedMultiPartitionCosmosContainer(client); } - + @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } - private String getCollectionLink() { - return createdCollection.getSelfLink(); - } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionQueryTest.java index b8ffbc79fe9f0..aa0449c0a7f30 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionQueryTest.java @@ -29,37 +29,37 @@ import java.util.UUID; import java.util.stream.Collectors; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosRequestOptions; +import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionSettings; import com.microsoft.azure.cosmosdb.Database; import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; - -import rx.Observable; +import reactor.core.publisher.Flux; public class UserDefinedFunctionQueryTest extends TestSuiteBase { private Database createdDatabase; - private DocumentCollection createdCollection; - private List createdUDF = new ArrayList<>(); + private CosmosContainer createdCollection; + private List createdUDF = new ArrayList<>(); - private AsyncDocumentClient client; + private CosmosClient client; public String getCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); } @Factory(dataProvider = "clientBuildersWithDirect") - public UserDefinedFunctionQueryTest(Builder clientBuilder) { + public UserDefinedFunctionQueryTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -71,19 +71,18 @@ public void queryWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(5); - Observable> queryObservable = client - .queryUserDefinedFunctions(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); - List expectedDocs = createdUDF.stream().filter(sp -> filterId.equals(sp.getId()) ).collect(Collectors.toList()); + List expectedDocs = createdUDF.stream().filter(sp -> filterId.equals(sp.getId()) ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -96,13 +95,12 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryUserDefinedFunctions(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -115,21 +113,20 @@ public void queryAll() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(3); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryUserDefinedFunctions(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); - List expectedDocs = createdUDF; + List expectedDocs = createdUDF; int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() .map(d -> d.getResourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -140,8 +137,7 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = client - .queryUserDefinedFunctions(getCollectionLink(), query, options); + Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(DocumentClientException.class) @@ -151,20 +147,19 @@ public void invalidQuerySytax() throws Exception { validateQueryFailure(queryObservable, validator); } - public UserDefinedFunction createUserDefinedFunction(AsyncDocumentClient client) { - UserDefinedFunction storedProcedure = getUserDefinedFunctionDef(); - return client.createUserDefinedFunction(getCollectionLink(), storedProcedure, null).toBlocking().single().getResource(); + public CosmosUserDefinedFunctionSettings createUserDefinedFunction(CosmosContainer cosmosContainer) { + CosmosUserDefinedFunctionSettings storedProcedure = getUserDefinedFunctionDef(); + return cosmosContainer.createUserDefinedFunction(storedProcedure, new CosmosRequestOptions()).block().getCosmosUserDefinedFunctionSettings(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); for(int i = 0; i < 5; i++) { - createdUDF.add(createUserDefinedFunction(client)); + createdUDF.add(createUserDefinedFunction(createdCollection)); } waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -175,8 +170,8 @@ public void afterClass() { safeClose(client); } - private static UserDefinedFunction getUserDefinedFunctionDef() { - UserDefinedFunction udf = new UserDefinedFunction(); + private static CosmosUserDefinedFunctionSettings getUserDefinedFunctionDef() { + CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); return udf; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionUpsertReplaceTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionUpsertReplaceTest.java index 5d35cf792b2b6..793b5ad6581bc 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionUpsertReplaceTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionUpsertReplaceTest.java @@ -24,6 +24,7 @@ import java.util.UUID; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -31,91 +32,42 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; - -import rx.Observable; - -import javax.net.ssl.SSLException; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosRequestOptions; +import com.microsoft.azure.cosmos.CosmosResponseValidator; +import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionResponse; +import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionSettings; +import com.microsoft.azure.cosmosdb.RequestOptions; +import reactor.core.publisher.Mono; public class UserDefinedFunctionUpsertReplaceTest extends TestSuiteBase { - private Database createdDatabase; - private DocumentCollection createdCollection; + private CosmosContainer createdCollection; - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuildersWithDirect") - public UserDefinedFunctionUpsertReplaceTest(AsyncDocumentClient.Builder clientBuilder) { + public UserDefinedFunctionUpsertReplaceTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void upsertUserDefinedFunction() throws Exception { - - // create a udf - UserDefinedFunction udf = new UserDefinedFunction(); - udf.setId(UUID.randomUUID().toString()); - udf.setBody("function() {var x = 10;}"); - - UserDefinedFunction readBackUdf = null; - - try { - readBackUdf = client.upsertUserDefinedFunction(getCollectionLink(), udf, null).toBlocking().single().getResource(); - } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } - - // read udf to validate creation - waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readUserDefinedFunction(readBackUdf.getSelfLink(), null); - - // validate udf create - ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() - .withId(readBackUdf.getId()) - .withUserDefinedFunctionBody("function() {var x = 10;}") - .notNullEtag() - .build(); - validateSuccess(readObservable, validatorForRead); - - //update udf - readBackUdf.setBody("function() {var x = 11;}"); - - Observable> updateObservable = client.upsertUserDefinedFunction(getCollectionLink(), readBackUdf, null); - - // validate udf update - ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() - .withId(readBackUdf.getId()) - .withUserDefinedFunctionBody("function() {var x = 11;}") - .notNullEtag() - .build(); - validateSuccess(updateObservable, validatorForUpdate); - } - @Test(groups = { "simple" }, timeOut = TIMEOUT) public void replaceUserDefinedFunction() throws Exception { // create a udf - UserDefinedFunction udf = new UserDefinedFunction(); + CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); udf.setId(UUID.randomUUID().toString()); udf.setBody("function() {var x = 10;}"); - UserDefinedFunction readBackUdf = null; + CosmosUserDefinedFunctionSettings readBackUdf = null; try { - readBackUdf = client.createUserDefinedFunction(getCollectionLink(), udf, null).toBlocking().single().getResource(); + readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().getCosmosUserDefinedFunctionSettings(); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -124,10 +76,10 @@ public void replaceUserDefinedFunction() throws Exception { // read udf to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder); - Observable> readObservable = client.readUserDefinedFunction(readBackUdf.getSelfLink(), null); + Mono readObservable = createdCollection.getUserDefinedFunction(readBackUdf.getId()).read(new RequestOptions()); // validate udf creation - ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() + CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() .withId(readBackUdf.getId()) .withUserDefinedFunctionBody("function() {var x = 10;}") .notNullEtag() @@ -137,10 +89,10 @@ public void replaceUserDefinedFunction() throws Exception { //update udf readBackUdf.setBody("function() {var x = 11;}"); - Observable> replaceObservable = client.replaceUserDefinedFunction(readBackUdf, null); + Mono replaceObservable = createdCollection.getUserDefinedFunction(readBackUdf.getId()).replace(readBackUdf, new RequestOptions()); //validate udf replace - ResourceResponseValidator validatorForReplace = new ResourceResponseValidator.Builder() + CosmosResponseValidator validatorForReplace = new CosmosResponseValidator.Builder() .withId(readBackUdf.getId()) .withUserDefinedFunctionBody("function() {var x = 11;}") .notNullEtag() @@ -151,16 +103,12 @@ public void replaceUserDefinedFunction() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - truncateCollection(createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } - - private String getCollectionLink() { - return createdCollection.getSelfLink(); - } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserQueryTest.java index a1feb7046b18c..5003dd13cfe1e 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserQueryTest.java @@ -29,35 +29,33 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DatabaseForTest; +import com.microsoft.azure.cosmos.CosmosClientBuilder; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosDatabase; +import com.microsoft.azure.cosmos.CosmosDatabaseForTest; +import com.microsoft.azure.cosmos.CosmosUserSettings; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; -import rx.Observable; +import reactor.core.publisher.Flux; public class UserQueryTest extends TestSuiteBase { - public final String databaseId = DatabaseForTest.generateId(); + public final String databaseId = CosmosDatabaseForTest.generateId(); - private List createdUsers = new ArrayList<>(); + private List createdUsers = new ArrayList<>(); - private AsyncDocumentClient client; + private CosmosClient client; + private CosmosDatabase createdDatabase; - private String getDatabaseLink() { - return Utils.getDatabaseNameLink(databaseId); - } - @Factory(dataProvider = "clientBuilders") - public UserQueryTest(Builder clientBuilder) { + public UserQueryTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @@ -69,20 +67,20 @@ public void queryUsersWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(5); - Observable> queryObservable = client.queryUsers(getDatabaseLink(), query, options); + Flux> queryObservable = createdDatabase.queryUsers(query, options); - List expectedUsers = createdUsers.stream() + List expectedUsers = createdUsers.stream() .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -97,19 +95,19 @@ public void queryAllUsers() throws Exception { FeedOptions options = new FeedOptions(); options.setMaxItemCount(2); String databaseLink = Utils.getDatabaseNameLink(databaseId); - Observable> queryObservable = client.queryUsers(databaseLink, query, options); + Flux> queryObservable = createdDatabase.queryUsers(query, options); - List expectedUsers = createdUsers; + List expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -121,12 +119,12 @@ public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - Observable> queryObservable = client.queryUsers(getDatabaseLink(), query, options); + Flux> queryObservable = createdDatabase.queryUsers(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -136,14 +134,12 @@ public void queryUsers_NoResults() throws Exception { public void beforeClass() throws Exception { client = clientBuilder.build(); - Database d1 = new Database(); - d1.setId(databaseId); - createDatabase(client, d1); + createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { - User user = new User(); + CosmosUserSettings user = new CosmosUserSettings(); user.setId(UUID.randomUUID().toString()); - createdUsers.add(createUser(client, databaseId, user)); + createdUsers.add(createUser(client, databaseId, user).read().block().getCosmosUserSettings()); } waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -151,7 +147,7 @@ public void beforeClass() throws Exception { @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteDatabase(client, databaseId); + safeDeleteDatabase(createdDatabase); safeClose(client); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java index bbb9072868dbf..99750757ed8d0 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java @@ -22,20 +22,26 @@ */ package com.microsoft.azure.cosmosdb.rx; +import com.microsoft.azure.cosmos.CosmosClient; +import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.microsoft.azure.cosmos.CosmosContainer; +import com.microsoft.azure.cosmos.CosmosItemRequestOptions; +import com.microsoft.azure.cosmos.CosmosItemResponse; +import com.microsoft.azure.cosmos.CosmosResponseValidator; import com.microsoft.azure.cosmosdb.Database; import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.RetryAnalyzer; import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; + +import reactor.core.publisher.Mono; + import org.apache.commons.lang3.StringUtils; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; import java.util.UUID; @@ -45,28 +51,30 @@ public class VeryLargeDocumentQueryTest extends TestSuiteBase { private final static int TIMEOUT = 60000; private final static int SETUP_TIMEOUT = 60000; private Database createdDatabase; - private DocumentCollection createdCollection; + private CosmosContainer createdCollection; - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "simpleClientBuildersWithDirect") - public VeryLargeDocumentQueryTest(Builder clientBuilder) { + public VeryLargeDocumentQueryTest(CosmosClientBuilder clientBuilder) { this.clientBuilder = clientBuilder; } @Test(groups = { "emulator" }, timeOut = TIMEOUT, retryAnalyzer = RetryAnalyzer.class) - public void queryLargeDocuments() { + public void queryLargeDocuments() throws InterruptedException { int cnt = 5; for(int i = 0; i < cnt; i++) { createLargeDocument(); } try { - validateQuerySuccess(client.queryDocuments(getCollectionLink(), "SELECT * FROM r", null), + FeedOptions options = new FeedOptions(); + options.setEnableCrossPartitionQuery(true); + validateQuerySuccess(createdCollection.queryItems("SELECT * FROM r", options), new FeedResponseListValidator.Builder().totalSize(cnt).build()); } catch (Throwable error) { - if (this.clientBuilder.configs.getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.desiredConsistencyLevel); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -74,17 +82,16 @@ public void queryLargeDocuments() { } } - private void createLargeDocument() { + private void createLargeDocument() throws InterruptedException { Document docDefinition = getDocumentDefinition(); //Keep size as ~ 1.999MB to account for size of other props int size = (int) (ONE_MB * 1.999); docDefinition.set("largeString", StringUtils.repeat("x", size)); - Observable> createObservable = client - .createDocument(getCollectionLink(), docDefinition, null, false); + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.getId()) .build(); @@ -94,9 +101,8 @@ private void createLargeDocument() { @BeforeClass(groups = { "emulator" }, timeOut = 2 * SETUP_TIMEOUT) public void beforeClass() throws Exception { client = clientBuilder.build(); - createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; - truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + truncateCollection(createdCollection); } @AfterClass(groups = { "emulator" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTests1.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTests1.java index a7d110a9b8c3e..4d06338211b9d 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTests1.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTests1.java @@ -303,4 +303,4 @@ private static User getUserDefinition() { user.setId(USER_NAME); return user; } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java index fd2a6dba097cd..fd02c4a8989c2 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java @@ -53,7 +53,6 @@ import com.microsoft.azure.cosmosdb.rx.FailureValidator; import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; import org.apache.commons.collections4.map.UnmodifiableMap; import org.apache.commons.lang3.StringUtils; import org.testng.SkipException; @@ -858,4 +857,4 @@ private boolean isSessionEqual(SessionContainer sessionContainer1, SessionContai return true; } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentQuerySpyWireContentTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentQuerySpyWireContentTest.java index 79e792a5c0cfa..0e623bda8e3ff 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentQuerySpyWireContentTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentQuerySpyWireContentTest.java @@ -43,17 +43,11 @@ import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.Index; -import com.microsoft.azure.cosmosdb.IndexingPolicy; import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.internal.HttpConstants; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; import com.microsoft.azure.cosmosdb.rx.SpyClientBuilder; -import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; import com.microsoft.azure.cosmosdb.rx.Utils; import io.netty.buffer.ByteBuf; @@ -219,4 +213,4 @@ private static Document getDocumentDefinition(int cnt) { , uuid, cnt, cnt)); return doc; } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/NetworkFailureTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/NetworkFailureTest.java index 4ce4abf58452b..81ffc4d664447 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/NetworkFailureTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/NetworkFailureTest.java @@ -28,9 +28,7 @@ import com.microsoft.azure.cosmosdb.ResourceResponse; import com.microsoft.azure.cosmosdb.internal.ResourceType; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.CollectionCrudTest; import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; import org.mockito.Mockito; import org.testng.annotations.AfterClass; import org.testng.annotations.Factory; @@ -97,4 +95,4 @@ public void afterClass() { safeDeleteCollection(client, collectionDefinition); client.close(); } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryCreateDocumentTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryCreateDocumentTest.java index 536ac8e7c38bf..64fb216cc7624 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryCreateDocumentTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryCreateDocumentTest.java @@ -36,7 +36,6 @@ import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.rx.FailureValidator; import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; -import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -214,4 +213,4 @@ private Document getDocumentDefinition() { public void afterClass() { safeClose(client); } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java index 63498109452c4..efc3b44043e54 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java @@ -24,17 +24,14 @@ package com.microsoft.azure.cosmosdb.rx.internal; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.doAnswer; -import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.AfterClass; @@ -48,7 +45,6 @@ import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.ResourceResponse; import com.microsoft.azure.cosmosdb.RetryOptions; import com.microsoft.azure.cosmosdb.internal.HttpConstants; @@ -57,7 +53,6 @@ import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; import rx.Observable; @@ -162,7 +157,7 @@ private void afterMethod() { public void beforeClass() { // set up the client database = SHARED_DATABASE; - collection = SHARED_SINGLE_PARTITION_COLLECTION_WITHOUT_PARTITION_KEY; + collection = SHARED_SINGLE_PARTITION_COLLECTION; } private Document getDocumentDefinition() { @@ -179,4 +174,4 @@ private Document getDocumentDefinition() { @AfterClass(groups = { "long" }, timeOut = SHUTDOWN_TIMEOUT, enabled = false) public void afterClass() { } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientUnderTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientUnderTest.java index 3cf2844149a31..a59078f224f73 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientUnderTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientUnderTest.java @@ -22,6 +22,7 @@ */ package com.microsoft.azure.cosmosdb.rx.internal; +import com.microsoft.azure.cosmos.ClientUnderTestBuilder; import com.microsoft.azure.cosmosdb.ConnectionPolicy; import com.microsoft.azure.cosmosdb.ConsistencyLevel; import com.microsoft.azure.cosmosdb.ISessionContainer; @@ -46,7 +47,7 @@ import static org.mockito.Mockito.doAnswer; /** - * This class in conjunction with {@link com.microsoft.azure.cosmosdb.rx.ClientUnderTestBuilder} + * This class in conjunction with {@link ClientUnderTestBuilder} * provides the functionality for spying the client behavior and the http requests sent. */ public class RxDocumentClientUnderTest extends RxDocumentClientImpl { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/SessionTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/SessionTest.java index 209bc4e792df6..7cb4c83c7b319 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/SessionTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/SessionTest.java @@ -26,9 +26,11 @@ import com.microsoft.azure.cosmosdb.Database; import com.microsoft.azure.cosmosdb.Document; import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; +import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.internal.HttpConstants; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; @@ -46,6 +48,7 @@ import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.net.URLDecoder; +import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; @@ -61,6 +64,7 @@ public class SessionTest extends TestSuiteBase { private SpyClientUnderTestFactory.SpyBaseClass> spyClient; private AsyncDocumentClient houseKeepingClient; private ConnectionMode connectionMode; + private RequestOptions options; @Factory(dataProvider = "clientBuildersWithDirectSession") public SessionTest(AsyncDocumentClient.Builder clientBuilder) { @@ -80,9 +84,16 @@ public Object[] sessionTestArgProvider() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { createdDatabase = SHARED_DATABASE; - + + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + DocumentCollection collection = new DocumentCollection(); collection.setId(collectionId); + collection.setPartitionKey(partitionKeyDef); + createdCollection = createCollection(createGatewayHouseKeepingDocumentClient().build(), createdDatabase.getId(), collection, null); houseKeepingClient = clientBuilder.build(); @@ -93,6 +104,8 @@ public void beforeClass() { } else { spyClient = SpyClientUnderTestFactory.createClientUnderTest(clientBuilder); } + options = new RequestOptions(); + options.setPartitionKey(PartitionKey.None); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) @@ -131,12 +144,12 @@ public void sessionConsistency_ReadYourWrites(boolean isNameBased) { assertThat(getSessionTokensInRequests().get(3 * i + 0)).isNotEmpty(); } - spyClient.readDocument(getDocumentLink(documentCreated, isNameBased), null).toBlocking().single(); + spyClient.readDocument(getDocumentLink(documentCreated, isNameBased), options).toBlocking().single(); assertThat(getSessionTokensInRequests()).hasSize(3 * i + 2); assertThat(getSessionTokensInRequests().get(3 * i + 1)).isNotEmpty(); - spyClient.readDocument(getDocumentLink(documentCreated, isNameBased), null).toBlocking().single(); + spyClient.readDocument(getDocumentLink(documentCreated, isNameBased), options).toBlocking().single(); assertThat(getSessionTokensInRequests()).hasSize(3 * i + 3); assertThat(getSessionTokensInRequests().get(3 * i + 2)).isNotEmpty(); @@ -152,7 +165,7 @@ public void sessionTokenInDocumentRead(boolean isNameBased) throws UnsupportedEn .getResource(); final String documentLink = getDocumentLink(document, isNameBased); - spyClient.readDocument(documentLink, null).toBlocking().single() + spyClient.readDocument(documentLink, options).toBlocking().single() .getResource(); List> documentReadHttpRequests = spyClient.getCapturedRequests().stream() diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/StoreHeaderTests.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/StoreHeaderTests.java index ecdb689b542b9..c7efac21b137d 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/StoreHeaderTests.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/StoreHeaderTests.java @@ -27,7 +27,6 @@ import com.microsoft.azure.cosmosdb.DocumentCollection; import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -86,4 +85,4 @@ private Document getDocumentDefinition() { , uuid, uuid)); return doc; } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java new file mode 100644 index 0000000000000..6465e8ed135e8 --- /dev/null +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java @@ -0,0 +1,1045 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmosdb.rx.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import com.microsoft.azure.cosmosdb.DataType; +import com.microsoft.azure.cosmosdb.DatabaseForTest; +import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.microsoft.azure.cosmosdb.IncludedPath; +import com.microsoft.azure.cosmosdb.Index; +import com.microsoft.azure.cosmosdb.IndexingPolicy; +import com.microsoft.azure.cosmosdb.RetryOptions; +import com.microsoft.azure.cosmosdb.SqlQuerySpec; +import com.microsoft.azure.cosmosdb.Undefined; +import com.microsoft.azure.cosmosdb.internal.PathParser; +import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.microsoft.azure.cosmosdb.rx.internal.Configs; +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; +import org.mockito.stubbing.Answer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.DataProvider; + +import com.microsoft.azure.cosmosdb.CompositePath; +import com.microsoft.azure.cosmosdb.CompositePathSortOrder; +import com.microsoft.azure.cosmosdb.ConnectionMode; +import com.microsoft.azure.cosmosdb.ConnectionPolicy; +import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.microsoft.azure.cosmosdb.Database; +import com.microsoft.azure.cosmosdb.Document; +import com.microsoft.azure.cosmosdb.DocumentCollection; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.microsoft.azure.cosmosdb.User; +import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; +import com.microsoft.azure.cosmosdb.rx.FailureValidator; +import com.microsoft.azure.cosmosdb.rx.FeedResponseListValidator; +import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; +import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +import com.microsoft.azure.cosmosdb.rx.Utils; + +import org.testng.annotations.Test; +import rx.Observable; +import rx.observers.TestSubscriber; + +public class TestSuiteBase { + private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; + private static final ObjectMapper objectMapper = new ObjectMapper(); + protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); + protected static final int TIMEOUT = 40000; + protected static final int FEED_TIMEOUT = 40000; + protected static final int SETUP_TIMEOUT = 60000; + protected static final int SHUTDOWN_TIMEOUT = 12000; + + protected static final int SUITE_SETUP_TIMEOUT = 120000; + protected static final int SUITE_SHUTDOWN_TIMEOUT = 60000; + + protected static final int WAIT_REPLICA_CATCH_UP_IN_MILLIS = 4000; + + protected final static ConsistencyLevel accountConsistency; + protected static final ImmutableList preferredLocations; + private static final ImmutableList desiredConsistencies; + private static final ImmutableList protocols; + + protected int subscriberValidationTimeout = TIMEOUT; + protected Builder clientBuilder; + + protected static Database SHARED_DATABASE; + protected static DocumentCollection SHARED_MULTI_PARTITION_COLLECTION; + protected static DocumentCollection SHARED_SINGLE_PARTITION_COLLECTION; + protected static DocumentCollection SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES; + + static { + accountConsistency = parseConsistency(TestConfigurations.CONSISTENCY); + desiredConsistencies = immutableListOrNull( + ObjectUtils.defaultIfNull(parseDesiredConsistencies(TestConfigurations.DESIRED_CONSISTENCIES), + allEqualOrLowerConsistencies(accountConsistency))); + preferredLocations = immutableListOrNull(parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS)); + protocols = ObjectUtils.defaultIfNull(immutableListOrNull(parseProtocols(TestConfigurations.PROTOCOLS)), + ImmutableList.of(Protocol.Https, Protocol.Tcp)); + } + + protected TestSuiteBase() { + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); + objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); + objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); + logger.debug("Initializing {} ...", this.getClass().getSimpleName()); + } + + private static ImmutableList immutableListOrNull(List list) { + return list != null ? ImmutableList.copyOf(list) : null; + } + + @BeforeMethod(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}) + public void beforeMethod(Method method) { + if (this.clientBuilder != null) { + logger.info("Starting {}::{} using {} {} mode with {} consistency", + method.getDeclaringClass().getSimpleName(), method.getName(), + this.clientBuilder.getConnectionPolicy().getConnectionMode(), + this.clientBuilder.getConfigs().getProtocol(), + this.clientBuilder.getDesiredConsistencyLevel()); + return; + } + logger.info("Starting {}::{}", method.getDeclaringClass().getSimpleName(), method.getName()); + } + + @AfterMethod(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}) + public void afterMethod(Method m) { + Test t = m.getAnnotation(Test.class); + logger.info("Finished {}:{}.", m.getDeclaringClass().getSimpleName(), m.getName()); + } + + private static class DatabaseManagerImpl implements DatabaseForTest.DatabaseManager { + public static DatabaseManagerImpl getInstance(AsyncDocumentClient client) { + return new DatabaseManagerImpl(client); + } + + private final AsyncDocumentClient client; + + private DatabaseManagerImpl(AsyncDocumentClient client) { + this.client = client; + } + + @Override + public Observable> queryDatabases(SqlQuerySpec query) { + return client.queryDatabases(query, null); + } + + @Override + public Observable> createDatabase(Database databaseDefinition) { + return client.createDatabase(databaseDefinition, null); + } + + @Override + public Observable> deleteDatabase(String id) { + + return client.deleteDatabase("dbs/" + id, null); + } + } + + @BeforeSuite(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}, timeOut = SUITE_SETUP_TIMEOUT) + public static void beforeSuite() { + logger.info("beforeSuite Started"); + AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); + try { + DatabaseForTest dbForTest = DatabaseForTest.create(DatabaseManagerImpl.getInstance(houseKeepingClient)); + SHARED_DATABASE = dbForTest.createdDatabase; + RequestOptions options = new RequestOptions(); + options.setOfferThroughput(10100); + SHARED_MULTI_PARTITION_COLLECTION = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinitionWithRangeRangeIndex(), options); + SHARED_SINGLE_PARTITION_COLLECTION = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinition(), null); + SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes(), options); + } finally { + houseKeepingClient.close(); + } + } + + @AfterSuite(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}, timeOut = SUITE_SHUTDOWN_TIMEOUT) + public static void afterSuite() { + logger.info("afterSuite Started"); + AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); + try { + safeDeleteDatabase(houseKeepingClient, SHARED_DATABASE); + DatabaseForTest.cleanupStaleTestDatabases(DatabaseManagerImpl.getInstance(houseKeepingClient)); + } finally { + safeClose(houseKeepingClient); + } + } + + protected static void truncateCollection(DocumentCollection collection) { + logger.info("Truncating collection {} ...", collection.getId()); + AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); + try { + List paths = collection.getPartitionKey().getPaths(); + + FeedOptions options = new FeedOptions(); + options.setMaxDegreeOfParallelism(-1); + options.setEnableCrossPartitionQuery(true); + options.setMaxItemCount(100); + + logger.info("Truncating collection {} documents ...", collection.getId()); + + houseKeepingClient.queryDocuments(collection.getSelfLink(), "SELECT * FROM root", options) + .flatMap(page -> Observable.from(page.getResults())) + .flatMap(doc -> { + RequestOptions requestOptions = new RequestOptions(); + + if (paths != null && !paths.isEmpty()) { + List pkPath = PathParser.getPathParts(paths.get(0)); + Object propertyValue = doc.getObjectByPath(pkPath); + if (propertyValue == null) { + propertyValue = Undefined.Value(); + } + + requestOptions.setPartitionKey(new PartitionKey(propertyValue)); + } + + return houseKeepingClient.deleteDocument(doc.getSelfLink(), requestOptions); + }).toCompletable().await(); + + logger.info("Truncating collection {} triggers ...", collection.getId()); + + houseKeepingClient.queryTriggers(collection.getSelfLink(), "SELECT * FROM root", options) + .flatMap(page -> Observable.from(page.getResults())) + .flatMap(trigger -> { + RequestOptions requestOptions = new RequestOptions(); + +// if (paths != null && !paths.isEmpty()) { +// Object propertyValue = trigger.getObjectByPath(PathParser.getPathParts(paths.get(0))); +// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); +// } + + return houseKeepingClient.deleteTrigger(trigger.getSelfLink(), requestOptions); + }).toCompletable().await(); + + logger.info("Truncating collection {} storedProcedures ...", collection.getId()); + + houseKeepingClient.queryStoredProcedures(collection.getSelfLink(), "SELECT * FROM root", options) + .flatMap(page -> Observable.from(page.getResults())) + .flatMap(storedProcedure -> { + RequestOptions requestOptions = new RequestOptions(); + +// if (paths != null && !paths.isEmpty()) { +// Object propertyValue = storedProcedure.getObjectByPath(PathParser.getPathParts(paths.get(0))); +// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); +// } + + return houseKeepingClient.deleteStoredProcedure(storedProcedure.getSelfLink(), requestOptions); + }).toCompletable().await(); + + logger.info("Truncating collection {} udfs ...", collection.getId()); + + houseKeepingClient.queryUserDefinedFunctions(collection.getSelfLink(), "SELECT * FROM root", options) + .flatMap(page -> Observable.from(page.getResults())) + .flatMap(udf -> { + RequestOptions requestOptions = new RequestOptions(); + +// if (paths != null && !paths.isEmpty()) { +// Object propertyValue = udf.getObjectByPath(PathParser.getPathParts(paths.get(0))); +// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); +// } + + return houseKeepingClient.deleteUserDefinedFunction(udf.getSelfLink(), requestOptions); + }).toCompletable().await(); + + } finally { + houseKeepingClient.close(); + } + + logger.info("Finished truncating collection {}.", collection.getId()); + } + + protected static void waitIfNeededForReplicasToCatchUp(Builder clientBuilder) { + switch (clientBuilder.getDesiredConsistencyLevel()) { + case Eventual: + case ConsistentPrefix: + logger.info(" additional wait in Eventual mode so the replica catch up"); + // give times to replicas to catch up after a write + try { + TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); + } catch (Exception e) { + logger.error("unexpected failure", e); + } + + case Session: + case BoundedStaleness: + case Strong: + default: + break; + } + } + + public static DocumentCollection createCollection(String databaseId, + DocumentCollection collection, + RequestOptions options) { + AsyncDocumentClient client = createGatewayHouseKeepingDocumentClient().build(); + try { + return client.createCollection("dbs/" + databaseId, collection, options).toBlocking().single().getResource(); + } finally { + client.close(); + } + } + + public static DocumentCollection createCollection(AsyncDocumentClient client, String databaseId, + DocumentCollection collection, RequestOptions options) { + return client.createCollection("dbs/" + databaseId, collection, options).toBlocking().single().getResource(); + } + + public static DocumentCollection createCollection(AsyncDocumentClient client, String databaseId, + DocumentCollection collection) { + return client.createCollection("dbs/" + databaseId, collection, null).toBlocking().single().getResource(); + } + + private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { + final String NUMBER_FIELD = "numberField"; + final String STRING_FIELD = "stringField"; + final String NUMBER_FIELD_2 = "numberField2"; + final String STRING_FIELD_2 = "stringField2"; + final String BOOL_FIELD = "boolField"; + final String NULL_FIELD = "nullField"; + final String OBJECT_FIELD = "objectField"; + final String ARRAY_FIELD = "arrayField"; + final String SHORT_STRING_FIELD = "shortStringField"; + final String MEDIUM_STRING_FIELD = "mediumStringField"; + final String LONG_STRING_FIELD = "longStringField"; + final String PARTITION_KEY = "pk"; + + DocumentCollection documentCollection = new DocumentCollection(); + + IndexingPolicy indexingPolicy = new IndexingPolicy(); + Collection> compositeIndexes = new ArrayList>(); + + //Simple + ArrayList compositeIndexSimple = new ArrayList(); + CompositePath compositePath1 = new CompositePath(); + compositePath1.setPath("/" + NUMBER_FIELD); + compositePath1.setOrder(CompositePathSortOrder.Ascending); + + CompositePath compositePath2 = new CompositePath(); + compositePath2.setPath("/" + STRING_FIELD); + compositePath2.setOrder(CompositePathSortOrder.Descending); + + compositeIndexSimple.add(compositePath1); + compositeIndexSimple.add(compositePath2); + + //Max Columns + ArrayList compositeIndexMaxColumns = new ArrayList(); + CompositePath compositePath3 = new CompositePath(); + compositePath3.setPath("/" + NUMBER_FIELD); + compositePath3.setOrder(CompositePathSortOrder.Descending); + + CompositePath compositePath4 = new CompositePath(); + compositePath4.setPath("/" + STRING_FIELD); + compositePath4.setOrder(CompositePathSortOrder.Ascending); + + CompositePath compositePath5 = new CompositePath(); + compositePath5.setPath("/" + NUMBER_FIELD_2); + compositePath5.setOrder(CompositePathSortOrder.Descending); + + CompositePath compositePath6 = new CompositePath(); + compositePath6.setPath("/" + STRING_FIELD_2); + compositePath6.setOrder(CompositePathSortOrder.Ascending); + + compositeIndexMaxColumns.add(compositePath3); + compositeIndexMaxColumns.add(compositePath4); + compositeIndexMaxColumns.add(compositePath5); + compositeIndexMaxColumns.add(compositePath6); + + //Primitive Values + ArrayList compositeIndexPrimitiveValues = new ArrayList(); + CompositePath compositePath7 = new CompositePath(); + compositePath7.setPath("/" + NUMBER_FIELD); + compositePath7.setOrder(CompositePathSortOrder.Descending); + + CompositePath compositePath8 = new CompositePath(); + compositePath8.setPath("/" + STRING_FIELD); + compositePath8.setOrder(CompositePathSortOrder.Ascending); + + CompositePath compositePath9 = new CompositePath(); + compositePath9.setPath("/" + BOOL_FIELD); + compositePath9.setOrder(CompositePathSortOrder.Descending); + + CompositePath compositePath10 = new CompositePath(); + compositePath10.setPath("/" + NULL_FIELD); + compositePath10.setOrder(CompositePathSortOrder.Ascending); + + compositeIndexPrimitiveValues.add(compositePath7); + compositeIndexPrimitiveValues.add(compositePath8); + compositeIndexPrimitiveValues.add(compositePath9); + compositeIndexPrimitiveValues.add(compositePath10); + + //Long Strings + ArrayList compositeIndexLongStrings = new ArrayList(); + CompositePath compositePath11 = new CompositePath(); + compositePath11.setPath("/" + STRING_FIELD); + + CompositePath compositePath12 = new CompositePath(); + compositePath12.setPath("/" + SHORT_STRING_FIELD); + + CompositePath compositePath13 = new CompositePath(); + compositePath13.setPath("/" + MEDIUM_STRING_FIELD); + + CompositePath compositePath14 = new CompositePath(); + compositePath14.setPath("/" + LONG_STRING_FIELD); + + compositeIndexLongStrings.add(compositePath11); + compositeIndexLongStrings.add(compositePath12); + compositeIndexLongStrings.add(compositePath13); + compositeIndexLongStrings.add(compositePath14); + + compositeIndexes.add(compositeIndexSimple); + compositeIndexes.add(compositeIndexMaxColumns); + compositeIndexes.add(compositeIndexPrimitiveValues); + compositeIndexes.add(compositeIndexLongStrings); + + indexingPolicy.setCompositeIndexes(compositeIndexes); + documentCollection.setIndexingPolicy(indexingPolicy); + + PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); + ArrayList partitionKeyPaths = new ArrayList(); + partitionKeyPaths.add("/" + PARTITION_KEY); + partitionKeyDefinition.setPaths(partitionKeyPaths); + documentCollection.setPartitionKey(partitionKeyDefinition); + + documentCollection.setId(UUID.randomUUID().toString()); + + return documentCollection; + } + + public static Document createDocument(AsyncDocumentClient client, String databaseId, String collectionId, Document document) { + return createDocument(client, databaseId, collectionId, document, null); + } + + public static Document createDocument(AsyncDocumentClient client, String databaseId, String collectionId, Document document, RequestOptions options) { + return client.createDocument(Utils.getCollectionNameLink(databaseId, collectionId), document, options, false).toBlocking().single().getResource(); + } + + public Observable> bulkInsert(AsyncDocumentClient client, + String collectionLink, + List documentDefinitionList, + int concurrencyLevel) { + ArrayList>> result = new ArrayList>>(documentDefinitionList.size()); + for (Document docDef : documentDefinitionList) { + result.add(client.createDocument(collectionLink, docDef, null, false)); + } + + return Observable.merge(result, concurrencyLevel); + } + + public Observable> bulkInsert(AsyncDocumentClient client, + String collectionLink, + List documentDefinitionList) { + return bulkInsert(client, collectionLink, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL); + } + + public List bulkInsertBlocking(AsyncDocumentClient client, + String collectionLink, + List documentDefinitionList) { + return bulkInsert(client, collectionLink, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) + .map(ResourceResponse::getResource) + .toList() + .toBlocking() + .single(); + } + + public static ConsistencyLevel getAccountDefaultConsistencyLevel(AsyncDocumentClient client) { + return client.getDatabaseAccount().toBlocking().single().getConsistencyPolicy().getDefaultConsistencyLevel(); + } + + public static User createUser(AsyncDocumentClient client, String databaseId, User user) { + return client.createUser("dbs/" + databaseId, user, null).toBlocking().single().getResource(); + } + + public static User safeCreateUser(AsyncDocumentClient client, String databaseId, User user) { + deleteUserIfExists(client, databaseId, user.getId()); + return createUser(client, databaseId, user); + } + + private static DocumentCollection safeCreateCollection(AsyncDocumentClient client, String databaseId, DocumentCollection collection, RequestOptions options) { + deleteCollectionIfExists(client, databaseId, collection.getId()); + return createCollection(client, databaseId, collection, options); + } + + public static String getCollectionLink(DocumentCollection collection) { + return collection.getSelfLink(); + } + + static protected DocumentCollection getCollectionDefinition() { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + + DocumentCollection collectionDefinition = new DocumentCollection(); + collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.setPartitionKey(partitionKeyDef); + + return collectionDefinition; + } + + static protected DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList<>(); + paths.add("/mypk"); + partitionKeyDef.setPaths(paths); + IndexingPolicy indexingPolicy = new IndexingPolicy(); + Collection includedPaths = new ArrayList<>(); + IncludedPath includedPath = new IncludedPath(); + includedPath.setPath("/*"); + Collection indexes = new ArrayList<>(); + Index stringIndex = Index.Range(DataType.String); + stringIndex.set("precision", -1); + indexes.add(stringIndex); + + Index numberIndex = Index.Range(DataType.Number); + numberIndex.set("precision", -1); + indexes.add(numberIndex); + includedPath.setIndexes(indexes); + includedPaths.add(includedPath); + indexingPolicy.setIncludedPaths(includedPaths); + + DocumentCollection collectionDefinition = new DocumentCollection(); + collectionDefinition.setIndexingPolicy(indexingPolicy); + collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.setPartitionKey(partitionKeyDef); + + return collectionDefinition; + } + + public static void deleteCollectionIfExists(AsyncDocumentClient client, String databaseId, String collectionId) { + List res = client.queryCollections("dbs/" + databaseId, + String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null).toBlocking().single() + .getResults(); + if (!res.isEmpty()) { + deleteCollection(client, Utils.getCollectionNameLink(databaseId, collectionId)); + } + } + + public static void deleteCollection(AsyncDocumentClient client, String collectionLink) { + client.deleteCollection(collectionLink, null).toBlocking().single(); + } + + public static void deleteDocumentIfExists(AsyncDocumentClient client, String databaseId, String collectionId, String docId) { + FeedOptions options = new FeedOptions(); + options.setPartitionKey(new PartitionKey(docId)); + List res = client + .queryDocuments(Utils.getCollectionNameLink(databaseId, collectionId), String.format("SELECT * FROM root r where r.id = '%s'", docId), options) + .toBlocking().single().getResults(); + if (!res.isEmpty()) { + deleteDocument(client, Utils.getDocumentNameLink(databaseId, collectionId, docId)); + } + } + + public static void safeDeleteDocument(AsyncDocumentClient client, String documentLink, RequestOptions options) { + if (client != null && documentLink != null) { + try { + client.deleteDocument(documentLink, options).toBlocking().single(); + } catch (Exception e) { + DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e, DocumentClientException.class); + if (dce == null || dce.getStatusCode() != 404) { + throw e; + } + } + } + } + + public static void deleteDocument(AsyncDocumentClient client, String documentLink) { + client.deleteDocument(documentLink, null).toBlocking().single(); + } + + public static void deleteUserIfExists(AsyncDocumentClient client, String databaseId, String userId) { + List res = client + .queryUsers("dbs/" + databaseId, String.format("SELECT * FROM root r where r.id = '%s'", userId), null) + .toBlocking().single().getResults(); + if (!res.isEmpty()) { + deleteUser(client, Utils.getUserNameLink(databaseId, userId)); + } + } + + public static void deleteUser(AsyncDocumentClient client, String userLink) { + client.deleteUser(userLink, null).toBlocking().single(); + } + + public static String getDatabaseLink(Database database) { + return database.getSelfLink(); + } + + static private Database safeCreateDatabase(AsyncDocumentClient client, Database database) { + safeDeleteDatabase(client, database.getId()); + return createDatabase(client, database); + } + + static protected Database createDatabase(AsyncDocumentClient client, Database database) { + Observable> databaseObservable = client.createDatabase(database, null); + return databaseObservable.toBlocking().single().getResource(); + } + + static protected Database createDatabase(AsyncDocumentClient client, String databaseId) { + Database databaseDefinition = new Database(); + databaseDefinition.setId(databaseId); + return createDatabase(client, databaseDefinition); + } + + static protected Database createDatabaseIfNotExists(AsyncDocumentClient client, String databaseId) { + return client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null).flatMap(p -> Observable.from(p.getResults())).switchIfEmpty( + Observable.defer(() -> { + + Database databaseDefinition = new Database(); + databaseDefinition.setId(databaseId); + + return client.createDatabase(databaseDefinition, null).map(ResourceResponse::getResource); + }) + ).toBlocking().single(); + } + + static protected void safeDeleteDatabase(AsyncDocumentClient client, Database database) { + if (database != null) { + safeDeleteDatabase(client, database.getId()); + } + } + + static protected void safeDeleteDatabase(AsyncDocumentClient client, String databaseId) { + if (client != null) { + try { + client.deleteDatabase(Utils.getDatabaseNameLink(databaseId), null).toBlocking().single(); + } catch (Exception e) { + } + } + } + + static protected void safeDeleteAllCollections(AsyncDocumentClient client, Database database) { + if (database != null) { + List collections = client.readCollections(database.getSelfLink(), null) + .flatMap(p -> Observable.from(p.getResults())) + .toList() + .toBlocking() + .single(); + + for (DocumentCollection collection : collections) { + client.deleteCollection(collection.getSelfLink(), null).toBlocking().single().getResource(); + } + } + } + + static protected void safeDeleteCollection(AsyncDocumentClient client, DocumentCollection collection) { + if (client != null && collection != null) { + try { + client.deleteCollection(collection.getSelfLink(), null).toBlocking().single(); + } catch (Exception e) { + } + } + } + + static protected void safeDeleteCollection(AsyncDocumentClient client, String databaseId, String collectionId) { + if (client != null && databaseId != null && collectionId != null) { + try { + client.deleteCollection("/dbs/" + databaseId + "/colls/" + collectionId, null).toBlocking().single(); + } catch (Exception e) { + } + } + } + + static protected void safeCloseAsync(AsyncDocumentClient client) { + if (client != null) { + new Thread(() -> { + try { + client.close(); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + } + } + + static protected void safeClose(AsyncDocumentClient client) { + if (client != null) { + try { + client.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + public void validateSuccess(Observable> observable, + ResourceResponseValidator validator) { + validateSuccess(observable, validator, subscriberValidationTimeout); + } + + public static void validateSuccess(Observable> observable, + ResourceResponseValidator validator, long timeout) { + + VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); + + observable.subscribe(testSubscriber); + testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + testSubscriber.assertNoErrors(); + testSubscriber.assertCompleted(); + testSubscriber.assertValueCount(1); + validator.validate(testSubscriber.getOnNextEvents().get(0)); + } + + public void validateFailure(Observable> observable, + FailureValidator validator) { + validateFailure(observable, validator, subscriberValidationTimeout); + } + + public static void validateFailure(Observable> observable, + FailureValidator validator, long timeout) { + + VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); + + observable.subscribe(testSubscriber); + testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + testSubscriber.assertNotCompleted(); + testSubscriber.assertTerminalEvent(); + assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); + validator.validate(testSubscriber.getOnErrorEvents().get(0)); + } + + public void validateQuerySuccess(Observable> observable, + FeedResponseListValidator validator) { + validateQuerySuccess(observable, validator, subscriberValidationTimeout); + } + + public static void validateQuerySuccess(Observable> observable, + FeedResponseListValidator validator, long timeout) { + + VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); + + observable.subscribe(testSubscriber); + testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + testSubscriber.assertNoErrors(); + testSubscriber.assertCompleted(); + validator.validate(testSubscriber.getOnNextEvents()); + } + + public void validateQueryFailure(Observable> observable, + FailureValidator validator) { + validateQueryFailure(observable, validator, subscriberValidationTimeout); + } + + public static void validateQueryFailure(Observable> observable, + FailureValidator validator, long timeout) { + + VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); + + observable.subscribe(testSubscriber); + testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + testSubscriber.assertNotCompleted(); + testSubscriber.assertTerminalEvent(); + assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); + validator.validate(testSubscriber.getOnErrorEvents().get(0)); + } + + @DataProvider + public static Object[][] clientBuilders() { + return new Object[][]{{createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null)}}; + } + + @DataProvider + public static Object[][] clientBuildersWithSessionConsistency() { + return new Object[][]{ + {createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null)}, + {createDirectRxDocumentClient(ConsistencyLevel.Session, Protocol.Https, false, null)}, + {createDirectRxDocumentClient(ConsistencyLevel.Session, Protocol.Tcp, false, null)} + }; + } + + private static ConsistencyLevel parseConsistency(String consistency) { + if (consistency != null) { + for (ConsistencyLevel consistencyLevel : ConsistencyLevel.values()) { + if (consistencyLevel.name().toLowerCase().equals(consistency.toLowerCase())) { + return consistencyLevel; + } + } + } + + logger.error("Invalid configured test consistency [{}].", consistency); + throw new IllegalStateException("Invalid configured test consistency " + consistency); + } + + static List parsePreferredLocation(String preferredLocations) { + if (StringUtils.isEmpty(preferredLocations)) { + return null; + } + + try { + return objectMapper.readValue(preferredLocations, new TypeReference>() { + }); + } catch (Exception e) { + logger.error("Invalid configured test preferredLocations [{}].", preferredLocations); + throw new IllegalStateException("Invalid configured test preferredLocations " + preferredLocations); + } + } + + static List parseProtocols(String protocols) { + if (StringUtils.isEmpty(protocols)) { + return null; + } + + try { + return objectMapper.readValue(protocols, new TypeReference>() { + }); + } catch (Exception e) { + logger.error("Invalid configured test protocols [{}].", protocols); + throw new IllegalStateException("Invalid configured test protocols " + protocols); + } + } + + @DataProvider + public static Object[][] simpleClientBuildersWithDirect() { + return simpleClientBuildersWithDirect(toArray(protocols)); + } + + @DataProvider + public static Object[][] simpleClientBuildersWithDirectHttps() { + return simpleClientBuildersWithDirect(Protocol.Https); + } + + private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) { + logger.info("Max test consistency to use is [{}]", accountConsistency); + List testConsistencies = ImmutableList.of(ConsistencyLevel.Eventual); + + boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.Session; + + List builders = new ArrayList<>(); + builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null)); + + for (Protocol protocol : protocols) { + testConsistencies.forEach(consistencyLevel -> builders.add(createDirectRxDocumentClient(consistencyLevel, + protocol, + isMultiMasterEnabled, + preferredLocations))); + } + + builders.forEach(b -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", + b.getConnectionPolicy().getConnectionMode(), + b.getDesiredConsistencyLevel(), + b.getConfigs().getProtocol() + )); + + return builders.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); + } + + @DataProvider + public static Object[][] clientBuildersWithDirect() { + return clientBuildersWithDirectAllConsistencies(toArray(protocols)); + } + + @DataProvider + public static Object[][] clientBuildersWithDirectHttps() { + return clientBuildersWithDirectAllConsistencies(Protocol.Https); + } + + @DataProvider + public static Object[][] clientBuildersWithDirectSession() { + return clientBuildersWithDirectSession(toArray(protocols)); + } + + static Protocol[] toArray(List protocols) { + return protocols.toArray(new Protocol[0]); + } + + private static Object[][] clientBuildersWithDirectSession(Protocol... protocols) { + return clientBuildersWithDirect(new ArrayList() {{ + add(ConsistencyLevel.Session); + }}, protocols); + } + + private static Object[][] clientBuildersWithDirectAllConsistencies(Protocol... protocols) { + logger.info("Max test consistency to use is [{}]", accountConsistency); + return clientBuildersWithDirect(desiredConsistencies, protocols); + } + + static List parseDesiredConsistencies(String consistencies) { + if (StringUtils.isEmpty(consistencies)) { + return null; + } + + try { + return objectMapper.readValue(consistencies, new TypeReference>() { + }); + } catch (Exception e) { + logger.error("Invalid consistency test desiredConsistencies [{}].", consistencies); + throw new IllegalStateException("Invalid configured test desiredConsistencies " + consistencies); + } + } + + static List allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { + List testConsistencies = new ArrayList<>(); + switch (accountConsistency) { + case Strong: + testConsistencies.add(ConsistencyLevel.Strong); + case BoundedStaleness: + testConsistencies.add(ConsistencyLevel.BoundedStaleness); + case Session: + testConsistencies.add(ConsistencyLevel.Session); + case ConsistentPrefix: + testConsistencies.add(ConsistencyLevel.ConsistentPrefix); + case Eventual: + testConsistencies.add(ConsistencyLevel.Eventual); + break; + default: + throw new IllegalStateException("Invalid configured test consistency " + accountConsistency); + } + return testConsistencies; + } + + private static Object[][] clientBuildersWithDirect(List testConsistencies, Protocol... protocols) { + boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.Session; + + List builders = new ArrayList<>(); + builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, isMultiMasterEnabled, preferredLocations)); + + for (Protocol protocol : protocols) { + testConsistencies.forEach(consistencyLevel -> builders.add(createDirectRxDocumentClient(consistencyLevel, + protocol, + isMultiMasterEnabled, + preferredLocations))); + } + + builders.forEach(b -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", + b.getConnectionPolicy().getConnectionMode(), + b.getDesiredConsistencyLevel(), + b.getConfigs().getProtocol() + )); + + return builders.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); + } + + static protected Builder createGatewayHouseKeepingDocumentClient() { + ConnectionPolicy connectionPolicy = new ConnectionPolicy(); + connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + RetryOptions options = new RetryOptions(); + options.setMaxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); + connectionPolicy.setRetryOptions(options); + return new Builder().withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.Session); + } + + static protected Builder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List preferredLocations) { + ConnectionPolicy connectionPolicy = new ConnectionPolicy(); + connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.setUsingMultipleWriteLocations(multiMasterEnabled); + connectionPolicy.setPreferredLocations(preferredLocations); + return new Builder().withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(consistencyLevel); + } + + static protected Builder createGatewayRxDocumentClient() { + return createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null); + } + + static protected Builder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, + Protocol protocol, + boolean multiMasterEnabled, + List preferredLocations) { + ConnectionPolicy connectionPolicy = new ConnectionPolicy(); + connectionPolicy.setConnectionMode(ConnectionMode.Direct); + + if (preferredLocations != null) { + connectionPolicy.setPreferredLocations(preferredLocations); + } + + if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.Session) { + connectionPolicy.setUsingMultipleWriteLocations(true); + } + + Configs configs = spy(new Configs()); + doAnswer((Answer)invocation -> protocol).when(configs).getProtocol(); + + return new Builder().withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(consistencyLevel) + .withConfigs(configs); + } + + protected int expectedNumberOfPages(int totalExpectedResult, int maxPageSize) { + return Math.max((totalExpectedResult + maxPageSize - 1 ) / maxPageSize, 1); + } + + @DataProvider(name = "queryMetricsArgProvider") + public Object[][] queryMetricsArgProvider() { + return new Object[][]{ + {true}, + {false}, + }; + } + + public static class VerboseTestSubscriber extends TestSubscriber { + @Override + public void assertNoErrors() { + List onErrorEvents = getOnErrorEvents(); + StringBuilder errorMessageBuilder = new StringBuilder(); + if (!onErrorEvents.isEmpty()) { + for(Throwable throwable : onErrorEvents) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + throwable.printStackTrace(pw); + String sStackTrace = sw.toString(); // stack trace as a string + errorMessageBuilder.append(sStackTrace); + } + + AssertionError ae = new AssertionError(errorMessageBuilder.toString()); + throw ae; + } + } + } +} \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/ReflectionUtils.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/ReflectionUtils.java index 944089112f01c..80f31b9cc3f63 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/ReflectionUtils.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/ReflectionUtils.java @@ -23,10 +23,12 @@ package com.microsoft.azure.cosmosdb.rx.internal.directconnectivity; +import com.microsoft.azure.cosmos.CosmosClient; import com.microsoft.azure.cosmosdb.internal.directconnectivity.HttpTransportClient; import com.microsoft.azure.cosmosdb.internal.directconnectivity.ServerStoreModel; import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreClient; import com.microsoft.azure.cosmosdb.internal.directconnectivity.TransportClient; +import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientImpl; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; @@ -89,4 +91,12 @@ public static void setDirectHttpsHttpClient(RxDocumentClientImpl client, Composi assert transportClient instanceof HttpTransportClient; set(transportClient, newHttpClient, "httpClient"); } + + public static AsyncDocumentClient getAsyncDocumentClient(CosmosClient client) { + return get(AsyncDocumentClient.class, client, "asyncDocumentClient"); + } + + public static void setAsyncDocumentClient(CosmosClient client, RxDocumentClientImpl rxClient) { + set(client, rxClient, "asyncDocumentClient"); + } } From 337c77955e31d42fd8a89e8b53e694eee4695080 Mon Sep 17 00:00:00 2001 From: mbhaskar Date: Sat, 8 Jun 2019 22:32:07 -0700 Subject: [PATCH 33/85] Adding permissions and throughput (#177) --- .../azure/cosmos/CosmosContainer.java | 59 ++++++++ .../azure/cosmos/CosmosDatabase.java | 56 ++++++++ .../azure/cosmos/CosmosPermission.java | 109 ++++++++++++++ .../cosmos/CosmosPermissionResponse.java | 56 ++++++++ .../cosmos/CosmosPermissionSettings.java | 134 ++++++++++++++++++ .../CosmosPermissionsRequestOptions.java | 40 ++++++ .../microsoft/azure/cosmos/CosmosUser.java | 91 ++++++++++++ .../azure/cosmos/CosmosContainerCrudTest.java | 27 ++++ 8 files changed, 572 insertions(+) create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermission.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionResponse.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionSettings.java create mode 100644 sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionsRequestOptions.java diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java index 9f168dbd83d34..68bb673a1255e 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java @@ -24,14 +24,17 @@ import com.microsoft.azure.cosmosdb.BridgeInternal; import com.microsoft.azure.cosmosdb.ChangeFeedOptions; +import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.Offer; import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.SqlQuerySpec; import com.microsoft.azure.cosmosdb.StoredProcedure; import com.microsoft.azure.cosmosdb.Trigger; import com.microsoft.azure.cosmosdb.UserDefinedFunction; import com.microsoft.azure.cosmosdb.internal.Constants; +import com.microsoft.azure.cosmosdb.internal.HttpConstants; import com.microsoft.azure.cosmosdb.internal.Paths; import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; @@ -681,6 +684,62 @@ public CosmosTrigger getTrigger(String id){ return new CosmosTrigger(id, this); } + /** + * Gets the throughput of the container + * + * @return a {@link Mono} containing throughput or an error. + */ + public Mono readProvisionedThroughput(){ + return this.read() + .flatMap(cosmosContainerResponse -> + RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(database.getDocClientWrapper() + .queryOffers("select * from c where c.offerResourceId = '" + + cosmosContainerResponse.getResourceSettings().getResourceId() + + "'", new FeedOptions()).toSingle())) + .flatMap(offerFeedResponse -> { + if(offerFeedResponse.getResults().isEmpty()){ + return Mono.error(new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + "No offers found for the resource")); + } + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(database.getDocClientWrapper() + .readOffer(offerFeedResponse.getResults() + .get(0) + .getSelfLink()).toSingle())); + }) + .map(cosmosOfferResponse -> cosmosOfferResponse + .getResource() + .getThroughput())); + } + + /** + * Sets throughput provisioned for a container in measurement of Requests-per-Unit in the Azure Cosmos service. + * + * @param requestUnitsPerSecond the cosmos container throughput, expressed in Request Units per second + * @return a {@link Mono} containing throughput or an error. + */ + public Mono replaceProvisionedThroughputAsync(int requestUnitsPerSecond){ + return this.read() + .flatMap(cosmosContainerResponse -> + RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(database.getDocClientWrapper() + .queryOffers("select * from c where c.offerResourceId = '" + + cosmosContainerResponse.getResourceSettings().getResourceId() + + "'", new FeedOptions()).toSingle())) + .flatMap(offerFeedResponse -> { + if(offerFeedResponse.getResults().isEmpty()){ + return Mono.error(new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + "No offers found for the resource")); + } + Offer offer = offerFeedResponse.getResults().get(0); + offer.setThroughput(requestUnitsPerSecond); + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(database.getDocClientWrapper() + .replaceOffer(offer).toSingle())); + }).map(offerResourceResponse -> offerResourceResponse.getResource().getThroughput())); + } + /** * Gets the parent Database * diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java index 75fb16970a13e..3afbe6953f7dd 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java @@ -26,6 +26,7 @@ import com.microsoft.azure.cosmosdb.DocumentClientException; import com.microsoft.azure.cosmosdb.FeedOptions; import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.Offer; import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.SqlQuerySpec; import com.microsoft.azure.cosmosdb.internal.HttpConstants; @@ -375,6 +376,61 @@ public CosmosUser getUser(String id) { return new CosmosUser(id, this); } + /** + * Gets the throughput of the database + * + * @return a {@link Mono} containing throughput or an error. + */ + public Mono readProvisionedThroughput(){ + return this.read() + .flatMap(cosmosDatabaseResponse -> + RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(getDocClientWrapper().queryOffers("select * from c where c.offerResourceId = '" + + cosmosDatabaseResponse.getResourceSettings().getResourceId() + + "'", new FeedOptions()).toSingle())) + .flatMap(offerFeedResponse -> { + if(offerFeedResponse.getResults().isEmpty()){ + return Mono.error(new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + "No offers found for the resource")); + } + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(getDocClientWrapper() + .readOffer(offerFeedResponse.getResults() + .get(0) + .getSelfLink()).toSingle())); + }) + .map(cosmosContainerResponse1 -> cosmosContainerResponse1 + .getResource() + .getThroughput())); + } + + /** + * Sets throughput provisioned for a container in measurement of Requests-per-Unit in the Azure Cosmos service. + * + * @param requestUnitsPerSecond the cosmos container throughput, expressed in Request Units per second + * @return a {@link Mono} containing throughput or an error. + */ + public Mono replaceProvisionedThroughputAsync(int requestUnitsPerSecond){ + return this.read() + .flatMap(cosmosDatabaseResponse -> + RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(this.getDocClientWrapper() + .queryOffers("select * from c where c.offerResourceId = '" + + cosmosDatabaseResponse.getResourceSettings().getResourceId() + + "'", new FeedOptions()).toSingle())) + .flatMap(offerFeedResponse -> { + if(offerFeedResponse.getResults().isEmpty()){ + return Mono.error(new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + "No offers found for the resource")); + } + Offer offer = offerFeedResponse.getResults().get(0); + offer.setThroughput(requestUnitsPerSecond); + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(this.getDocClientWrapper() + .replaceOffer(offer).toSingle())); + }).map(offerResourceResponse -> offerResourceResponse.getResource().getThroughput())); + } + CosmosClient getClient() { return client; } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermission.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermission.java new file mode 100644 index 0000000000000..995dcff0dfef3 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermission.java @@ -0,0 +1,109 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.RequestOptions; +import com.microsoft.azure.cosmosdb.internal.Paths; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Mono; + +public class CosmosPermission extends CosmosResource{ + + private final CosmosUser cosmosUser; + + CosmosPermission(String id, CosmosUser user){ + super(id); + this.cosmosUser = user; + } + + /** + * Reads a permission. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the read permission. + * In case of failure the {@link Mono} will error. + * + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the read permission or an error. + */ + public Mono read(RequestOptions options) { + + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(cosmosUser.getDatabase() + .getDocClientWrapper() + .readPermission(getLink(),options) + .map(response -> new CosmosPermissionResponse(response, cosmosUser)) + .toSingle())); + } + + /** + * Replaces a permission. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the replaced permission. + * In case of failure the {@link Mono} will error. + * + * @param permissionSettings the permission settings to use. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the replaced permission or an error. + */ + public Mono replace(CosmosPermissionSettings permissionSettings, RequestOptions options) { + + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(cosmosUser.getDatabase() + .getDocClientWrapper() + .replacePermission(permissionSettings.getV2Permissions(), options) + .map(response -> new CosmosPermissionResponse(response, cosmosUser)) + .toSingle())); + } + + /** + * Deletes a permission. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response for the deleted permission. + * In case of failure the {@link Mono} will error. + * + * @param options the request options. + * @return an {@link Mono} containing the single resource response for the deleted permission or an error. + */ + public Mono delete(CosmosPermissionsRequestOptions options) { + if(options == null){ + options = new CosmosPermissionsRequestOptions(); + } + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(cosmosUser.getDatabase() + .getDocClientWrapper() + .deletePermission(getLink(), options.toRequestOptions()) + .map(response -> new CosmosPermissionResponse(response, cosmosUser)) + .toSingle())); + } + + @Override + protected String getURIPathSegment() { + return Paths.PERMISSIONS_PATH_SEGMENT; + } + + @Override + protected String getParentLink() { + return cosmosUser.getLink(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionResponse.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionResponse.java new file mode 100644 index 0000000000000..1724654dfe51f --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionResponse.java @@ -0,0 +1,56 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.Permission; +import com.microsoft.azure.cosmosdb.ResourceResponse; + +public class CosmosPermissionResponse extends CosmosResponse { + CosmosPermission permissionClient; + + CosmosPermissionResponse(ResourceResponse response, CosmosUser cosmosUser) { + super(response); + if(response.getResource() == null){ + super.setResourceSettings(null); + }else{ + super.setResourceSettings(new CosmosPermissionSettings(response.getResource().toJson())); + permissionClient = new CosmosPermission(response.getResource().getId(), cosmosUser); + } + } + + /** + * Get the permission settings + * @return the permission settings + */ + public CosmosPermissionSettings getPermissionSettings(){ + return super.getResourceSettings(); + } + + /** + * Gets the CosmosPermission + * @return the cosmos permission + */ + public CosmosPermission getPermission() { + return permissionClient; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionSettings.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionSettings.java new file mode 100644 index 0000000000000..926afe7f24d94 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionSettings.java @@ -0,0 +1,134 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.PartitionKey; +import com.microsoft.azure.cosmosdb.Permission; +import com.microsoft.azure.cosmosdb.PermissionMode; +import com.microsoft.azure.cosmosdb.Resource; +import com.microsoft.azure.cosmosdb.internal.Constants; +import org.apache.commons.text.WordUtils; + +import java.util.List; +import java.util.stream.Collectors; + +public class CosmosPermissionSettings extends Resource { + + + public static List getFromV2Results(List results) { + return results.stream().map(permission -> new CosmosPermissionSettings(permission.toJson())).collect(Collectors.toList()); + } + + /** + * Initialize a permission object. + */ + public CosmosPermissionSettings() { + super(); + } + + /** + * Initialize a permission object from json string. + * + * @param jsonString the json string that represents the permission. + */ + public CosmosPermissionSettings(String jsonString) { + super(jsonString); + } + + /** + * Gets the self-link of resource to which the permission applies. + * + * @return the resource link. + */ + public String getResourceLink() { + return super.getString(Constants.Properties.RESOURCE_LINK); + } + + /** + * Sets the self-link of resource to which the permission applies. + * + * @param resourceLink the resource link. + */ + public void setResourceLink(String resourceLink) { + super.set(Constants.Properties.RESOURCE_LINK, resourceLink); + } + + /** + * Gets the permission mode. + * + * @return the permission mode. + */ + public PermissionMode getPermissionMode() { + String value = super.getString(Constants.Properties.PERMISSION_MODE); + return PermissionMode.valueOf(WordUtils.capitalize(value)); + } + + /** + * Sets the permission mode. + * + * @param permissionMode the permission mode. + */ + public void setPermissionMode(PermissionMode permissionMode) { + this.set(Constants.Properties.PERMISSION_MODE, + permissionMode.name().toLowerCase()); + } + + /** + * Gets the access token granting the defined permission. + * + * @return the access token. + */ + public String getToken() { + return super.getString(Constants.Properties.TOKEN); + } + + //TODO: need getValue from JsonSerializable +// /** +// * Gets the resource partition key associated with this permission object. +// * +// * @return the partition key. +// */ +// public PartitionKey getResourcePartitionKey() { +// PartitionKey key = null; +// Object value = super.get(Constants.Properties.RESOURCE_PARTITION_KEY); +// if (value != null) { +// ArrayNode arrayValue = (ArrayNode) value; +// key = new PartitionKey(getValue(arrayValue.get(0))); +// } +// +// return key; +// } + + /** + * Sets the resource partition key associated with this permission object. + * + * @param partitionkey the partition key. + */ + public void setResourcePartitionKey(PartitionKey partitionkey) { + super.set(Constants.Properties.RESOURCE_PARTITION_KEY, partitionkey.getInternalPartitionKey().toJson()); + } + + public Permission getV2Permissions() { + return null; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionsRequestOptions.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionsRequestOptions.java new file mode 100644 index 0000000000000..d804050a9fce8 --- /dev/null +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionsRequestOptions.java @@ -0,0 +1,40 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.microsoft.azure.cosmos; + +import com.microsoft.azure.cosmosdb.RequestOptions; + +/** + * Contains the request options of CosmosPermission + */ +public class CosmosPermissionsRequestOptions extends CosmosRequestOptions { + //TODO: Need to add respective options + + + @Override + protected RequestOptions toRequestOptions() { + //TODO: Should we set any default values instead of nulls? + super.toRequestOptions(); + return requestOptions; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java index fc8b3cc7f8f1a..8d9af78a0c29f 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java +++ b/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java @@ -1,9 +1,14 @@ package com.microsoft.azure.cosmos; +import com.microsoft.azure.cosmosdb.BridgeInternal; +import com.microsoft.azure.cosmosdb.FeedOptions; +import com.microsoft.azure.cosmosdb.FeedResponse; +import com.microsoft.azure.cosmosdb.Permission; import com.microsoft.azure.cosmosdb.RequestOptions; import com.microsoft.azure.cosmosdb.internal.Paths; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public class CosmosUser extends CosmosResource { @@ -57,6 +62,88 @@ public Mono delete(RequestOptions options) { .map(response -> new CosmosUserResponse(response, database)).toSingle())); } + /** + * Creates a permission. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the created permission. + * In case of failure the {@link Mono} will error. + * + * @param permissionSettings the permission settings to create. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the created permission or an error. + */ + public Mono createPermission(CosmosPermissionSettings permissionSettings, CosmosPermissionsRequestOptions options) { + if(options == null){ + options = new CosmosPermissionsRequestOptions(); + } + Permission permission = permissionSettings.getV2Permissions(); + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(database.getDocClientWrapper() + .createPermission(getLink(), permission, options.toRequestOptions()) + .map(response -> new CosmosPermissionResponse(response, this)) + .toSingle())); + } + + /** + * Upserts a permission. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the upserted permission. + * In case of failure the {@link Mono} will error. + * + * @param permissionSettings the permission settings to upsert. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the upserted permission or an error. + */ + public Mono upsertPermission(CosmosPermissionSettings permissionSettings, CosmosPermissionsRequestOptions options) { + Permission permission = permissionSettings.getV2Permissions(); + if(options == null){ + options = new CosmosPermissionsRequestOptions(); + } + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(database.getDocClientWrapper() + .upsertPermission(getLink(), permission, options.toRequestOptions()) + .map(response -> new CosmosPermissionResponse(response, this)) + .toSingle())); + } + + + /** + * Reads all permissions. + *

+ * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the read permissions. + * In case of failure the {@link Flux} will error. + * + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the read permissions or an error. + */ + public Flux> listPermissions(FeedOptions options) { + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(getDatabase().getDocClientWrapper() + .readPermissions(getLink(), options) + .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + + /** + * Query for permissions. + *

+ * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained permissions. + * In case of failure the {@link Flux} will error. + * + * @param query the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained permissions or an error. + */ + public Flux> queryPermissions(String query, FeedOptions options) { + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(getDatabase().getDocClientWrapper() + .queryPermissions(getLink(), query, options) + .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionSettings.getFromV2Results(response.getResults()), + response.getResponseHeaders())))); + } + @Override protected String getURIPathSegment() { return Paths.USERS_PATH_SEGMENT; @@ -66,4 +153,8 @@ protected String getURIPathSegment() { protected String getParentLink() { return database.getLink() ; } + + CosmosDatabase getDatabase() { + return database; + } } \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java index 3491fb571e102..5aacc530925bf 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java @@ -148,6 +148,33 @@ public void testreplaceContainer() throws Exception { validateSuccess(replaceMono, validator); } + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testGetThroughput(){ + CosmosDatabase database = client.getDatabase(PRE_EXISTING_DATABASE_ID); + + Mono containerMono = database.createContainer(getContainerSettings()); + + CosmosContainerResponse containerResponse = containerMono.block(); + CosmosContainer container = containerResponse.getContainer(); + + Integer throughput = container.readProvisionedThroughput().block(); + } + + @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) + public void testReplaceThroughput(){ + CosmosDatabase database = client.getDatabase(PRE_EXISTING_DATABASE_ID); + int newThroughput = 1000; + + Mono containerMono = database.createContainer(getContainerSettings()); + + CosmosContainerResponse containerResponse = containerMono.block(); + CosmosContainer container = containerResponse.getContainer(); + + Integer throughput = container.replaceProvisionedThroughputAsync(newThroughput).block(); + assertThat(throughput).isEqualTo(newThroughput); + } + + @BeforeClass(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); From 91d9fe196bf85c10f2a5f1e2151632eb67ffc1c5 Mon Sep 17 00:00:00 2001 From: Christopher Anderson Date: Sun, 9 Jun 2019 03:36:57 -0700 Subject: [PATCH 34/85] artifact renaming, versioning update, and jar collection command (#174) * 3.0.0-a1 * Add .vscode to .gitignore * SNAPSHOT & jar collection command --- .gitignore | 2 + README.md | 88 ++++++++++------- benchmark/pom.xml | 25 ++++- commons-test-utils/pom.xml | 23 ++++- commons/pom.xml | 21 +++- .../cosmosdb/internal/HttpConstants.java | 19 ++-- direct-impl/pom.xml | 26 +++-- examples/pom.xml | 39 +++++--- gateway/pom.xml | 25 ++++- pom.xml | 97 +++++++++++++++++-- sdk/pom.xml | 29 ++++-- 11 files changed, 303 insertions(+), 91 deletions(-) diff --git a/.gitignore b/.gitignore index 19547d6a1616a..a40847a0d9499 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,5 @@ docs target bin test-output + +.vscode diff --git a/README.md b/README.md index 570b621739ee9..39d7e07f8a756 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,13 @@ # Java SDK for SQL API of Azure Cosmos DB + [![Maven Central](https://img.shields.io/maven-central/v/com.microsoft.azure/azure-cosmosdb.svg)](https://search.maven.org/artifact/com.microsoft.azure/azure-cosmosdb/2.4.3/jar) [![Build Status](https://api.travis-ci.org/Azure/azure-cosmosdb-java.svg?branch=master)](https://travis-ci.org/Azure/azure-cosmosdb-java) [![Known Vulnerabilities](https://snyk.io/test/github/Azure/azure-cosmosdb-java/badge.svg?targetFile=sdk%2Fpom.xml)](https://snyk.io/test/github/Azure/azure-cosmosdb-java?targetFile=sdk%2Fpom.xml) + - + - [Consuming the official Microsoft Azure Cosmos DB Java SDK](#consuming-the-official-microsoft-azure-cosmos-db-java-sdk) @@ -22,13 +24,12 @@ - ## Consuming the official Microsoft Azure Cosmos DB Java SDK This project provides a SDK library in Java for interacting with [SQL API](https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-sql-query) of [Azure Cosmos DB Database Service](https://azure.microsoft.com/en-us/services/cosmos-db/). This project also includes samples, tools, and utilities. -Jar dependency binary information for maven and gradle can be found here at [maven]( https://mvnrepository.com/artifact/com.microsoft.azure/azure-cosmosdb/2.4.3). +Jar dependency binary information for maven and gradle can be found here at [maven](https://mvnrepository.com/artifact/com.microsoft.azure/azure-cosmosdb/2.4.3). For example, using maven, you can add the following dependency to your maven pom file: @@ -40,35 +41,35 @@ For example, using maven, you can add the following dependency to your maven pom ``` - - Useful links: + - [Sample Get Started APP](https://github.com/Azure-Samples/azure-cosmos-db-sql-api-async-java-getting-started) -- [Introduction to Resource Model of Azure Cosmos DB Service]( https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-resources) +- [Introduction to Resource Model of Azure Cosmos DB Service](https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-resources) - [Introduction to SQL API of Azure Cosmos DB Service](https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-sql-query) - [SDK JavaDoc API](https://azure.github.io/azure-cosmosdb-java/2.4.0/com/microsoft/azure/cosmosdb/rx/AsyncDocumentClient.html) - [RxJava Observable JavaDoc API](http://reactivex.io/RxJava/1.x/javadoc/rx/Observable.html) - [SDK FAQ](faq/) ## Prerequisites -* Java Development Kit 8 -* An active Azure account. If you don't have one, you can sign up for a [free account](https://azure.microsoft.com/free/). Alternatively, you can use the [Azure Cosmos DB Emulator](https://azure.microsoft.com/documentation/articles/documentdb-nosql-local-emulator) for development and testing. As emulator https certificate is self signed, you need to import its certificate to java trusted cert store as [explained here](https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator-export-ssl-certificates) -* (Optional) SLF4J is a logging facade. -* (Optional) [SLF4J binding](http://www.slf4j.org/manual.html) is used to associate a specific logging framework with SLF4J. -* (Optional) Maven -SLF4J is only needed if you plan to use logging, please also download an SLF4J binding which will link the SLF4J API with the logging implementation of your choice. See the [SLF4J user manual](http://www.slf4j.org/manual.html) for more information. +- Java Development Kit 8 +- An active Azure account. If you don't have one, you can sign up for a [free account](https://azure.microsoft.com/free/). Alternatively, you can use the [Azure Cosmos DB Emulator](https://azure.microsoft.com/documentation/articles/documentdb-nosql-local-emulator) for development and testing. As emulator https certificate is self signed, you need to import its certificate to java trusted cert store as [explained here](https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator-export-ssl-certificates) +- (Optional) SLF4J is a logging facade. +- (Optional) [SLF4J binding](http://www.slf4j.org/manual.html) is used to associate a specific logging framework with SLF4J. +- (Optional) Maven +SLF4J is only needed if you plan to use logging, please also download an SLF4J binding which will link the SLF4J API with the logging implementation of your choice. See the [SLF4J user manual](http://www.slf4j.org/manual.html) for more information. ## API Documentation + Javadoc is available [here](https://azure.github.io/azure-cosmosdb-java/2.4.0/com/microsoft/azure/cosmosdb/rx/AsyncDocumentClient.html). The SDK provide Reactive Extension Observable based async API. You can read more about RxJava and [Observable APIs here](http://reactivex.io/RxJava/1.x/javadoc/rx/Observable.html). - ## Usage Code Sample Code Sample for creating a Document: + ```java import com.microsoft.azure.cosmosdb.rx.*; import com.microsoft.azure.cosmosdb.*; @@ -104,18 +105,18 @@ We have a get started sample app available [here](https://github.com/Azure-Sampl Also We have more examples in form of standalone unit tests in [examples project](examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples). - ## Guide for Prod + To achieve better performance and higher throughput there are a few tips that are helpful to follow: ### Use Appropriate Scheduler (Avoid stealing Eventloop IO Netty threads) + SDK uses [netty](https://netty.io/) for non-blocking IO. The SDK uses a fixed number of IO netty eventloop threads (as many CPU cores your machine has) for executing IO operations. - The Observable returned by API emits the result on one of the shared IO eventloop netty threads. So it is important to not block the shared IO eventloop netty threads. Doing CPU intensive work or blocking operation on the IO eventloop netty thread may cause deadlock or significantly reduce SDK throughput. +The Observable returned by API emits the result on one of the shared IO eventloop netty threads. So it is important to not block the shared IO eventloop netty threads. Doing CPU intensive work or blocking operation on the IO eventloop netty thread may cause deadlock or significantly reduce SDK throughput. For example the following code executes a cpu intensive work on the eventloop IO netty thread: - ```java Observable> createDocObs = asyncDocumentClient.createDocument( collectionLink, document, null, true); @@ -150,18 +151,19 @@ subscribe( ``` Based on the type of your work you should use the appropriate existing RxJava Scheduler for your work. Please read here -[``Schedulers``](http://reactivex.io/RxJava/1.x/javadoc/rx/schedulers/Schedulers.html). - +[`Schedulers`](http://reactivex.io/RxJava/1.x/javadoc/rx/schedulers/Schedulers.html). ### Disable netty's logging + Netty library logging is very chatty and need to be turned off (suppressing log in the configuration may not be enough) to avoid additional CPU costs. -If you are not in debugging mode disable netty's logging altogether. So if you are using log4j to remove the additional CPU costs incurred by ``org.apache.log4j.Category.callAppenders()`` from netty add the following line to your codebase: +If you are not in debugging mode disable netty's logging altogether. So if you are using log4j to remove the additional CPU costs incurred by `org.apache.log4j.Category.callAppenders()` from netty add the following line to your codebase: ```java org.apache.log4j.Logger.getLogger("io.netty").setLevel(org.apache.log4j.Level.OFF); ``` ### OS Open files Resource Limit + Some Linux systems (like Redhat) have an upper limit on the number of open files and so the total number of connections. Run the following to view the current limits: ```bash @@ -175,6 +177,7 @@ Open the limits.conf file: ```bash vim /etc/security/limits.conf ``` + Add/modify the following lines: ``` @@ -182,16 +185,19 @@ Add/modify the following lines: ``` ### Use native SSL implementation for netty + Netty can use OpenSSL directly for SSL implementation stack to achieve better performance. In the absence of this configuration netty will fall back to Java's default SSL implementation. on Ubuntu: + ```bash sudo apt-get install openssl sudo apt-get install libapr1 ``` and add the following dependency to your project maven dependencies: + ```xml io.netty @@ -204,14 +210,14 @@ and add the following dependency to your project maven dependencies: For other platforms (Redhat, Windows, Mac, etc) please refer to these instructions https://netty.io/wiki/forked-tomcat-native.html ### Common Perf Tips + There is a set of common perf tips written for our sync SDK. The majority of them also apply to the async SDK. It is available [here](https://docs.microsoft.com/en-us/azure/cosmos-db/performance-tips-java). ## Future, CompletableFuture, and ListenableFuture The SDK provide Reactive Extension (Rx) [Observable](http://reactivex.io/RxJava/1.x/javadoc/rx/Observable.html) based async API. - -RX API has advantages over Future based APIs. But if you wish to use ``Future`` you can translate Observables to Java native Futures: +RX API has advantages over Future based APIs. But if you wish to use `Future` you can translate Observables to Java native Futures: ```java // You can convert an Observable to a ListenableFuture. @@ -239,9 +245,11 @@ You can see more details on how to convert Observables to Futures here: https://dzone.com/articles/converting-between ## Checking out the Source Code + The SDK is open source and is available here [sdk](sdk/). - Clone the Repo +Clone the Repo + ```bash git clone https://github.com/Azure/azure-cosmosdb-java.git cd azure-cosmosdb-java @@ -249,12 +257,24 @@ cd azure-cosmosdb-java ### How to Build from Command Line -* Run the following maven command to build: +- Run the following maven command to build: ```bash maven clean package -DskipTests ``` +### How to generate directory structure for publishing + +- Run the following maven command to collect the jars needed for publishing + +```bash +mvn antrun:run -N +``` + +Note: the `-N` is required to assert this command is only run in the parent pom. + +Afterwards, you can upload the contents of `./target/collectedArtifactsForRelease` for publishing. + #### Running Tests from Command Line Running tests require Azure Cosmos DB Endpoint credentials: @@ -265,25 +285,27 @@ mvn test -DACCOUNT_HOST="https://REPLACE_ME_WITH_YOURS.documents.azure.com:443/" ### Import into Intellij or Eclipse -* Load the main parent project pom file in Intellij/Eclipse (That should automatically load examples). -* For running the samples you need a proper Azure Cosmos DB Endpoint. The endpoints are picked up from [TestConfigurations.java](examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TestConfigurations.java). There is a similar endpoint config file for the sdk tests [here](sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java). -* You can pass your endpoint credentials as VM Arguments in Eclipse JUnit Run Config: +- Load the main parent project pom file in Intellij/Eclipse (That should automatically load examples). +- For running the samples you need a proper Azure Cosmos DB Endpoint. The endpoints are picked up from [TestConfigurations.java](examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TestConfigurations.java). There is a similar endpoint config file for the sdk tests [here](sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java). +- You can pass your endpoint credentials as VM Arguments in Eclipse JUnit Run Config: + ```bash -DACCOUNT_HOST="https://REPLACE_ME.documents.azure.com:443/" -DACCOUNT_KEY="REPLACE_ME" - ``` -* or you can simply put your endpoint credentials in TestConfigurations.java -* The SDK tests are written using TestNG framework, if you use Eclipse you may have to +``` + +- or you can simply put your endpoint credentials in TestConfigurations.java +- The SDK tests are written using TestNG framework, if you use Eclipse you may have to add TestNG plugin to your eclipse IDE as explained [here](http://testng.org/doc/eclipse.html). Intellij has builtin support for TestNG. -* Now you can run the tests in your Intellij/Eclipse IDE. - +- Now you can run the tests in your Intellij/Eclipse IDE. ## FAQ + We have a frequently asked questions which is maintained [here](faq/). ## Release changes -Release changelog is available [here](changelog/). +Release changelog is available [here](changelog/). ## Contribution and Feedback @@ -295,7 +317,7 @@ We have [travis build CI](https://travis-ci.org/Azure/azure-cosmosdb-java) which If you encounter any bugs with the SDK please file an [issue](https://github.com/Azure/azure-cosmosdb-java/issues) in the Issues section of the project. - ## License + MIT License Copyright (c) 2018 Copyright (c) Microsoft Corporation diff --git a/benchmark/pom.xml b/benchmark/pom.xml index 7e3a747891512..fdcae64c6558e 100644 --- a/benchmark/pom.xml +++ b/benchmark/pom.xml @@ -28,11 +28,11 @@ 4.0.0 com.microsoft.azure - azure-cosmosdb-parent - 3.0.0-SNAPSHOT + azure-cosmos-parent + 3.0.0-a1-SNAPSHOT - azure-cosmosdb-benchmark + azure-cosmos-benchmark Async SDK for SQL API of Azure Cosmos DB Service - Benchmarking tool Benchmarking tool for Async SDK for SQL API of Azure Cosmos DB Service @@ -96,16 +96,31 @@ + + org.apache.maven.plugins + maven-antrun-plugin + 1.8 + false + + + none + default-cli + + + + true + + com.microsoft.azure - azure-cosmosdb + azure-cosmos com.microsoft.azure - azure-cosmosdb-commons-test-utils + azure-cosmos-commons-test-utils io.netty diff --git a/commons-test-utils/pom.xml b/commons-test-utils/pom.xml index 857a9edeb3d54..52a5c8abfec48 100644 --- a/commons-test-utils/pom.xml +++ b/commons-test-utils/pom.xml @@ -27,10 +27,10 @@ SOFTWARE. 4.0.0 com.microsoft.azure - azure-cosmosdb-parent - 3.0.0-SNAPSHOT + azure-cosmos-parent + 3.0.0-a1-SNAPSHOT - azure-cosmosdb-commons-test-utils + azure-cosmos-commons-test-utils Common Test Components for Testing Async SDK for SQL API of Azure Cosmos DB Service Common Test Components for Testing Async SDK for SQL API of Azure Cosmos DB Service jar @@ -70,6 +70,21 @@ SOFTWARE. + + org.apache.maven.plugins + maven-antrun-plugin + 1.8 + false + + + none + default-cli + + + + true + + @@ -94,7 +109,7 @@ SOFTWARE. com.microsoft.azure - azure-cosmosdb-commons + azure-cosmos-commons org.slf4j diff --git a/commons/pom.xml b/commons/pom.xml index 293faef19f94d..82b0280ba0974 100644 --- a/commons/pom.xml +++ b/commons/pom.xml @@ -26,10 +26,10 @@ SOFTWARE. 4.0.0 com.microsoft.azure - azure-cosmosdb-parent - 3.0.0-SNAPSHOT + azure-cosmos-parent + 3.0.0-a1-SNAPSHOT - azure-cosmosdb-commons + azure-cosmos-commons Common Components for Async SDK for SQL API of Azure Cosmos DB Service Common Components for Async SDK for SQL API of Azure Cosmos DB Service jar @@ -56,6 +56,21 @@ SOFTWARE. + + org.apache.maven.plugins + maven-antrun-plugin + 1.8 + false + + + none + default-cli + + + + true + + diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java index 78c0bf4e23ffa..9775dad3dfc79 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java @@ -24,7 +24,8 @@ package com.microsoft.azure.cosmosdb.internal; /** - * Used internally. HTTP constants in the Azure Cosmos DB database service Java SDK. + * Used internally. HTTP constants in the Azure Cosmos DB database service Java + * SDK. */ public class HttpConstants { public static class HttpMethods { @@ -125,7 +126,7 @@ public static class HttpHeaders { public static final String TARGET_LSN = "x-ms-target-lsn"; public static final String TARGET_GLOBAL_COMMITTED_LSN = "x-ms-target-global-committed-lsn"; - //Request validation + // Request validation public static final String REQUEST_VALIDATION_FAILURE = "x-ms-request-validation-failure"; public static final String WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH = "x-ms-write-request-trigger-refresh"; @@ -192,7 +193,7 @@ public static class HttpHeaders { public static final String INDEX_TRANSFORMATION_PROGRESS = "x-ms-documentdb-collection-index-transformation-progress"; public static final String LAZY_INDEXING_PROGRESS = "x-ms-documentdb-collection-lazy-indexing-progress"; - //Owner name + // Owner name public static final String OWNER_FULL_NAME = "x-ms-alt-content-path"; // Owner ID used for name based request in session token. @@ -218,7 +219,8 @@ public static class HttpHeaders { public static final String A_IM = "A-IM"; public static final String ALLOW_TENTATIVE_WRITES = "x-ms-cosmos-allow-tentative-writes"; - // These settings were added to support RNTBD and they've been added here to reduce merge conflicts + // These settings were added to support RNTBD and they've been added here to + // reduce merge conflicts public static final String CAN_CHARGE = "x-ms-cancharge"; public static final String CAN_OFFER_REPLACE_COMPLETE = "x-ms-can-offer-replace-complete"; @@ -268,8 +270,9 @@ public static class Versions { public static final String CURRENT_VERSION = "2018-12-31"; // TODO: FIXME we can use maven plugin for generating a version file - // @see https://stackoverflow.com/questions/2469922/generate-a-version-java-file-in-maven - public static final String SDK_VERSION = "3.0.0-SNAPSHOT"; + // @see + // https://stackoverflow.com/questions/2469922/generate-a-version-java-file-in-maven + public static final String SDK_VERSION = "3.0.0-a1-SNAPSHOT"; public static final String SDK_NAME = "cosmosdb-java-sdk"; } @@ -296,7 +299,7 @@ public static class StatusCodes { } public static class SubStatusCodes { - // Unknown SubStatus Code + // Unknown SubStatus Code public static final int UNKNOWN = 0; // 400: Bad Request substatus @@ -318,6 +321,6 @@ public static class SubStatusCodes { } public static class HeaderValues { - public static final String NoCache = "no-cache"; + public static final String NoCache = "no-cache"; } } diff --git a/direct-impl/pom.xml b/direct-impl/pom.xml index 407e05f2cc06c..e925fe6321287 100644 --- a/direct-impl/pom.xml +++ b/direct-impl/pom.xml @@ -25,16 +25,16 @@ SOFTWARE. 4.0.0 com.microsoft.azure - azure-cosmosdb-direct + azure-cosmos-direct Azure Cosmos DB Async SDK Direct Internal Implementation - 3.0.0-SNAPSHOT + 3.0.0-a1-SNAPSHOT Azure Cosmos DB Async SDK Direct Internal Implementation https://docs.microsoft.com/en-us/azure/cosmos-db jar UTF-8 unit - 3.0.0-SNAPSHOT + 3.0.0-a1-SNAPSHOT 27.0.1-jre @@ -219,7 +219,6 @@ SOFTWARE. - maven-javadoc-plugin 3.0.1 @@ -261,6 +260,21 @@ SOFTWARE. + + org.apache.maven.plugins + maven-antrun-plugin + 1.8 + false + + + none + default-cli + + + + true + + @@ -285,12 +299,12 @@ SOFTWARE. com.microsoft.azure - azure-cosmosdb-gateway + azure-cosmos-gateway ${cosmosdb-sdk.version} com.microsoft.azure - azure-cosmosdb-commons-test-utils + azure-cosmos-commons-test-utils ${cosmosdb-sdk.version} test diff --git a/examples/pom.xml b/examples/pom.xml index f95c90de11847..8865464255d38 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -28,11 +28,11 @@ 4.0.0 com.microsoft.azure - azure-cosmosdb-parent - 3.0.0-SNAPSHOT + azure-cosmos-parent + 3.0.0-a1-SNAPSHOT - azure-cosmosdb-examples + azure-cosmos-examples Async SDK for SQL API of Azure Cosmos DB Service - Examples Examples for Async SDK for SQL API of Azure Cosmos DB Service @@ -95,22 +95,37 @@ + + org.apache.maven.plugins + maven-antrun-plugin + 1.8 + false + + + none + default-cli + + + + true + + - com.microsoft.azure - azure-cosmosdb - + com.microsoft.azure + azure-cosmos + com.microsoft.azure - azure-cosmosdb-commons-test-utils + azure-cosmos-commons-test-utils + + + com.google.guava + guava + ${guava.version} - - com.google.guava - guava - ${guava.version} - io.reactivex rxjava-guava diff --git a/gateway/pom.xml b/gateway/pom.xml index ff0f98aef71d2..ab4eaec0ab1ab 100644 --- a/gateway/pom.xml +++ b/gateway/pom.xml @@ -26,10 +26,10 @@ SOFTWARE. 4.0.0 com.microsoft.azure - azure-cosmosdb-parent - 3.0.0-SNAPSHOT + azure-cosmos-parent + 3.0.0-a1-SNAPSHOT - azure-cosmosdb-gateway + azure-cosmos-gateway Common Gateway Components for Async SDK for SQL API of Azure Cosmos DB Service Common Gateway Components for Async SDK for SQL API of Azure Cosmos DB Service jar @@ -56,6 +56,21 @@ SOFTWARE. + + org.apache.maven.plugins + maven-antrun-plugin + 1.8 + false + + + none + default-cli + + + + true + + @@ -80,11 +95,11 @@ SOFTWARE. com.microsoft.azure - azure-cosmosdb-commons + azure-cosmos-commons com.microsoft.azure - azure-cosmosdb-commons-test-utils + azure-cosmos-commons-test-utils test diff --git a/pom.xml b/pom.xml index 66119ea309925..426d6986c9501 100644 --- a/pom.xml +++ b/pom.xml @@ -25,8 +25,8 @@ 4.0.0 com.microsoft.azure - azure-cosmosdb-parent - 3.0.0-SNAPSHOT + azure-cosmos-parent + 3.0.0-a1-SNAPSHOT pom Azure Cosmos DB SQL API Java Async SDK (with Reactive Extension RX support) for Azure Cosmos DB SQL API @@ -66,7 +66,10 @@ 1.6 Bismuth-RELEASE unit - 3.0.0-SNAPSHOT + 3.0.0-a1-SNAPSHOT + 3.0.0-a1-SNAPSHOT + 3.0.0-a1-SNAPSHOT + ${project.basedir}/target/collectedArtifactsForRelease @@ -305,6 +308,84 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.8 + + + + org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 + + + + + + org.apache.maven.plugins + maven-antrun-plugin + 1.8 + + + + default-cli + + + + + + + + + + + + + + + + + + + + + + + + + + + + run + + + + @@ -330,27 +411,27 @@ com.microsoft.azure - azure-cosmosdb + azure-cosmos ${project.parent.version} com.microsoft.azure - azure-cosmosdb-commons + azure-cosmos-commons ${project.parent.version} com.microsoft.azure - azure-cosmosdb-gateway + azure-cosmos-gateway ${project.parent.version} com.microsoft.azure - azure-cosmosdb-direct + azure-cosmos-direct ${cosmosdb-sdk-direct-impl.version} com.microsoft.azure - azure-cosmosdb-commons-test-utils + azure-cosmos-commons-test-utils ${project.parent.version} diff --git a/sdk/pom.xml b/sdk/pom.xml index 05b3cdf373792..6c7c9920a867b 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -26,10 +26,10 @@ SOFTWARE. 4.0.0 com.microsoft.azure - azure-cosmosdb-parent - 3.0.0-SNAPSHOT + azure-cosmos-parent + 3.0.0-a1-SNAPSHOT - azure-cosmosdb + azure-cosmos Async SDK for SQL API of Azure Cosmos DB Service Java Async SDK (with Reactive Extension rx support) for Azure Cosmos DB SQL API jar @@ -69,6 +69,21 @@ SOFTWARE. + + org.apache.maven.plugins + maven-antrun-plugin + 1.8 + false + + + none + default-cli + + + + true + + @@ -146,19 +161,19 @@ SOFTWARE. com.microsoft.azure - azure-cosmosdb-commons + azure-cosmos-commons com.microsoft.azure - azure-cosmosdb-gateway + azure-cosmos-gateway com.microsoft.azure - azure-cosmosdb-direct + azure-cosmos-direct com.microsoft.azure - azure-cosmosdb-commons-test-utils + azure-cosmos-commons-test-utils test From 5809664699ed34b1846a5b7bbc1f81245054e90c Mon Sep 17 00:00:00 2001 From: Christopher Anderson Date: Sun, 9 Jun 2019 03:54:20 -0700 Subject: [PATCH 35/85] JsonSerializable changes (#172) * Remove HashMap from public methods - fixes #155 * ObjectMapper methods to package private - fixes #153 * Remove CosmosItemSettings constructor with ObjectMapper --- .../azure/cosmosdb/rx/ResourceValidator.java | 8 ++++---- .../azure/cosmos/CosmosItemSettings.java | 13 +------------ .../com/microsoft/azure/cosmosdb/Document.java | 3 ++- .../azure/cosmosdb/JsonSerializable.java | 18 +++++++----------- .../com/microsoft/azure/cosmosdb/Resource.java | 3 ++- .../cosmosdb/rx/OrderbyDocumentQueryTest.java | 2 +- 6 files changed, 17 insertions(+), 30 deletions(-) diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceValidator.java b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceValidator.java index a95a6346089c9..d2bba2e3cd837 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceValidator.java +++ b/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceValidator.java @@ -54,11 +54,11 @@ public Builder areEqual(T expectedValue) { @Override public void validate(T v) { - assertThat(v.getHashMap().keySet()) + assertThat(v.getMap().keySet()) .describedAs("number of fields"). - hasSize(expectedValue.getHashMap().keySet().size()); - expectedValue.getHashMap().keySet(); - for(String key: expectedValue.getHashMap().keySet()) { + hasSize(expectedValue.getMap().keySet().size()); + expectedValue.getMap().keySet(); + for(String key: expectedValue.getMap().keySet()) { assertThat(expectedValue.get(key)) .describedAs("value for " + key) .isEqualTo(expectedValue.get(key)); diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java index 6bee41456d56e..050d5136b373b 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java +++ b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java @@ -48,18 +48,7 @@ public CosmosItemSettings() {} public CosmosItemSettings(String jsonString) { super(jsonString); } - - - /** - * Initialize an CosmosItemSettings object from json string. - * - * @param jsonString the json string that represents the item object. - * @param objectMapper the custom object mapper - */ - public CosmosItemSettings(String jsonString, ObjectMapper objectMapper) { - super(jsonString, objectMapper); - } - + /** * fromObject returns Document for compatibility with V2 sdk * diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Document.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/Document.java index 31922b93adba1..59e77a5ede98f 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Document.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/Document.java @@ -50,7 +50,8 @@ public Document() { * @param jsonString the json string that represents the document object. * @param objectMapper the custom object mapper */ - public Document(String jsonString, ObjectMapper objectMapper) { + Document(String jsonString, ObjectMapper objectMapper) { + // TODO: Made package private due to #153. #171 adding custom serialization options back. super(jsonString, objectMapper); } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/JsonSerializable.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/JsonSerializable.java index 27b52d80d51b2..64b8a40f48fe7 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/JsonSerializable.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/JsonSerializable.java @@ -24,15 +24,9 @@ package com.microsoft.azure.cosmosdb; import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; +import java.util.*; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; @@ -64,7 +58,8 @@ protected JsonSerializable() { * @param jsonString the json string that represents the JsonSerializable. * @param objectMapper the custom object mapper */ - protected JsonSerializable(String jsonString, ObjectMapper objectMapper) { + JsonSerializable(String jsonString, ObjectMapper objectMapper) { + // TODO: Made package private due to #153. #171 adding custom serialization options back. this.propertyBag = fromJson(jsonString); this.om = objectMapper; } @@ -87,8 +82,9 @@ protected JsonSerializable(String jsonString) { this.propertyBag = objectNode; } - protected ObjectMapper getMapper() { - if (this.om != null) { return this.om; } + ObjectMapper getMapper() { + // TODO: Made package private due to #153. #171 adding custom serialization options back. + if (this.om != null) { return this.om; } return OBJECT_MAPPER; } @@ -115,7 +111,7 @@ void populatePropertyBag() { * * @return the HashMap. */ - public HashMap getHashMap() { + public Map getMap() { return getMapper().convertValue(this.propertyBag, HashMap.class); } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java index 2ceb5fdb6cf0e..da3d723b3e0b5 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java +++ b/commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java @@ -72,7 +72,8 @@ protected Resource() { * @param jsonString the json string that represents the resource. * @param objectMapper the custom object mapper */ - protected Resource(String jsonString, ObjectMapper objectMapper) { + Resource(String jsonString, ObjectMapper objectMapper) { + // TODO: Made package private due to #153. #171 adding custom serialization options back. super(jsonString, objectMapper); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java index d54f7ffba7d2a..37c521e4478f6 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java @@ -261,7 +261,7 @@ public void queryOrderWithTop(int topValue) throws Exception { private List sortDocumentsAndCollectResourceIds(String propName, Function extractProp, Comparator comparer) { return createdDocuments.stream() - .filter(d -> d.getHashMap().containsKey(propName)) // removes undefined + .filter(d -> d.getMap().containsKey(propName)) // removes undefined .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) .map(d -> d.getResourceId()).collect(Collectors.toList()); } From 9d49eceaa182fe152647553c9ee2e7240693ea32 Mon Sep 17 00:00:00 2001 From: Christopher Anderson Date: Sun, 9 Jun 2019 05:03:22 -0700 Subject: [PATCH 36/85] Refactoring & package renaming (#178) * Refactoring POCOs based on rules * package rename * Package visibility issues * fix example pom * fix enum value handling --- README.md | 4 +- benchmark/pom.xml | 4 +- .../cosmos}/benchmark/AsyncBenchmark.java | 30 +- .../benchmark/AsyncMixedBenchmark.java | 22 +- .../benchmark/AsyncQueryBenchmark.java | 36 +- .../AsyncQuerySinglePartitionMultiple.java | 16 +- .../cosmos}/benchmark/AsyncReadBenchmark.java | 16 +- .../benchmark/AsyncWriteBenchmark.java | 12 +- .../data/cosmos}/benchmark/Configuration.java | 30 +- .../data/cosmos}/benchmark/DocDBUtils.java | 24 +- .../data/cosmos}/benchmark/Main.java | 4 +- .../benchmark/ReadMyWriteWorkflow.java | 41 +- benchmark/src/main/resources/log4j.properties | 2 +- .../cosmos}/benchmark/QueryBuilderTest.java | 23 +- .../ReadMyWritesConsistencyTest.java | 48 +- .../data/cosmos}/benchmark/Utils.java | 32 +- .../data/cosmos}/benchmark/WorkflowTest.java | 92 +- changelog/README.md | 97 ++- .../data/cosmos}/BridgeUtils.java | 12 +- .../data/cosmos}/ConfigsBuilder.java | 6 +- .../data/cosmos}/DatabaseForTest.java | 16 +- .../data/cosmos}/RetryAnalyzer.java | 4 +- .../HttpClientUnderTestWrapper.java | 2 +- .../StoreResponseBuilder.java | 5 +- ...ocumentServiceRequestContextValidator.java | 9 +- .../rx/DocumentServiceRequestValidator.java | 8 +- .../data/cosmos}/rx/FailureValidator.java | 82 +- .../cosmos}/rx/FeedResponseListValidator.java | 63 +- .../cosmos}/rx/FeedResponseValidator.java | 26 +- .../cosmos}/rx/ResourceResponseValidator.java | 67 +- .../data/cosmos}/rx/ResourceValidator.java | 4 +- .../data/cosmos}/rx/TestConfigurations.java | 6 +- .../data/cosmos}/rx/Utils.java | 8 +- .../data/cosmos}/ConfigsBuilderTest.java | 6 +- .../data/cosmos}/AccessCondition.java | 14 +- .../data/cosmos}/AccessConditionType.java | 6 +- .../data/cosmos}/Attachment.java | 4 +- .../data/cosmos}/BridgeInternal.java | 136 +-- .../data/cosmos}/ChangeFeedOptions.java | 58 +- .../cosmos}/ClientSideRequestStatistics.java | 14 +- .../data/cosmos}/CommonsBridgeInternal.java | 6 +- .../data/cosmos}/CompositePath.java | 22 +- .../data/cosmos}/CompositePathSortOrder.java | 10 +- .../data/cosmos}/Conflict.java | 6 +- .../data/cosmos}/ConflictResolutionMode.java | 20 +- .../cosmos}/ConflictResolutionPolicy.java | 82 +- .../data/cosmos}/ConnectionMode.java | 12 +- .../data/cosmos}/ConnectionPolicy.java | 108 +-- .../data/cosmos}/ConsistencyLevel.java | 22 +- .../data/cosmos}/ConsistencyPolicy.java | 24 +- .../data/cosmos/CosmosClientException.java} | 104 +-- .../cosmos/CosmosContainerRequestOptions.java | 13 +- .../data}/cosmos/CosmosContainerSettings.java | 41 +- .../cosmos/CosmosDatabaseRequestOptions.java | 6 +- .../data}/cosmos/CosmosDatabaseSettings.java | 8 +- .../data}/cosmos/CosmosFeedResponse.java | 7 +- .../data/cosmos/CosmosItemProperties.java} | 30 +- .../cosmos/CosmosItemRequestOptions.java | 45 +- .../data}/cosmos/CosmosRequestOptions.java | 7 +- .../data}/cosmos/CosmosResource.java | 26 +- .../data/cosmos}/CosmosResourceType.java | 2 +- .../data}/cosmos/CosmosResponse.java | 50 +- .../CosmosStoredProcedureRequestOptions.java | 23 +- .../cosmos/CosmosStoredProcedureSettings.java | 40 +- .../data/cosmos/CosmosTriggerSettings.java | 130 +++ .../CosmosUserDefinedFunctionSettings.java | 26 +- .../data}/cosmos/CosmosUserSettings.java | 10 +- .../data/cosmos}/DataType.java | 14 +- .../data/cosmos}/Database.java | 8 +- .../data/cosmos}/DatabaseAccount.java | 8 +- .../data/cosmos}/DatabaseAccountLocation.java | 6 +- .../data/cosmos}/Document.java | 4 +- .../data/cosmos}/DocumentCollection.java | 18 +- .../cosmosdb => azure/data/cosmos}/Error.java | 4 +- .../data/cosmos}/ExcludedPath.java | 9 +- .../data/cosmos}/FeedOptions.java | 107 +-- .../data/cosmos}/FeedOptionsBase.java | 27 +- .../data/cosmos}/FeedResponse.java | 118 +-- .../data/cosmos}/HashIndex.java | 37 +- .../data/cosmos}/IncludedPath.java | 27 +- .../cosmosdb => azure/data/cosmos}/Index.java | 28 +- .../data/cosmos}/IndexKind.java | 12 +- .../data/cosmos}/IndexingDirective.java | 8 +- .../data/cosmos}/IndexingMode.java | 10 +- .../data/cosmos}/IndexingPolicy.java | 64 +- .../data/cosmos}/JsonSerializable.java | 22 +- .../data/cosmos}/MediaOptions.java | 2 +- .../data/cosmos}/MediaReadMode.java | 2 +- .../data/cosmos}/MediaResponse.java | 4 +- .../cosmosdb => azure/data/cosmos}/Offer.java | 6 +- .../data/cosmos}/PartitionKey.java | 22 +- .../data/cosmos}/PartitionKeyDefinition.java | 29 +- .../PartitionKeyDefinitionVersion.java | 4 +- .../data/cosmos}/PartitionKeyRange.java | 14 +- .../data/cosmos}/PartitionKind.java | 4 +- .../data/cosmos}/Permission.java | 7 +- .../data/cosmos}/PermissionMode.java | 6 +- .../data/cosmos}/QueryMetrics.java | 10 +- .../data/cosmos}/QueryMetricsConstants.java | 2 +- .../data/cosmos}/QueryMetricsUtils.java | 4 +- .../data/cosmos}/QueryPreparationTimes.java | 2 +- .../data/cosmos}/RangeIndex.java | 37 +- .../data/cosmos}/ReplicationPolicy.java | 4 +- .../data/cosmos}/RequestOptions.java | 4 +- .../data/cosmos}/Resource.java | 65 +- .../data/cosmos}/ResourceResponse.java | 8 +- .../data/cosmos}/RetryOptions.java | 12 +- .../data/cosmos}/RuntimeExecutionTimes.java | 2 +- .../SerializationFormattingPolicy.java | 6 +- .../data/cosmos}/SpatialIndex.java | 24 +- .../data/cosmos}/SpatialSpec.java | 14 +- .../data/cosmos}/SpatialType.java | 10 +- .../data/cosmos}/SqlParameter.java | 16 +- .../data/cosmos}/SqlParameterCollection.java | 2 +- .../data/cosmos}/SqlQuerySpec.java | 16 +- .../data/cosmos}/StoredProcedure.java | 4 +- .../data/cosmos}/StoredProcedureResponse.java | 8 +- .../data/cosmos}/TokenResolver.java | 2 +- .../data/cosmos}/Trigger.java | 17 +- .../data/cosmos}/TriggerOperation.java | 22 +- .../data/cosmos}/TriggerType.java | 6 +- .../data/cosmos}/Undefined.java | 4 +- .../data/cosmos}/UniqueKey.java | 9 +- .../data/cosmos}/UniqueKeyPolicy.java | 9 +- .../cosmosdb => azure/data/cosmos}/User.java | 6 +- .../data/cosmos}/UserDefinedFunction.java | 4 +- .../cosmos}/directconnectivity/Address.java | 6 +- .../AddressInformation.java | 6 +- .../directconnectivity/GoneException.java | 18 +- .../cosmos}/directconnectivity/HttpUtils.java | 8 +- .../cosmos}/directconnectivity/Protocol.java | 8 +- .../RequestTimeoutException.java | 16 +- .../directconnectivity/StoreResponse.java | 6 +- .../directconnectivity/StoreResult.java | 46 +- .../directconnectivity/TimeoutHelper.java | 2 +- .../directconnectivity/WFConstants.java | 2 +- .../internal/AuthorizationTokenType.java | 2 +- .../cosmos}/internal/BadRequestException.java | 13 +- .../data/cosmos}/internal/Bytes.java | 2 +- .../data/cosmos}/internal/Configs.java | 8 +- .../data/cosmos}/internal/Constants.java | 2 +- .../DocumentServiceRequestContext.java | 18 +- .../data/cosmos}/internal/Exceptions.java | 17 +- .../cosmos}/internal/HttpClientFactory.java | 32 +- .../data/cosmos}/internal/HttpConstants.java | 10 +- .../data/cosmos}/internal/ISessionToken.java | 10 +- .../data/cosmos}/internal/Integers.java | 4 +- .../cosmos}/internal/InternalConstants.java | 2 +- .../InternalServerErrorException.java | 13 +- .../cosmos}/internal/JavaStreamUtils.java | 6 +- .../data/cosmos}/internal/LifeCycleUtils.java | 2 +- .../data/cosmos}/internal/Lists.java | 2 +- .../data/cosmos}/internal/Longs.java | 4 +- .../cosmos}/internal/MutableVolatile.java | 2 +- .../data/cosmos}/internal/OperationType.java | 2 +- .../data/cosmos}/internal/PathInfo.java | 2 +- .../data/cosmos}/internal/PathParser.java | 7 +- .../data/cosmos}/internal/Paths.java | 2 +- .../data/cosmos}/internal/PathsHelper.java | 33 +- .../data/cosmos}/internal/Quadruple.java | 2 +- .../internal/QueryCompatibilityMode.java | 2 +- .../data/cosmos}/internal/RMResources.java | 14 +- .../internal/RequestChargeTracker.java | 2 +- .../data/cosmos}/internal/ResourceId.java | 4 +- .../ResourceTokenAuthorizationHelper.java | 7 +- .../data/cosmos}/internal/ResourceType.java | 2 +- .../cosmos}/internal/RuntimeConstants.java | 2 +- .../internal/RxDocumentServiceRequest.java | 30 +- .../internal/RxDocumentServiceResponse.java | 42 +- .../data/cosmos}/internal/Strings.java | 2 +- .../data/cosmos}/internal/Utils.java | 272 ++++-- .../query/metrics/ClientSideMetrics.java | 2 +- .../query/metrics/FetchExecutionRange.java | 2 +- .../FetchExecutionRangeAccumulator.java | 2 +- .../query/metrics/QueryMetricsTextWriter.java | 8 +- .../query/metrics/QueryMetricsWriter.java | 10 +- .../query/metrics/SchedulingStopwatch.java | 2 +- .../query/metrics/SchedulingTimeSpan.java | 4 +- .../internal/query/metrics/TextTable.java | 2 +- .../routing/BoolPartitionKeyComponent.java | 4 +- .../routing/IPartitionKeyComponent.java | 2 +- .../InfinityPartitionKeyComponent.java | 4 +- .../MaxNumberPartitionKeyComponent.java | 4 +- .../MaxStringPartitionKeyComponent.java | 4 +- .../MinNumberPartitionKeyComponent.java | 4 +- .../MinStringPartitionKeyComponent.java | 4 +- .../routing/NullPartitionKeyComponent.java | 4 +- .../routing/NumberPartitionKeyComponent.java | 5 +- .../PartitionKeyAndResourceTokenPair.java | 2 +- .../routing/PartitionKeyComponentType.java | 2 +- .../routing/PartitionKeyInternal.java | 12 +- .../routing/PartitionKeyRangeIdentity.java | 2 +- .../data/cosmos}/internal/routing/Range.java | 5 +- .../routing/StringPartitionKeyComponent.java | 6 +- .../UndefinedPartitionKeyComponent.java | 4 +- .../data/cosmos}/package-info.java | 2 +- .../azure/cosmos/CosmosTriggerSettings.java | 56 -- .../azure/cosmosdb/rx/internal/Utils.java | 172 ---- .../data/cosmos}/ConflictTests.java | 10 +- .../data/cosmos}/ConnectionPolicyTest.java | 16 +- .../cosmos/CosmosClientExceptionTest.java} | 48 +- .../data/cosmos}/DocumentCollectionTests.java | 17 +- .../data/cosmos}/DocumentTests.java | 7 +- .../data/cosmos}/IncludedPathTest.java | 19 +- .../data/cosmos}/JsonSerializableTests.java | 13 +- .../data/cosmos}/PermissionTest.java | 7 +- .../data/cosmos}/ResourceIdTests.java | 4 +- .../directconnectivity/HttpUtilsTest.java | 5 +- .../directconnectivity/StoreResponseTest.java | 2 +- .../cosmos}/internal/PathsHelperTest.java | 5 +- .../RxDocumentServiceRequestTest.java | 7 +- .../data/cosmos}/internal/TimeTokenTest.java | 2 +- .../StringPartitionKeyComponentTest.java | 2 +- commons/src/test/resources/log4j.properties | 2 +- .../directconnectivity/AddressResolver.java | 116 +-- .../directconnectivity/AddressSelector.java | 6 +- .../BarrierRequestHelper.java | 29 +- .../directconnectivity/ConflictException.java | 14 +- .../directconnectivity/ConsistencyReader.java | 104 +-- .../directconnectivity/ConsistencyWriter.java | 50 +- .../directconnectivity/CustomHeaders.java | 2 +- .../directconnectivity/ErrorUtils.java | 2 +- .../ForbiddenException.java | 14 +- .../GatewayAddressCache.java | 59 +- .../GatewayServiceConfigurationReader.java | 28 +- .../GoneAndRetryWithRetryPolicy.java | 31 +- .../directconnectivity/HttpClientUtils.java | 14 +- .../HttpTransportClient.java | 70 +- .../directconnectivity/IAddressCache.java | 6 +- .../directconnectivity/IAddressResolver.java | 4 +- .../directconnectivity/IStoreClient.java | 8 +- .../directconnectivity/LockedException.java | 14 +- .../MethodNotAllowedException.java | 14 +- .../PartitionKeyRangeGoneException.java | 19 +- .../PreconditionFailedException.java | 14 +- .../QueryRequestPerformanceActivity.java | 2 +- .../directconnectivity/QuorumReader.java | 50 +- .../cosmos}/directconnectivity/ReadMode.java | 2 +- .../ReplicatedResourceClient.java | 30 +- .../RequestEntityTooLargeException.java | 14 +- .../directconnectivity/RequestHelper.java | 18 +- .../RequestRateTooLargeException.java | 15 +- .../directconnectivity/ResourceOperation.java | 6 +- .../directconnectivity/ResponseUtils.java | 14 +- .../RetryWithException.java | 14 +- .../RntbdTransportClient.java | 16 +- .../directconnectivity/ServerProperties.java | 2 +- .../directconnectivity/ServerStoreModel.java | 20 +- .../directconnectivity/ServiceConfig.java | 2 +- .../ServiceUnavailableException.java | 14 +- .../directconnectivity/StoreClient.java | 58 +- .../StoreClientFactory.java | 14 +- .../directconnectivity/StoreReader.java | 100 +-- .../directconnectivity/TransportClient.java | 4 +- .../TransportException.java | 6 +- .../UnauthorizedException.java | 14 +- .../rntbd/RntbdClientChannelInitializer.java | 8 +- .../rntbd/RntbdConstants.java | 2 +- .../rntbd/RntbdContext.java | 10 +- .../rntbd/RntbdContextDecoder.java | 2 +- .../rntbd/RntbdContextNegotiator.java | 4 +- .../rntbd/RntbdContextRequest.java | 14 +- .../rntbd/RntbdContextRequestDecoder.java | 2 +- .../rntbd/RntbdContextRequestEncoder.java | 2 +- .../directconnectivity/rntbd/RntbdFramer.java | 2 +- .../rntbd/RntbdObjectMapper.java | 2 +- .../rntbd/RntbdRequest.java | 4 +- .../rntbd/RntbdRequestArgs.java | 4 +- .../rntbd/RntbdRequestDecoder.java | 2 +- .../rntbd/RntbdRequestEncoder.java | 2 +- .../rntbd/RntbdRequestFrame.java | 10 +- .../rntbd/RntbdRequestFramer.java | 2 +- .../rntbd/RntbdRequestHeaders.java | 70 +- .../rntbd/RntbdRequestManager.java | 68 +- .../rntbd/RntbdResponse.java | 6 +- .../rntbd/RntbdResponseDecoder.java | 2 +- .../rntbd/RntbdResponseHeaders.java | 10 +- .../rntbd/RntbdResponseStatus.java | 2 +- .../directconnectivity/rntbd/RntbdToken.java | 6 +- .../rntbd/RntbdTokenStream.java | 4 +- .../rntbd/RntbdTokenType.java | 10 +- .../directconnectivity/rntbd/RntbdUUID.java | 2 +- .../internal/ContentSerializationFormat.java | 4 +- .../internal/EnumerationDirection.java | 2 +- .../internal/FanoutOperationState.java | 2 +- .../internal/MigrateCollectionDirective.java | 2 +- .../cosmos}/internal/ReadFeedKeyType.java | 2 +- .../cosmos}/internal/RemoteStorageType.java | 2 +- .../data/cosmos}/internal/routing/Int128.java | 2 +- .../internal/routing/MurmurHash3_128.java | 2 +- .../internal/routing/MurmurHash3_32.java | 2 +- .../routing/PartitionKeyInternalHelper.java | 22 +- .../cosmos}/internal/routing/UInt128.java | 2 +- .../cosmos}/PartitionKeyHashingTests.java | 30 +- .../AddressResolverTest.java | 162 ++-- .../AddressSelectorTest.java | 70 +- .../AddressSelectorWrapper.java | 8 +- .../ConsistencyReaderTest.java | 118 +-- .../ConsistencyReaderUnderTest.java | 8 +- .../ConsistencyWriterTest.java | 42 +- .../directconnectivity/EndpointMock.java | 6 +- .../directconnectivity/ExceptionBuilder.java | 22 +- .../Function1WithCheckedException.java | 2 +- .../Function2WithCheckedException.java | 2 +- .../GatewayServiceConfiguratorReaderMock.java | 8 +- .../GoneAndRetryWithRetryPolicyTest.java | 28 +- .../HttpClientMockWrapper.java | 2 +- .../HttpTransportClientTest.java | 30 +- .../MultiStoreResultValidator.java | 10 +- .../MurmurHash3_32Test.java | 4 +- .../PartitionKeyInternalTest.java | 28 +- .../directconnectivity/PartitionKeyTest.java | 16 +- .../directconnectivity/QuorumReaderTest.java | 24 +- .../ReplicaAddressFactory.java | 2 +- ...catedResourceClientPartitionSplitTest.java | 44 +- .../ReplicatedResourceClientTest.java | 20 +- .../RntbdTransportClientTest.java | 58 +- .../StoreReaderDotNetTest.java | 80 +- .../directconnectivity/StoreReaderTest.java | 96 +-- .../StoreReaderUnderTest.java | 6 +- .../StoreResponseValidator.java | 6 +- .../StoreResultValidator.java | 10 +- .../directconnectivity/TimeoutHelperTest.java | 2 +- .../TransportClientWrapper.java | 10 +- .../WebExceptionUtilityTest.java | 2 +- .../data/cosmos}/internal/RetryUtilsTest.java | 15 +- .../routing/PartitionKeyInternalUtils.java | 2 +- .../src/test/resources/log4j.properties | 2 +- examples/pom.xml | 4 +- .../cosmos/examples/AccountSettings.java | 4 +- .../data}/cosmos/examples/BasicDemo.java | 69 +- .../ChangeFeed/SampleChangeFeedProcessor.java | 60 +- .../ChangeFeed/SampleConfigurations.java | 4 +- .../ChangeFeed/SampleObserverImpl.java | 20 +- .../multimaster/ConfigurationManager.java | 2 +- .../rx/examples/multimaster/Helpers.java | 36 +- .../multimaster/samples/ConflictWorker.java | 155 ++-- .../rx/examples/multimaster/samples/Main.java | 4 +- .../samples/MultiMasterScenario.java | 17 +- .../examples/multimaster/samples/Worker.java | 40 +- examples/src/main/resources/log4j.properties | 12 +- .../examples/CollectionCRUDAsyncAPITest.java | 80 +- .../cosmos}/rx/examples/ConflictAPITest.java | 56 +- .../rx/examples/DatabaseCRUDAsyncAPITest.java | 57 +- .../rx/examples/DocumentCRUDAsyncAPITest.java | 98 +-- .../examples/DocumentQueryAsyncAPITest.java | 110 +-- .../rx/examples/InMemoryGroupbyTest.java | 56 +- .../rx/examples/OfferCRUDAsyncAPITest.java | 68 +- .../examples/StoredProcedureAsyncAPITest.java | 70 +- .../rx/examples/TestConfigurations.java | 4 +- .../rx/examples/TokenResolverTest.java | 126 +-- .../rx/examples/UniqueIndexAsyncAPITest.java | 39 +- .../data/cosmos}/rx/examples/Utils.java | 34 +- .../DatabaseAccountManagerInternal.java | 2 +- .../data/cosmos}/ISessionContainer.java | 6 +- .../WebExceptionUtility.java | 4 +- .../internal/AuthorizationTokenProvider.java | 2 +- .../cosmos}/internal/BackoffRetryUtility.java | 4 +- .../BaseAuthorizationTokenProvider.java | 7 +- ...eDatabaseAccountConfigurationProvider.java | 6 +- ...ringSessionContainerClientRetryPolicy.java | 9 +- .../cosmos}/internal/ClientRetryPolicy.java | 21 +- .../ConnectionPoolExhaustedRetry.java | 4 +- .../DatabaseAccountConfigurationProvider.java | 4 +- .../internal/GlobalEndpointManager.java | 27 +- .../internal/IAuthorizationTokenProvider.java | 4 +- .../internal/ICollectionRoutingMapCache.java | 4 +- .../internal/IDocumentClientRetryPolicy.java | 2 +- .../data/cosmos}/internal/IRetryPolicy.java | 4 +- .../cosmos}/internal/IRetryPolicyFactory.java | 2 +- .../cosmos}/internal/IRoutingMapProvider.java | 6 +- .../internal/InvalidPartitionException.java | 18 +- .../InvalidPartitionExceptionRetryPolicy.java | 15 +- .../cosmos}/internal/NotFoundException.java | 13 +- .../cosmos}/internal/ObservableHelper.java | 2 +- .../PartitionIsMigratingException.java | 17 +- .../PartitionKeyMismatchRetryPolicy.java | 15 +- .../PartitionKeyRangeGoneRetryPolicy.java | 25 +- ...PartitionKeyRangeIsSplittingException.java | 17 +- ...enameCollectionAwareClientRetryPolicy.java | 15 +- .../ReplicatedResourceClientUtils.java | 5 +- .../ResetSessionTokenRetryPolicyFactory.java | 6 +- .../internal/ResourceThrottleRetryPolicy.java | 10 +- .../data/cosmos}/internal/RetryPolicy.java | 10 +- .../data/cosmos}/internal/RetryUtils.java | 9 +- .../cosmos}/internal/RxGatewayStoreModel.java | 53 +- .../data/cosmos}/internal/RxStoreModel.java | 2 +- .../cosmos}/internal/SessionContainer.java | 17 +- .../cosmos}/internal/SessionTokenHelper.java | 22 +- .../cosmos}/internal/UserAgentContainer.java | 2 +- .../cosmos}/internal/VectorSessionToken.java | 17 +- .../internal/WebExceptionRetryPolicy.java | 4 +- .../cosmos}/internal/caches/AsyncCache.java | 4 +- .../cosmos}/internal/caches/AsyncLazy.java | 2 +- .../internal/caches/IEqualityComparer.java | 2 +- .../caches/IPartitionKeyRangeCache.java | 12 +- .../caches/RxClientCollectionCache.java | 36 +- .../internal/caches/RxCollectionCache.java | 34 +- ...ggregateDocumentQueryExecutionContext.java | 45 +- .../query/CompositeContinuationToken.java | 8 +- .../DefaultDocumentQueryExecutionContext.java | 84 +- .../internal/query/DocumentProducer.java | 61 +- .../DocumentQueryExecutionContextBase.java | 84 +- .../DocumentQueryExecutionContextFactory.java | 44 +- .../internal/query/ExceptionHelper.java | 2 +- .../data/cosmos}/internal/query/Fetcher.java | 20 +- .../internal/query/IDocumentQueryClient.java | 18 +- .../IDocumentQueryExecutionComponent.java | 6 +- .../query/IDocumentQueryExecutionContext.java | 6 +- .../internal/query/ItemComparator.java | 2 +- .../data/cosmos}/internal/query/ItemType.java | 2 +- .../internal/query/ItemTypeHelper.java | 4 +- .../query/OrderByContinuationToken.java | 7 +- .../query/OrderByDocumentProducer.java | 28 +- .../OrderByDocumentQueryExecutionContext.java | 84 +- .../cosmos}/internal/query/OrderByUtils.java | 39 +- .../cosmos}/internal/query/Paginator.java | 14 +- ...ParallelDocumentQueryExecutionContext.java | 65 +- ...llelDocumentQueryExecutionContextBase.java | 34 +- .../internal/query/ParallelQueryConfig.java | 2 +- .../query/PartitionedQueryExecutionInfo.java | 8 +- ...PartitionedQueryExecutionInfoInternal.java | 12 +- ...ipelinedDocumentQueryExecutionContext.java | 27 +- .../ProxyDocumentQueryExecutionContext.java | 37 +- .../cosmos}/internal/query/QueryInfo.java | 6 +- .../cosmos}/internal/query/QueryItem.java | 6 +- .../cosmos}/internal/query/SortOrder.java | 2 +- .../internal/query/TakeContinuationToken.java | 6 +- .../TopDocumentQueryExecutionContext.java | 40 +- .../query/aggregation/AggregateOperator.java | 2 +- .../query/aggregation/Aggregator.java | 2 +- .../query/aggregation/AverageAggregator.java | 6 +- .../query/aggregation/CountAggregator.java | 2 +- .../query/aggregation/MaxAggregator.java | 6 +- .../query/aggregation/MinAggregator.java | 6 +- .../query/aggregation/SumAggregator.java | 4 +- .../query/orderbyquery/OrderByRowResult.java | 8 +- .../orderbyquery/OrderbyRowComparer.java | 12 +- .../routing/CaseInsensitiveHashMap.java | 2 +- .../routing/CollectionRoutingMap.java | 4 +- .../internal/routing/IServerIdentity.java | 2 +- .../routing/InMemoryCollectionRoutingMap.java | 14 +- .../internal/routing/LocationCache.java | 24 +- .../internal/routing/LocationHelper.java | 2 +- .../internal/routing/RoutingMapProvider.java | 4 +- .../routing/RoutingMapProviderHelper.java | 4 +- .../azure/cosmosdb/internal/RetryPolicy.java | 7 +- .../data/cosmos}/GatewayTestUtils.java | 2 +- .../internal/ClientRetryPolicyTest.java | 6 +- .../data/cosmos}/internal/ConfigsTests.java | 6 +- .../cosmos}/internal/LocationHelperTest.java | 4 +- ...eCollectionAwareClientRetryPolicyTest.java | 31 +- .../internal/RxGatewayStoreModelTest.java | 18 +- .../internal/SessionContainerTest.java | 13 +- .../cosmos}/internal/SessionTokenTest.java | 4 +- .../internal/ShouldRetryValidator.java | 4 +- .../internal/caches/AsyncCacheTest.java | 2 +- .../InMemoryCollectionRoutingMapTest.java | 32 +- .../internal/routing/LocationCacheTest.java | 34 +- .../routing/RoutingMapProviderHelperTest.java | 6 +- .../data/cosmos}/AsyncDocumentClient.java | 213 +---- .../data}/cosmos/ChangeFeedObserver.java | 4 +- .../cosmos/ChangeFeedObserverCloseReason.java | 2 +- .../cosmos/ChangeFeedObserverContext.java | 5 +- .../cosmos/ChangeFeedObserverFactory.java | 2 +- .../data}/cosmos/ChangeFeedProcessor.java | 10 +- .../cosmos/ChangeFeedProcessorOptions.java | 113 +-- .../data}/cosmos/CosmosClient.java | 42 +- .../data}/cosmos/CosmosClientBuilder.java | 12 +- .../data}/cosmos/CosmosContainer.java | 102 +-- .../data}/cosmos/CosmosContainerResponse.java | 35 +- .../data}/cosmos/CosmosDatabase.java | 62 +- .../data}/cosmos/CosmosDatabaseResponse.java | 21 +- .../data}/cosmos/CosmosItem.java | 322 ++++--- .../data}/cosmos/CosmosItemResponse.java | 116 ++- .../data}/cosmos/CosmosPermission.java | 9 +- .../cosmos/CosmosPermissionResponse.java | 13 +- .../cosmos/CosmosPermissionSettings.java | 15 +- .../CosmosPermissionsRequestOptions.java | 4 +- .../data}/cosmos/CosmosStoredProcedure.java | 12 +- .../cosmos/CosmosStoredProcedureResponse.java | 36 +- .../data}/cosmos/CosmosTrigger.java | 10 +- .../data}/cosmos/CosmosTriggerResponse.java | 13 +- .../data}/cosmos/CosmosUser.java | 29 +- .../cosmos/CosmosUserDefinedFunction.java | 12 +- .../CosmosUserDefinedFunctionResponse.java | 111 ++- .../data}/cosmos/CosmosUserResponse.java | 19 +- .../data}/cosmos/CosmosUserSettings.java | 11 +- .../data}/cosmos/changefeed/Bootstrapper.java | 2 +- .../cosmos/changefeed/CancellationToken.java | 2 +- .../changefeed/CancellationTokenSource.java | 2 +- .../changefeed/ChangeFeedContextClient.java | 43 +- .../changefeed/CheckpointFrequency.java | 4 +- .../changefeed/ContainerConnectionInfo.java | 10 +- .../cosmos/changefeed/HealthMonitor.java | 2 +- .../changefeed/HealthMonitoringRecord.java | 2 +- .../data}/cosmos/changefeed/Lease.java | 20 +- .../cosmos/changefeed/LeaseCheckpointer.java | 2 +- .../cosmos/changefeed/LeaseContainer.java | 2 +- .../data}/cosmos/changefeed/LeaseManager.java | 9 +- .../data}/cosmos/changefeed/LeaseRenewer.java | 2 +- .../data}/cosmos/changefeed/LeaseStore.java | 2 +- .../cosmos/changefeed/LeaseStoreManager.java | 12 +- .../changefeed/LeaseStoreManagerSettings.java | 4 +- .../changefeed/PartitionCheckpointer.java | 2 +- .../changefeed/PartitionController.java | 3 +- .../changefeed/PartitionLoadBalancer.java | 2 +- .../PartitionLoadBalancingStrategy.java | 16 +- .../cosmos/changefeed/PartitionManager.java | 2 +- .../cosmos/changefeed/PartitionProcessor.java | 8 +- .../changefeed/PartitionProcessorFactory.java | 4 +- .../changefeed/PartitionSupervisor.java | 2 +- .../PartitionSupervisorFactory.java | 2 +- .../changefeed/PartitionSynchronizer.java | 4 +- .../cosmos/changefeed/ProcessorSettings.java | 18 +- .../changefeed/RemainingPartitionWork.java | 2 +- .../changefeed/RemainingWorkEstimator.java | 2 +- .../changefeed/RequestOptionsFactory.java | 7 +- .../cosmos/changefeed/ServiceItemLease.java | 20 +- .../changefeed/ServiceItemLeaseUpdater.java | 7 +- .../exceptions/LeaseLostException.java | 4 +- .../exceptions/ObserverException.java | 2 +- .../exceptions/PartitionException.java | 2 +- .../PartitionNotFoundException.java | 2 +- .../exceptions/PartitionSplitException.java | 2 +- .../exceptions/TaskCancelledException.java | 2 +- .../changefeed/internal/AutoCheckpointer.java | 15 +- .../changefeed/internal/BootstrapperImpl.java | 8 +- .../internal/ChangeFeedContextClientImpl.java | 46 +- .../changefeed/internal/ChangeFeedHelper.java | 23 +- .../ChangeFeedObserverContextImpl.java | 19 +- .../ChangeFeedObserverFactoryImpl.java | 10 +- .../ChangeFeedProcessorBuilderImpl.java | 68 +- .../internal/CheckpointerObserverFactory.java | 8 +- .../cosmos/changefeed/internal/Constants.java | 4 +- .../internal/DocumentServiceLeaseStore.java | 81 +- .../DocumentServiceLeaseUpdaterImpl.java | 60 +- .../EqualPartitionsBalancingStrategy.java | 6 +- .../internal/ExceptionClassifier.java | 19 +- ...onitoringPartitionControllerDecorator.java | 14 +- .../changefeed/internal/LeaseRenewerImpl.java | 12 +- .../internal/LeaseStoreManagerImpl.java | 86 +- ...onWrappingChangeFeedObserverDecorator.java | 15 +- .../internal/PartitionCheckpointerImpl.java | 8 +- .../internal/PartitionControllerImpl.java | 28 +- .../internal/PartitionLoadBalancerImpl.java | 18 +- .../internal/PartitionManagerImpl.java | 10 +- .../PartitionProcessorFactoryImpl.java | 32 +- .../internal/PartitionProcessorImpl.java | 77 +- .../PartitionSupervisorFactoryImpl.java | 24 +- .../internal/PartitionSupervisorImpl.java | 30 +- .../internal/PartitionSynchronizerImpl.java | 30 +- ...edByIdCollectionRequestOptionsFactory.java | 17 +- .../internal/RemainingPartitionWorkImpl.java | 4 +- .../internal/RemainingWorkEstimatorImpl.java | 10 +- .../internal/StatusCodeErrorType.java | 2 +- .../internal/TraceHealthMonitor.java | 6 +- .../changefeed/internal/WorkerTask.java | 2 +- .../cosmos}/internal/ChangeFeedQueryImpl.java | 57 +- .../internal/RxDocumentClientImpl.java | 575 +++---------- .../caches/RxPartitionKeyRangeCache.java | 59 +- .../GlobalAddressResolver.java | 46 +- .../data/cosmos}/package-info.java | 2 +- .../data}/cosmos/ClientUnderTestBuilder.java | 6 +- .../data}/cosmos/CosmosBridgeInternal.java | 10 +- .../data}/cosmos/CosmosContainerCrudTest.java | 28 +- .../data}/cosmos/CosmosDatabaseCrudTest.java | 6 +- .../data}/cosmos/CosmosDatabaseForTest.java | 268 +++--- .../data}/cosmos/CosmosItemCrudTest.java | 28 +- .../data}/cosmos/CosmosPartitionKeyTests.java | 103 ++- .../data}/cosmos/CosmosResponseValidator.java | 525 ++++++------ .../data}/cosmos/CosmosTestSuiteBase.java | 34 +- .../data/cosmos}/SpyClientBuilder.java | 5 +- .../directconnectivity/AddressValidator.java | 10 +- .../BarrierRequestHelperTest.java | 34 +- .../DCDocumentCrudTest.java | 89 +- .../GatewayAddressCacheTest.java | 100 +-- ...GatewayServiceConfigurationReaderTest.java | 26 +- .../PartitionReplicasAddressesValidator.java | 6 +- .../ConnectionPoolExhaustedRetryTest.java | 8 +- .../cosmos}/internal/ConsistencyTests1.java | 109 ++- .../cosmos}/internal/ConsistencyTests2.java | 115 ++- .../internal/ConsistencyTestsBase.java | 328 ++++---- .../DocumentQuerySpyWireContentTest.java | 56 +- .../cosmos}/internal/NetworkFailureTest.java | 17 +- .../data/cosmos}/internal/ParallelAsync.java | 2 +- .../internal/RetryCreateDocumentTest.java | 39 +- .../cosmos}/internal/RetryThrottleTest.java | 43 +- .../internal/RxDocumentClientUnderTest.java | 14 +- .../data/cosmos}/internal/SessionTest.java | 49 +- .../internal/SpyClientUnderTestFactory.java | 24 +- .../cosmos}/internal/StoreHeaderTests.java | 22 +- .../data/cosmos}/internal/TestSuiteBase.java | 315 ++++--- .../GlobalAddressResolverTest.java | 54 +- .../directconnectivity/ReflectionUtils.java | 16 +- .../internal/query/DocumentProducerTest.java | 106 ++- .../internal/query/FeedResponseBuilder.java | 13 +- .../cosmos}/internal/query/FetcherTest.java | 46 +- .../data/cosmos}/rx/AggregateQueryTests.java | 50 +- .../rx/BackPressureCrossPartitionTest.java | 82 +- .../data/cosmos}/rx/BackPressureTest.java | 63 +- .../data/cosmos}/rx/ChangeFeedTest.java | 114 +-- .../data/cosmos}/rx/CollectionCrudTest.java | 655 +++++++-------- .../data/cosmos}/rx/CollectionQueryTest.java | 40 +- .../data/cosmos}/rx/DatabaseCrudTest.java | 28 +- .../data/cosmos}/rx/DatabaseQueryTest.java | 34 +- .../rx/DocumentClientResourceLeakTest.java | 20 +- .../data/cosmos}/rx/DocumentCrudTest.java | 783 +++++++++--------- .../data/cosmos}/rx/LogLevelTest.java | 101 ++- .../rx/MultiMasterConflictResolutionTest.java | 420 +++++----- .../cosmos}/rx/MultiOrderByQueryTests.java | 100 +-- .../data/cosmos}/rx/OfferQueryTest.java | 47 +- .../data/cosmos}/rx/OfferReadReplaceTest.java | 25 +- .../cosmos}/rx/OrderbyDocumentQueryTest.java | 209 +++-- .../cosmos}/rx/ParallelDocumentQueryTest.java | 188 ++--- .../data/cosmos}/rx/ParsingEnvTest.java | 16 +- .../data/cosmos}/rx/PermissionCrudTest.java | 91 +- .../data/cosmos}/rx/PermissionQueryTest.java | 65 +- .../data/cosmos}/rx/ProxyHostTest.java | 46 +- .../cosmos}/rx/ReadFeedCollectionsTest.java | 32 +- .../cosmos}/rx/ReadFeedDatabasesTest.java | 26 +- .../cosmos}/rx/ReadFeedDocumentsTest.java | 50 +- .../rx/ReadFeedExceptionHandlingTest.java | 16 +- .../data/cosmos}/rx/ReadFeedOffersTest.java | 36 +- .../cosmos}/rx/ReadFeedPermissionsTest.java | 39 +- .../data/cosmos}/rx/ReadFeedPkrTests.java | 18 +- .../rx/ReadFeedStoredProceduresTest.java | 28 +- .../data/cosmos}/rx/ReadFeedTriggersTest.java | 36 +- .../data/cosmos}/rx/ReadFeedUdfsTest.java | 34 +- .../data/cosmos}/rx/ReadFeedUsersTest.java | 28 +- .../data/cosmos}/rx/ResourceTokenTest.java | 209 ++--- .../cosmos}/rx/SimpleSerializationTest.java | 8 +- .../rx/SinglePartitionDocumentQueryTest.java | 176 ++-- .../SinglePartitionReadFeedDocumentsTest.java | 36 +- .../cosmos}/rx/StoredProcedureCrudTest.java | 40 +- .../cosmos}/rx/StoredProcedureQueryTest.java | 56 +- .../rx/StoredProcedureUpsertReplaceTest.java | 52 +- .../data/cosmos}/rx/TestSuiteBase.java | 329 ++++---- .../data/cosmos}/rx/TokenResolverTest.java | 200 ++--- .../data/cosmos}/rx/TopQueryTests.java | 90 +- .../data/cosmos}/rx/TriggerCrudTest.java | 62 +- .../data/cosmos}/rx/TriggerQueryTest.java | 52 +- .../cosmos}/rx/TriggerUpsertReplaceTest.java | 46 +- .../data/cosmos}/rx/UniqueIndexTest.java | 144 ++-- .../data/cosmos}/rx/UserCrudTest.java | 50 +- .../rx/UserDefinedFunctionCrudTest.java | 40 +- .../rx/UserDefinedFunctionQueryTest.java | 52 +- .../UserDefinedFunctionUpsertReplaceTest.java | 40 +- .../data/cosmos}/rx/UserQueryTest.java | 36 +- .../rx/VeryLargeDocumentQueryTest.java | 36 +- .../rx/proxy/HttpProxyChannelInitializer.java | 2 +- .../rx/proxy/HttpProxyClientHandler.java | 2 +- .../rx/proxy/HttpProxyClientHeader.java | 2 +- .../rx/proxy/HttpProxyRemoteHandler.java | 2 +- .../cosmos}/rx/proxy/HttpProxyServer.java | 2 +- sdk/src/test/resources/emulator-testng.xml | 2 +- sdk/src/test/resources/fast-testng.xml | 2 +- sdk/src/test/resources/long-testng.xml | 2 +- 658 files changed, 9612 insertions(+), 10679 deletions(-) rename benchmark/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/AsyncBenchmark.java (91%) rename benchmark/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/AsyncMixedBenchmark.java (85%) rename benchmark/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/AsyncQueryBenchmark.java (81%) rename benchmark/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/AsyncQuerySinglePartitionMultiple.java (85%) rename benchmark/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/AsyncReadBenchmark.java (88%) rename benchmark/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/AsyncWriteBenchmark.java (92%) rename benchmark/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/Configuration.java (94%) rename benchmark/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/DocDBUtils.java (77%) rename benchmark/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/Main.java (96%) rename benchmark/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/ReadMyWriteWorkflow.java (93%) rename benchmark/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/QueryBuilderTest.java (78%) rename benchmark/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/ReadMyWritesConsistencyTest.java (88%) rename benchmark/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/Utils.java (85%) rename benchmark/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/benchmark/WorkflowTest.java (81%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/BridgeUtils.java (87%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ConfigsBuilder.java (90%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/DatabaseForTest.java (89%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/RetryAnalyzer.java (95%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/HttpClientUnderTestWrapper.java (97%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreResponseBuilder.java (96%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/DocumentServiceRequestContextValidator.java (89%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/DocumentServiceRequestValidator.java (94%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/FailureValidator.java (76%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/FeedResponseListValidator.java (89%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/FeedResponseValidator.java (82%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ResourceResponseValidator.java (88%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ResourceValidator.java (96%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/TestConfigurations.java (96%) rename commons-test-utils/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/Utils.java (92%) rename commons-test-utils/src/main/tests/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ConfigsBuilderTest.java (91%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/AccessCondition.java (86%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/AccessConditionType.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Attachment.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/BridgeInternal.java (64%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ChangeFeedOptions.java (73%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ClientSideRequestStatistics.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/CommonsBridgeInternal.java (86%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/CompositePath.java (84%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/CompositePathSortOrder.java (90%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Conflict.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ConflictResolutionMode.java (74%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ConflictResolutionPolicy.java (76%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ConnectionMode.java (89%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ConnectionPolicy.java (81%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ConsistencyLevel.java (78%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ConsistencyPolicy.java (85%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/DocumentClientException.java => azure/data/cosmos/CosmosClientException.java} (73%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosContainerRequestOptions.java (93%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosContainerSettings.java (85%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosDatabaseRequestOptions.java (94%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosDatabaseSettings.java (92%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosFeedResponse.java (90%) rename commons/src/main/java/com/{microsoft/azure/cosmos/CosmosItemSettings.java => azure/data/cosmos/CosmosItemProperties.java} (70%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosItemRequestOptions.java (79%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosRequestOptions.java (91%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosResource.java (73%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/CosmosResourceType.java (97%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosResponse.java (74%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosStoredProcedureRequestOptions.java (82%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosStoredProcedureSettings.java (68%) create mode 100644 commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosUserDefinedFunctionSettings.java (76%) rename commons/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosUserSettings.java (80%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/DataType.java (93%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Database.java (92%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/DatabaseAccount.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/DatabaseAccountLocation.java (94%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Document.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/DocumentCollection.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Error.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ExcludedPath.java (91%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/FeedOptions.java (67%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/FeedOptionsBase.java (84%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/FeedResponse.java (78%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/HashIndex.java (79%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/IncludedPath.java (85%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Index.java (86%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/IndexKind.java (90%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/IndexingDirective.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/IndexingMode.java (93%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/IndexingPolicy.java (80%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/JsonSerializable.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/MediaOptions.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/MediaReadMode.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/MediaResponse.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Offer.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/PartitionKey.java (85%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/PartitionKeyDefinition.java (88%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/PartitionKeyDefinitionVersion.java (94%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/PartitionKeyRange.java (92%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/PartitionKind.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Permission.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/PermissionMode.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/QueryMetrics.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/QueryMetricsConstants.java (99%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/QueryMetricsUtils.java (99%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/QueryPreparationTimes.java (99%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/RangeIndex.java (78%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ReplicationPolicy.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/RequestOptions.java (99%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Resource.java (79%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ResourceResponse.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/RetryOptions.java (92%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/RuntimeExecutionTimes.java (99%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/SerializationFormattingPolicy.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/SpatialIndex.java (79%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/SpatialSpec.java (89%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/SpatialType.java (94%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/SqlParameter.java (89%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/SqlParameterCollection.java (99%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/SqlQuerySpec.java (90%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/StoredProcedure.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/StoredProcedureResponse.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/TokenResolver.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Trigger.java (86%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/TriggerOperation.java (86%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/TriggerType.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/Undefined.java (94%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/UniqueKey.java (93%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/UniqueKeyPolicy.java (92%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/User.java (93%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/UserDefinedFunction.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/Address.java (94%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/AddressInformation.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/GoneException.java (89%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/HttpUtils.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/Protocol.java (91%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/RequestTimeoutException.java (88%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreResponse.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreResult.java (81%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/TimeoutHelper.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/WFConstants.java (99%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/AuthorizationTokenType.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/BadRequestException.java (88%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/Bytes.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/Configs.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/Constants.java (99%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/DocumentServiceRequestContext.java (88%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/Exceptions.java (74%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/HttpClientFactory.java (85%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/HttpConstants.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/ISessionToken.java (88%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/Integers.java (94%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/InternalConstants.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/InternalServerErrorException.java (90%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/JavaStreamUtils.java (91%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/LifeCycleUtils.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/Lists.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/Longs.java (93%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/MutableVolatile.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/OperationType.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/PathInfo.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/PathParser.java (94%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/Paths.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/PathsHelper.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/Quadruple.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/QueryCompatibilityMode.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RMResources.java (91%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/RequestChargeTracker.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/ResourceId.java (99%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/ResourceTokenAuthorizationHelper.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/ResourceType.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/RuntimeConstants.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RxDocumentServiceRequest.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RxDocumentServiceResponse.java (87%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/Strings.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/Utils.java (64%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/metrics/ClientSideMetrics.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/metrics/FetchExecutionRange.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/metrics/FetchExecutionRangeAccumulator.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/metrics/QueryMetricsTextWriter.java (99%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/metrics/QueryMetricsWriter.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/metrics/SchedulingStopwatch.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/metrics/SchedulingTimeSpan.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/metrics/TextTable.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/BoolPartitionKeyComponent.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/IPartitionKeyComponent.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/InfinityPartitionKeyComponent.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/MaxNumberPartitionKeyComponent.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/MaxStringPartitionKeyComponent.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/MinNumberPartitionKeyComponent.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/MinStringPartitionKeyComponent.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/NullPartitionKeyComponent.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/NumberPartitionKeyComponent.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/PartitionKeyAndResourceTokenPair.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/PartitionKeyComponentType.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/PartitionKeyInternal.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/PartitionKeyRangeIdentity.java (98%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/Range.java (97%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/StringPartitionKeyComponent.java (95%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/UndefinedPartitionKeyComponent.java (96%) rename commons/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/package-info.java (97%) delete mode 100644 commons/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java delete mode 100644 commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Utils.java rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ConflictTests.java (87%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ConnectionPolicyTest.java (82%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb/DocumentClientExceptionTest.java => azure/data/cosmos/CosmosClientExceptionTest.java} (53%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/DocumentCollectionTests.java (74%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/DocumentTests.java (91%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/IncludedPathTest.java (80%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/JsonSerializableTests.java (91%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/PermissionTest.java (91%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ResourceIdTests.java (98%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/HttpUtilsTest.java (95%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreResponseTest.java (97%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/PathsHelperTest.java (97%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/RxDocumentServiceRequestTest.java (99%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/TimeTokenTest.java (97%) rename commons/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/StringPartitionKeyComponentTest.java (93%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/AddressResolver.java (88%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/AddressSelector.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/BarrierRequestHelper.java (88%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ConflictException.java (88%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ConsistencyReader.java (87%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ConsistencyWriter.java (92%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/CustomHeaders.java (95%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ErrorUtils.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ForbiddenException.java (87%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/GatewayAddressCache.java (92%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/GatewayServiceConfigurationReader.java (90%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/GoneAndRetryWithRetryPolicy.java (88%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/HttpClientUtils.java (82%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/HttpTransportClient.java (95%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/IAddressCache.java (90%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/IAddressResolver.java (90%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/IStoreClient.java (88%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/LockedException.java (87%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/MethodNotAllowedException.java (87%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/PartitionKeyRangeGoneException.java (81%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/PreconditionFailedException.java (87%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/QueryRequestPerformanceActivity.java (95%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/QuorumReader.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ReadMode.java (94%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ReplicatedResourceClient.java (90%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/RequestEntityTooLargeException.java (87%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/RequestHelper.java (80%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/RequestRateTooLargeException.java (87%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ResourceOperation.java (88%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ResponseUtils.java (92%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/RetryWithException.java (85%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/RntbdTransportClient.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ServerProperties.java (95%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ServerStoreModel.java (81%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ServiceConfig.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ServiceUnavailableException.java (87%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreClient.java (83%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreClientFactory.java (89%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreReader.java (91%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/TransportClient.java (92%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/TransportException.java (92%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/UnauthorizedException.java (87%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdClientChannelInitializer.java (92%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdConstants.java (99%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdContext.java (94%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdContextDecoder.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdContextNegotiator.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdContextRequest.java (88%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdContextRequestDecoder.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdContextRequestEncoder.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdFramer.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdObjectMapper.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdRequest.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdRequestArgs.java (95%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdRequestDecoder.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdRequestEncoder.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdRequestFrame.java (95%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdRequestFramer.java (95%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdRequestHeaders.java (94%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdRequestManager.java (91%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdResponse.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdResponseDecoder.java (97%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdResponseHeaders.java (98%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdResponseStatus.java (98%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdToken.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdTokenStream.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdTokenType.java (99%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/rntbd/RntbdUUID.java (98%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/ContentSerializationFormat.java (92%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/EnumerationDirection.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/FanoutOperationState.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/MigrateCollectionDirective.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/ReadFeedKeyType.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/RemoteStorageType.java (96%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/Int128.java (98%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/MurmurHash3_128.java (98%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/MurmurHash3_32.java (98%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/PartitionKeyInternalHelper.java (93%) rename direct-impl/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/UInt128.java (95%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/PartitionKeyHashingTests.java (81%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/AddressResolverTest.java (86%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/AddressSelectorTest.java (86%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/AddressSelectorWrapper.java (98%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ConsistencyReaderTest.java (90%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ConsistencyReaderUnderTest.java (93%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ConsistencyWriterTest.java (89%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/EndpointMock.java (98%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ExceptionBuilder.java (73%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/Function1WithCheckedException.java (95%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/Function2WithCheckedException.java (95%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/GatewayServiceConfiguratorReaderMock.java (94%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/GoneAndRetryWithRetryPolicyTest.java (89%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/HttpClientMockWrapper.java (99%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/HttpTransportClientTest.java (97%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/MultiStoreResultValidator.java (95%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/MurmurHash3_32Test.java (97%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/PartitionKeyInternalTest.java (96%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/PartitionKeyTest.java (88%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/QuorumReaderTest.java (97%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ReplicaAddressFactory.java (97%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java (89%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/ReplicatedResourceClientTest.java (87%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/RntbdTransportClientTest.java (94%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreReaderDotNetTest.java (95%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreReaderTest.java (91%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreReaderUnderTest.java (94%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreResponseValidator.java (97%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/StoreResultValidator.java (95%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/TimeoutHelperTest.java (97%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/TransportClientWrapper.java (97%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/WebExceptionUtilityTest.java (98%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RetryUtilsTest.java (92%) rename direct-impl/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/PartitionKeyInternalUtils.java (96%) rename examples/src/main/java/com/{microsoft/azure => azure/data}/cosmos/examples/AccountSettings.java (96%) rename examples/src/main/java/com/{microsoft/azure => azure/data}/cosmos/examples/BasicDemo.java (75%) rename examples/src/main/java/com/{microsoft/azure => azure/data}/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java (80%) rename examples/src/main/java/com/{microsoft/azure => azure/data}/cosmos/examples/ChangeFeed/SampleConfigurations.java (95%) rename examples/src/main/java/com/{microsoft/azure => azure/data}/cosmos/examples/ChangeFeed/SampleObserverImpl.java (78%) rename examples/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/multimaster/ConfigurationManager.java (95%) rename examples/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/multimaster/Helpers.java (75%) rename examples/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/multimaster/samples/ConflictWorker.java (86%) rename examples/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/multimaster/samples/Main.java (94%) rename examples/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/multimaster/samples/MultiMasterScenario.java (93%) rename examples/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/multimaster/samples/Worker.java (80%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/CollectionCRUDAsyncAPITest.java (86%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/ConflictAPITest.java (79%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/DatabaseCRUDAsyncAPITest.java (87%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/DocumentCRUDAsyncAPITest.java (87%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/DocumentQueryAsyncAPITest.java (85%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/InMemoryGroupbyTest.java (81%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/OfferCRUDAsyncAPITest.java (78%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/StoredProcedureAsyncAPITest.java (84%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/TestConfigurations.java (95%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/TokenResolverTest.java (77%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/UniqueIndexAsyncAPITest.java (75%) rename examples/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/examples/Utils.java (82%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/DatabaseAccountManagerInternal.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/ISessionContainer.java (96%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/WebExceptionUtility.java (96%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/AuthorizationTokenProvider.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/BackoffRetryUtility.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/BaseAuthorizationTokenProvider.java (98%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/BaseDatabaseAccountConfigurationProvider.java (94%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ClearingSessionContainerClientRetryPolicy.java (92%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ClientRetryPolicy.java (93%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ConnectionPoolExhaustedRetry.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/DatabaseAccountConfigurationProvider.java (93%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/GlobalEndpointManager.java (93%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/IAuthorizationTokenProvider.java (93%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ICollectionRoutingMapCache.java (93%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/IDocumentClientRetryPolicy.java (98%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/IRetryPolicy.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/IRetryPolicyFactory.java (96%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/IRoutingMapProvider.java (93%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/InvalidPartitionException.java (84%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/InvalidPartitionExceptionRetryPolicy.java (86%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/NotFoundException.java (89%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ObservableHelper.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/PartitionIsMigratingException.java (85%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/PartitionKeyMismatchRetryPolicy.java (87%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/PartitionKeyRangeGoneRetryPolicy.java (83%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/PartitionKeyRangeIsSplittingException.java (85%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RenameCollectionAwareClientRetryPolicy.java (90%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ReplicatedResourceClientUtils.java (94%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ResetSessionTokenRetryPolicyFactory.java (91%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ResourceThrottleRetryPolicy.java (93%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RetryPolicy.java (87%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RetryUtils.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RxGatewayStoreModel.java (91%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RxStoreModel.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/SessionContainer.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/SessionTokenHelper.java (92%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/UserAgentContainer.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/VectorSessionToken.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/WebExceptionRetryPolicy.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/caches/AsyncCache.java (98%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/caches/AsyncLazy.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/caches/IEqualityComparer.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/caches/IPartitionKeyRangeCache.java (84%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/caches/RxClientCollectionCache.java (80%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/caches/RxCollectionCache.java (90%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/AggregateDocumentQueryExecutionContext.java (79%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/CompositeContinuationToken.java (94%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/DefaultDocumentQueryExecutionContext.java (78%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/DocumentProducer.java (82%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/DocumentQueryExecutionContextBase.java (81%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/DocumentQueryExecutionContextFactory.java (81%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/ExceptionHelper.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/Fetcher.java (88%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/IDocumentQueryClient.java (83%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/IDocumentQueryExecutionComponent.java (90%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/IDocumentQueryExecutionContext.java (90%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/ItemComparator.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/ItemType.java (96%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/ItemTypeHelper.java (94%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/OrderByContinuationToken.java (96%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/OrderByDocumentProducer.java (84%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/OrderByDocumentQueryExecutionContext.java (90%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/OrderByUtils.java (89%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/Paginator.java (92%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/ParallelDocumentQueryExecutionContext.java (88%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/ParallelDocumentQueryExecutionContextBase.java (87%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/ParallelQueryConfig.java (96%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/PartitionedQueryExecutionInfo.java (92%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/PartitionedQueryExecutionInfoInternal.java (90%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/PipelinedDocumentQueryExecutionContext.java (87%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/ProxyDocumentQueryExecutionContext.java (85%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/QueryInfo.java (94%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/QueryItem.java (91%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/SortOrder.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/TakeContinuationToken.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/TopDocumentQueryExecutionContext.java (82%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/aggregation/AggregateOperator.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/aggregation/Aggregator.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/aggregation/AverageAggregator.java (93%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/aggregation/CountAggregator.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/aggregation/MaxAggregator.java (90%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/aggregation/MinAggregator.java (90%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/aggregation/SumAggregator.java (93%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/orderbyquery/OrderByRowResult.java (91%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/query/orderbyquery/OrderbyRowComparer.java (92%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/CaseInsensitiveHashMap.java (98%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/CollectionRoutingMap.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/IServerIdentity.java (95%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/InMemoryCollectionRoutingMap.java (96%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/LocationCache.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/routing/LocationHelper.java (97%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/RoutingMapProvider.java (93%) rename gateway/src/main/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/RoutingMapProviderHelper.java (97%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/GatewayTestUtils.java (97%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ClientRetryPolicyTest.java (96%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ConfigsTests.java (92%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/LocationHelperTest.java (84%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RenameCollectionAwareClientRetryPolicyTest.java (89%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RxGatewayStoreModelTest.java (87%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/SessionContainerTest.java (98%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/SessionTokenTest.java (98%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ShouldRetryValidator.java (97%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/caches/AsyncCacheTest.java (98%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/InMemoryCollectionRoutingMapTest.java (94%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/LocationCacheTest.java (95%) rename gateway/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/internal/routing/RoutingMapProviderHelperTest.java (97%) rename sdk/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/AsyncDocumentClient.java (86%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/ChangeFeedObserver.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/ChangeFeedObserverCloseReason.java (98%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/ChangeFeedObserverContext.java (93%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/ChangeFeedObserverFactory.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/ChangeFeedProcessor.java (92%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/ChangeFeedProcessorOptions.java (81%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosClient.java (88%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosClientBuilder.java (92%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosContainer.java (91%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosContainerResponse.java (66%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosDatabase.java (90%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosDatabaseResponse.java (78%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosItem.java (93%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosItemResponse.java (68%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosPermission.java (95%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosPermissionResponse.java (83%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosPermissionSettings.java (89%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosPermissionsRequestOptions.java (94%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosStoredProcedure.java (94%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosStoredProcedureResponse.java (78%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosTrigger.java (94%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosTriggerResponse.java (85%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosUser.java (87%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosUserDefinedFunction.java (93%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosUserDefinedFunctionResponse.java (80%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosUserResponse.java (52%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/CosmosUserSettings.java (80%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/Bootstrapper.java (96%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/CancellationToken.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/CancellationTokenSource.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/ChangeFeedContextClient.java (83%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/CheckpointFrequency.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/ContainerConnectionInfo.java (95%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/HealthMonitor.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/HealthMonitoringRecord.java (98%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/Lease.java (86%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/LeaseCheckpointer.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/LeaseContainer.java (96%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/LeaseManager.java (91%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/LeaseRenewer.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/LeaseStore.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/LeaseStoreManager.java (94%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/LeaseStoreManagerSettings.java (95%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/PartitionCheckpointer.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/PartitionController.java (95%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/PartitionLoadBalancer.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/PartitionLoadBalancingStrategy.java (87%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/PartitionManager.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/PartitionProcessor.java (90%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/PartitionProcessorFactory.java (94%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/PartitionSupervisor.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/PartitionSupervisorFactory.java (96%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/PartitionSynchronizer.java (93%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/ProcessorSettings.java (88%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/RemainingPartitionWork.java (96%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/RemainingWorkEstimator.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/RequestOptionsFactory.java (87%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/ServiceItemLease.java (92%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/ServiceItemLeaseUpdater.java (87%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/exceptions/LeaseLostException.java (96%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/exceptions/ObserverException.java (96%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/exceptions/PartitionException.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/exceptions/PartitionNotFoundException.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/exceptions/PartitionSplitException.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/exceptions/TaskCancelledException.java (96%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/AutoCheckpointer.java (88%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/BootstrapperImpl.java (94%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java (79%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/ChangeFeedHelper.java (87%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java (81%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java (84%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java (87%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/CheckpointerObserverFactory.java (91%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/Constants.java (99%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/DocumentServiceLeaseStore.java (67%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java (70%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java (97%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/ExceptionClassifier.java (64%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java (85%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/LeaseRenewerImpl.java (92%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/LeaseStoreManagerImpl.java (84%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java (86%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/PartitionCheckpointerImpl.java (90%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/PartitionControllerImpl.java (88%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java (91%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/PartitionManagerImpl.java (87%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java (76%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/PartitionProcessorImpl.java (66%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java (80%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/PartitionSupervisorImpl.java (86%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/PartitionSynchronizerImpl.java (89%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java (76%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java (94%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java (90%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/StatusCodeErrorType.java (96%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/TraceHealthMonitor.java (90%) rename sdk/src/main/java/com/{microsoft/azure => azure/data}/cosmos/changefeed/internal/WorkerTask.java (96%) rename sdk/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ChangeFeedQueryImpl.java (70%) rename sdk/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RxDocumentClientImpl.java (84%) rename sdk/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/caches/RxPartitionKeyRangeCache.java (79%) rename sdk/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/directconnectivity/GlobalAddressResolver.java (79%) rename sdk/src/main/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/package-info.java (96%) rename sdk/src/test/java/com/{microsoft/azure => azure/data}/cosmos/ClientUnderTestBuilder.java (92%) rename sdk/src/test/java/com/{microsoft/azure => azure/data}/cosmos/CosmosBridgeInternal.java (69%) rename sdk/src/test/java/com/{microsoft/azure => azure/data}/cosmos/CosmosContainerCrudTest.java (89%) rename sdk/src/test/java/com/{microsoft/azure => azure/data}/cosmos/CosmosDatabaseCrudTest.java (97%) rename sdk/src/test/java/com/{microsoft/azure => azure/data}/cosmos/CosmosDatabaseForTest.java (83%) rename sdk/src/test/java/com/{microsoft/azure => azure/data}/cosmos/CosmosItemCrudTest.java (89%) rename sdk/src/test/java/com/{microsoft/azure => azure/data}/cosmos/CosmosPartitionKeyTests.java (80%) rename sdk/src/test/java/com/{microsoft/azure => azure/data}/cosmos/CosmosResponseValidator.java (77%) rename sdk/src/test/java/com/{microsoft/azure => azure/data}/cosmos/CosmosTestSuiteBase.java (86%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/SpyClientBuilder.java (94%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/AddressValidator.java (93%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/BarrierRequestHelperTest.java (91%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/DCDocumentCrudTest.java (82%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/GatewayAddressCacheTest.java (94%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/GatewayServiceConfigurationReaderTest.java (91%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/internal => azure/data/cosmos}/directconnectivity/PartitionReplicasAddressesValidator.java (97%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ConnectionPoolExhaustedRetryTest.java (94%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ConsistencyTests1.java (79%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ConsistencyTests2.java (76%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ConsistencyTestsBase.java (78%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/DocumentQuerySpyWireContentTest.java (82%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/NetworkFailureTest.java (88%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/ParallelAsync.java (97%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RetryCreateDocumentTest.java (82%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RetryThrottleTest.java (82%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/RxDocumentClientUnderTest.java (90%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/SessionTest.java (85%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/SpyClientUnderTestFactory.java (95%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/StoreHeaderTests.java (82%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/TestSuiteBase.java (80%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/directconnectivity/GlobalAddressResolverTest.java (82%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/directconnectivity/ReflectionUtils.java (87%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/DocumentProducerTest.java (92%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/FeedResponseBuilder.java (89%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb/rx => azure/data/cosmos}/internal/query/FetcherTest.java (87%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/AggregateQueryTests.java (85%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/BackPressureCrossPartitionTest.java (77%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/BackPressureTest.java (78%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ChangeFeedTest.java (74%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/CollectionCrudTest.java (71%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/CollectionQueryTest.java (84%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/DatabaseCrudTest.java (88%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/DatabaseQueryTest.java (84%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/DocumentClientResourceLeakTest.java (85%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/DocumentCrudTest.java (77%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/LogLevelTest.java (80%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/MultiMasterConflictResolutionTest.java (61%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/MultiOrderByQueryTests.java (75%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/OfferQueryTest.java (84%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/OfferReadReplaceTest.java (86%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/OrderbyDocumentQueryTest.java (72%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ParallelDocumentQueryTest.java (68%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ParsingEnvTest.java (79%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/PermissionCrudTest.java (73%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/PermissionQueryTest.java (79%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ProxyHostTest.java (83%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedCollectionsTest.java (81%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedDatabasesTest.java (84%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedDocumentsTest.java (76%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedExceptionHandlingTest.java (89%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedOffersTest.java (81%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedPermissionsTest.java (81%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedPkrTests.java (83%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedStoredProceduresTest.java (83%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedTriggersTest.java (79%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedUdfsTest.java (82%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ReadFeedUsersTest.java (82%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/ResourceTokenTest.java (72%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/SimpleSerializationTest.java (95%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/SinglePartitionDocumentQueryTest.java (62%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/SinglePartitionReadFeedDocumentsTest.java (75%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/StoredProcedureCrudTest.java (81%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/StoredProcedureQueryTest.java (81%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/StoredProcedureUpsertReplaceTest.java (79%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/TestSuiteBase.java (80%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/TokenResolverTest.java (81%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/TopQueryTests.java (68%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/TriggerCrudTest.java (70%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/TriggerQueryTest.java (78%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/TriggerUpsertReplaceTest.java (71%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/UniqueIndexTest.java (56%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/UserCrudTest.java (83%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/UserDefinedFunctionCrudTest.java (81%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/UserDefinedFunctionQueryTest.java (80%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/UserDefinedFunctionUpsertReplaceTest.java (76%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/UserQueryTest.java (84%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/VeryLargeDocumentQueryTest.java (82%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/proxy/HttpProxyChannelInitializer.java (97%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/proxy/HttpProxyClientHandler.java (98%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/proxy/HttpProxyClientHeader.java (98%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/proxy/HttpProxyRemoteHandler.java (98%) rename sdk/src/test/java/com/{microsoft/azure/cosmosdb => azure/data/cosmos}/rx/proxy/HttpProxyServer.java (98%) diff --git a/README.md b/README.md index 39d7e07f8a756..b6ec762cc2cd3 100644 --- a/README.md +++ b/README.md @@ -71,8 +71,8 @@ The SDK provide Reactive Extension Observable based async API. You can read more Code Sample for creating a Document: ```java -import com.microsoft.azure.cosmosdb.rx.*; -import com.microsoft.azure.cosmosdb.*; +import com.azure.data.cosmos.rx.*; +import com.azure.data.cosmos.*; ConnectionPolicy policy = new ConnectionPolicy(); policy.setConnectionMode(ConnectionMode.Direct); diff --git a/benchmark/pom.xml b/benchmark/pom.xml index fdcae64c6558e..0b482581f1873 100644 --- a/benchmark/pom.xml +++ b/benchmark/pom.xml @@ -49,7 +49,7 @@ exec-maven-plugin 1.2.1 - com.microsoft.azure.cosmosdb.benchmark.Main + com.azure.data.cosmos.benchmark.Main @@ -61,7 +61,7 @@ - com.microsoft.azure.cosmosdb.benchmark.Main + com.azure.data.cosmos.benchmark.Main diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java similarity index 91% rename from benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java rename to benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java index 6905b29cd27be..ade143a0eb03d 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.benchmark; +package com.azure.data.cosmos.benchmark; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.Meter; @@ -34,12 +34,12 @@ import com.codahale.metrics.jvm.CachedThreadStatesGaugeSet; import com.codahale.metrics.jvm.GarbageCollectorMetricSet; import com.codahale.metrics.jvm.MemoryUsageGaugeSet; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.benchmark.Configuration.Operation; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.benchmark.Configuration.Operation; +import com.azure.data.cosmos.AsyncDocumentClient; import org.apache.commons.lang3.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -83,9 +83,9 @@ abstract class AsyncBenchmark { logger = LoggerFactory.getLogger(this.getClass()); Database database = DocDBUtils.getDatabase(client, cfg.getDatabaseId()); - collection = DocDBUtils.getCollection(client, database.getSelfLink(), cfg.getCollectionId()); - nameCollectionLink = String.format("dbs/%s/colls/%s", database.getId(), collection.getId()); - partitionKey = collection.getPartitionKey().getPaths().iterator().next().split("/")[1]; + collection = DocDBUtils.getCollection(client, database.selfLink(), cfg.getCollectionId()); + nameCollectionLink = String.format("dbs/%s/colls/%s", database.id(), collection.id()); + partitionKey = collection.getPartitionKey().paths().iterator().next().split("/")[1]; concurrencyControlSemaphore = new Semaphore(cfg.getConcurrency()); configuration = cfg; @@ -98,14 +98,14 @@ abstract class AsyncBenchmark { for (int i = 0; i < cfg.getNumberOfPreCreatedDocuments(); i++) { String uuid = UUID.randomUUID().toString(); Document newDoc = new Document(); - newDoc.setId(uuid); + newDoc.id(uuid); newDoc.set(partitionKey, uuid); newDoc.set("dataField1", dataFieldValue); newDoc.set("dataField2", dataFieldValue); newDoc.set("dataField3", dataFieldValue); newDoc.set("dataField4", dataFieldValue); newDoc.set("dataField5", dataFieldValue); - Observable obs = client.createDocument(collection.getSelfLink(), newDoc, null, false) + Observable obs = client.createDocument(collection.selfLink(), newDoc, null, false) .map(ResourceResponse::getResource); createDocumentObservables.add(obs); } @@ -151,15 +151,15 @@ protected String getCollectionLink() { if (configuration.isUseNameLink()) { return this.nameCollectionLink; } else { - return collection.getSelfLink(); + return collection.selfLink(); } } protected String getDocumentLink(Document doc) { if (configuration.isUseNameLink()) { - return this.nameCollectionLink + "/docs/" + doc.getId(); + return this.nameCollectionLink + "/docs/" + doc.id(); } else { - return doc.getSelfLink(); + return doc.selfLink(); } } diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncMixedBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java similarity index 85% rename from benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncMixedBenchmark.java rename to benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java index 9af6ddd21e598..df184c7ffa474 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncMixedBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.benchmark; +package com.azure.data.cosmos.benchmark; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.ResourceResponse; import org.apache.commons.lang3.RandomStringUtils; import rx.Observable; import rx.Subscriber; @@ -56,7 +56,7 @@ protected void performWorkload(Subscriber subs, long i) throws Interru String idString = uuid + i; Document newDoc = new Document(); - newDoc.setId(idString); + newDoc.id(idString); newDoc.set(partitionKey, idString); newDoc.set("dataField1", dataFieldValue); newDoc.set("dataField2", dataFieldValue); @@ -68,18 +68,18 @@ protected void performWorkload(Subscriber subs, long i) throws Interru } else if (i % 100 == 0) { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(10); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(10); + options.enableCrossPartitionQuery(true); String sqlQuery = "Select top 100 * from c order by c._ts"; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options) - .map(frp -> frp.getResults().get(0)); + .map(frp -> frp.results().get(0)); } else { int index = r.nextInt(1000); RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(docsToRead.get(index).getId())); + options.setPartitionKey(new PartitionKey(docsToRead.get(index).id())); obs = client.readDocument(getDocumentLink(docsToRead.get(index)), options).map(ResourceResponse::getResource); } diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncQueryBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java similarity index 81% rename from benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncQueryBenchmark.java rename to benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java index 73df9a4ab81d6..2974efeafeccf 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncQueryBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java @@ -21,22 +21,20 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.benchmark; +package com.azure.data.cosmos.benchmark; import java.util.Random; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.benchmark.Configuration.Operation; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.benchmark.Configuration.Operation; import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; -import javax.net.ssl.SSLException; - class AsyncQueryBenchmark extends AsyncBenchmark> { private int pageCount = 0; @@ -66,42 +64,42 @@ protected void performWorkload(Subscriber> subs, long i) if (configuration.getOperationType() == Operation.QueryCross) { int index = r.nextInt(1000); - options.setEnableCrossPartitionQuery(true); - String sqlQuery = "Select * from c where c._rid = \"" + docsToRead.get(index).getResourceId() + "\""; + options.enableCrossPartitionQuery(true); + String sqlQuery = "Select * from c where c._rid = \"" + docsToRead.get(index).resourceId() + "\""; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); } else if (configuration.getOperationType() == Operation.QuerySingle) { int index = r.nextInt(1000); String pk = docsToRead.get(index).getString("pk"); - options.setPartitionKey(new PartitionKey(pk)); + options.partitionKey(new PartitionKey(pk)); String sqlQuery = "Select * from c where c.pk = \"" + pk + "\""; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); } else if (configuration.getOperationType() == Operation.QueryParallel) { - options.setMaxItemCount(10); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(10); + options.enableCrossPartitionQuery(true); String sqlQuery = "Select * from c"; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); } else if (configuration.getOperationType() == Operation.QueryOrderby) { - options.setMaxItemCount(10); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(10); + options.enableCrossPartitionQuery(true); String sqlQuery = "Select * from c order by c._ts"; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); } else if (configuration.getOperationType() == Operation.QueryAggregate) { - options.setMaxItemCount(10); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(10); + options.enableCrossPartitionQuery(true); String sqlQuery = "Select value max(c._ts) from c"; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); } else if (configuration.getOperationType() == Operation.QueryAggregateTopOrderby) { - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); String sqlQuery = "Select top 1 value count(c) from c order by c._ts"; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); } else if (configuration.getOperationType() == Operation.QueryTopOrderby) { - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); String sqlQuery = "Select top 1000 * from c order by c._ts"; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); } else { diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncQuerySinglePartitionMultiple.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java similarity index 85% rename from benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncQuerySinglePartitionMultiple.java rename to benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java index 1d515226bea83..db2bacdd97c68 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncQuerySinglePartitionMultiple.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java @@ -21,19 +21,17 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.benchmark; +package com.azure.data.cosmos.benchmark; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; -import javax.net.ssl.SSLException; - class AsyncQuerySinglePartitionMultiple extends AsyncBenchmark> { private static final String SQL_QUERY = "Select * from c where c.pk = \"pk\""; @@ -43,8 +41,8 @@ class AsyncQuerySinglePartitionMultiple extends AsyncBenchmark> { class LatencySubscriber extends Subscriber { @@ -73,7 +71,7 @@ public void onNext(T t) { protected void performWorkload(Subscriber> subs, long i) throws InterruptedException { int index = (int) (i % docsToRead.size()); RequestOptions options = new RequestOptions(); - options.setPartitionKey(new PartitionKey(docsToRead.get(index).getId())); + options.setPartitionKey(new PartitionKey(docsToRead.get(index).id())); Observable> obs = client.readDocument(getDocumentLink(docsToRead.get(index)), options); diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncWriteBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java similarity index 92% rename from benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncWriteBenchmark.java rename to benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java index 8256e1c48cba5..bb1b7a8aa168d 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/AsyncWriteBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java @@ -21,23 +21,21 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.benchmark; +package com.azure.data.cosmos.benchmark; import java.util.UUID; import org.apache.commons.lang3.RandomStringUtils; import com.codahale.metrics.Timer; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.benchmark.Configuration.Operation; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.benchmark.Configuration.Operation; import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; -import javax.net.ssl.SSLException; - class AsyncWriteBenchmark extends AsyncBenchmark> { private final String uuid; @@ -81,7 +79,7 @@ protected void performWorkload(Subscriber> subs, long String idString = uuid + i; Document newDoc = new Document(); - newDoc.setId(idString); + newDoc.id(idString); newDoc.set(partitionKey, idString); newDoc.set("dataField1", dataFieldValue); newDoc.set("dataField2", dataFieldValue); diff --git a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java similarity index 94% rename from benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java rename to benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java index 2b1e350afcf1f..f3349fed910f8 100644 --- a/benchmark/src/main/java/com/microsoft/azure/cosmosdb/benchmark/Configuration.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.benchmark; +package com.azure.data.cosmos.benchmark; import java.time.Duration; import java.util.Arrays; @@ -34,10 +34,10 @@ import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.base.Strings; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.benchmark.Configuration.Operation.OperationTypeConverter; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.benchmark.Configuration.Operation.OperationTypeConverter; class Configuration { private final static int GRAPHITE_SERVER_DEFAULT_PORT = 2003; @@ -64,10 +64,10 @@ class Configuration { private Integer maxConnectionPoolSize = 1000; @Parameter(names = "-consistencyLevel", description = "Consistency Level", converter = ConsistencyLevelConverter.class) - private ConsistencyLevel consistencyLevel = ConsistencyLevel.Session; + private ConsistencyLevel consistencyLevel = ConsistencyLevel.SESSION; @Parameter(names = "-connectionMode", description = "Connection Mode") - private ConnectionMode connectionMode = ConnectionMode.Direct; + private ConnectionMode connectionMode = ConnectionMode.DIRECT; @Parameter(names = "-graphiteEndpoint", description = "Graphite endpoint") private String graphiteEndpoint; @@ -76,9 +76,9 @@ class Configuration { private boolean enableJvmStats; @Parameter(names = "-operation", description = "Type of Workload:\n" - + "\tReadThroughput- run a Read workload that prints only throughput *\n" + + "\tReadThroughput- run a READ workload that prints only throughput *\n" + "\tWriteThroughput - run a Write workload that prints only throughput\n" - + "\tReadLatency - run a Read workload that prints both throughput and latency *\n" + + "\tReadLatency - run a READ workload that prints both throughput and latency *\n" + "\tWriteLatency - run a Write workload that prints both throughput and latency\n" + "\tQueryCross - run a 'Select * from c where c._rid = SOME_RID' workload that prints throughput\n" + "\tQuerySingle - run a 'Select * from c where c.pk = SOME_PK' workload that prints throughput\n" @@ -97,7 +97,7 @@ class Configuration { + " If this value is not specified, the max connection pool size will be used as the concurrency level.") private Integer concurrency; - @Parameter(names = "-numberOfOperations", description = "Total Number Of Documents To Insert") + @Parameter(names = "-numberOfOperations", description = "Total NUMBER Of Documents To Insert") private int numberOfOperations = 100000; static class DurationConverter implements IStringConverter { @@ -117,7 +117,7 @@ public Duration convert(String value) { @Parameter(names = "-printingInterval", description = "Interval of time after which Metrics should be printed (seconds)") private int printingInterval = 10; - @Parameter(names = "-numberOfPreCreatedDocuments", description = "Total Number Of Documents To pre create for a read workload to use") + @Parameter(names = "-numberOfPreCreatedDocuments", description = "Total NUMBER Of Documents To pre create for a read workload to use") private int numberOfPreCreatedDocuments = 1000; @Parameter(names = {"-h", "-help", "--help"}, description = "Help", help = true) @@ -155,7 +155,7 @@ static class OperationTypeConverter implements IStringConverter { /* * (non-Javadoc) * - * @see com.beust.jcommander.IStringConverter#convert(java.lang.String) + * @see com.beust.jcommander.IStringConverter#convert(java.lang.STRING) */ @Override public Operation convert(String value) { @@ -183,7 +183,7 @@ static class ConsistencyLevelConverter implements IStringConverter writeDocument(Integer i) { String idString = Utils.randomUUID().toString(); String randomVal = Utils.randomUUID().toString(); Document document = new Document(); - document.setId(idString); + document.id(idString); document.set(partitionKey, idString); document.set(QUERY_FIELD_NAME, randomVal); document.set("dataField1", randomVal); @@ -237,11 +236,11 @@ private SqlQuerySpec generateRandomQuery() { */ private Observable xPartitionQuery(SqlQuerySpec query) { FeedOptions options = new FeedOptions(); - options.setMaxDegreeOfParallelism(-1); - options.setEnableCrossPartitionQuery(true); + options.maxDegreeOfParallelism(-1); + options.enableCrossPartitionQuery(true); return client.queryDocuments(getCollectionLink(), query, options) - .flatMap(p -> Observable.from(p.getResults())); + .flatMap(p -> Observable.from(p.results())); } /** @@ -253,13 +252,13 @@ private Observable xPartitionQuery(SqlQuerySpec query) { */ private Observable singlePartitionQuery(Document d) { FeedOptions options = new FeedOptions(); - options.setPartitionKey(new PartitionKey(d.get(partitionKey))); + options.partitionKey(new PartitionKey(d.get(partitionKey))); SqlQuerySpec sqlQuerySpec = new SqlQuerySpec(String.format("Select top 100 * from c where c.%s = '%s'", QUERY_FIELD_NAME, d.getString(QUERY_FIELD_NAME))); return client.queryDocuments(getCollectionLink(), sqlQuerySpec, options) - .flatMap(p -> Observable.from(p.getResults())); + .flatMap(p -> Observable.from(p.results())); } /** @@ -368,7 +367,7 @@ static InWhereClause asInWhereClause(String fieldName, List documentLi StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(fieldName); stringBuilder.append(" IN ("); - List params = parameters.stream().map(SqlParameter::getName).collect(Collectors.toList()); + List params = parameters.stream().map(SqlParameter::name).collect(Collectors.toList()); stringBuilder.append(String.join(", ", params)); stringBuilder.append(")"); diff --git a/benchmark/src/main/resources/log4j.properties b/benchmark/src/main/resources/log4j.properties index 92751a4192017..34cead5b2f2ae 100644 --- a/benchmark/src/main/resources/log4j.properties +++ b/benchmark/src/main/resources/log4j.properties @@ -3,7 +3,7 @@ # Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=INFO, A1 -log4j.category.com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd=WARN +log4j.category.com.azure.data.cosmos.directconnectivity.rntbd=WARN log4j.category.io.netty=INFO log4j.category.io.reactivex=INFO # A1 is set to be a ConsoleAppender. diff --git a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/QueryBuilderTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java similarity index 78% rename from benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/QueryBuilderTest.java rename to benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java index d83d5505e1d37..01b461f89360b 100644 --- a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/QueryBuilderTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java @@ -21,13 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.benchmark; +package com.azure.data.cosmos.benchmark; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.SqlParameter; +import com.azure.data.cosmos.SqlParameter; import org.testng.annotations.Test; -import static com.microsoft.azure.cosmosdb.benchmark.ReadMyWriteWorkflow.QueryBuilder.WhereClause; import static org.assertj.core.api.Assertions.assertThat; public class QueryBuilderTest { @@ -35,7 +34,7 @@ public class QueryBuilderTest { @Test(groups = {"unit"}) public void basic() { ReadMyWriteWorkflow.QueryBuilder queryBuilder = new ReadMyWriteWorkflow.QueryBuilder(); - assertThat(queryBuilder.toSqlQuerySpec().getQueryText()) + assertThat(queryBuilder.toSqlQuerySpec().queryText()) .isEqualTo("SELECT * FROM root"); } @@ -43,7 +42,7 @@ public void basic() { public void top() { ReadMyWriteWorkflow.QueryBuilder queryBuilder = new ReadMyWriteWorkflow.QueryBuilder(); queryBuilder.top(50); - assertThat(queryBuilder.toSqlQuerySpec().getQueryText()) + assertThat(queryBuilder.toSqlQuerySpec().queryText()) .isEqualTo("SELECT TOP 50 * FROM root"); } @@ -51,7 +50,7 @@ public void top() { public void orderBy() { ReadMyWriteWorkflow.QueryBuilder queryBuilder = new ReadMyWriteWorkflow.QueryBuilder(); queryBuilder.orderBy("prop"); - assertThat(queryBuilder.toSqlQuerySpec().getQueryText()) + assertThat(queryBuilder.toSqlQuerySpec().queryText()) .isEqualTo("SELECT * FROM root ORDER BY root.prop"); } @@ -61,11 +60,11 @@ public void whereInClause() { ImmutableList parameters = ImmutableList.of(new SqlParameter("@param1", 1), new SqlParameter("@param2", 2)); - queryBuilder.whereClause(new WhereClause.InWhereClause("colName", + queryBuilder.whereClause(new ReadMyWriteWorkflow.QueryBuilder.WhereClause.InWhereClause("colName", parameters)); - assertThat(queryBuilder.toSqlQuerySpec().getQueryText()) + assertThat(queryBuilder.toSqlQuerySpec().queryText()) .isEqualTo("SELECT * FROM root WHERE root.colName IN (@param1, @param2)"); - assertThat(queryBuilder.toSqlQuerySpec().getParameters()).containsExactlyElementsOf(parameters); + assertThat(queryBuilder.toSqlQuerySpec().parameters()).containsExactlyElementsOf(parameters); } @Test(groups = {"unit"}) @@ -76,10 +75,10 @@ public void topOrderByWhereClause() { ImmutableList parameters = ImmutableList.of(new SqlParameter("@param1", 1), new SqlParameter("@param2", 2)); - queryBuilder.whereClause(new WhereClause.InWhereClause("colName", + queryBuilder.whereClause(new ReadMyWriteWorkflow.QueryBuilder.WhereClause.InWhereClause("colName", parameters)); - assertThat(queryBuilder.toSqlQuerySpec().getQueryText()) + assertThat(queryBuilder.toSqlQuerySpec().queryText()) .isEqualTo("SELECT TOP 5 * FROM root WHERE root.colName IN (@param1, @param2) ORDER BY root.prop"); - assertThat(queryBuilder.toSqlQuerySpec().getParameters()).containsExactlyElementsOf(parameters); + assertThat(queryBuilder.toSqlQuerySpec().parameters()).containsExactlyElementsOf(parameters); } } diff --git a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java similarity index 88% rename from benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java rename to benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java index 8970087944837..860e500019ff9 100644 --- a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java @@ -21,20 +21,20 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.benchmark; +package com.azure.data.cosmos.benchmark; import com.beust.jcommander.JCommander; import com.google.common.base.Strings; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.Index; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +import com.azure.data.cosmos.DataType; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.IncludedPath; +import com.azure.data.cosmos.Index; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.rx.TestConfigurations; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,7 +70,7 @@ public class ReadMyWritesConsistencyTest { private final String desiredConsistency = System.getProperty("DESIRED_CONSISTENCY", StringUtils.defaultString(Strings.emptyToNull( - System.getenv().get("DESIRED_CONSISTENCY")), "Session")); + System.getenv().get("DESIRED_CONSISTENCY")), "SESSION")); private final String numberOfOperationsAsString = System.getProperty("NUMBER_OF_OPERATIONS", @@ -88,14 +88,14 @@ public void readMyWrites(boolean useNameLink) throws Exception { " -consistencyLevel %s -concurrency %d" + " -numberOfOperations %s" + " -maxRunningTimeDuration %s" + - " -operation ReadMyWrites -connectionMode Direct -numberOfPreCreatedDocuments 100 " + + " -operation ReadMyWrites -connectionMode DIRECT -numberOfPreCreatedDocuments 100 " + " -printingInterval 60"; String cmd = String.format(cmdFormat, TestConfigurations.HOST, TestConfigurations.MASTER_KEY, - database.getId(), - collection.getId(), + database.id(), + collection.id(), desiredConsistency, concurrency, numberOfOperationsAsString, @@ -142,7 +142,7 @@ public void beforeClass() { options.setOfferThroughput(initialCollectionThroughput); AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); database = Utils.createDatabaseForTest(housekeepingClient); - collection = housekeepingClient.createCollection("dbs/" + database.getId(), + collection = housekeepingClient.createCollection("dbs/" + database.id(), getCollectionDefinitionWithRangeRangeIndex(), options) .toBlocking().single().getResource(); @@ -169,26 +169,26 @@ DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); + includedPath.path("/*"); Collection indexes = new ArrayList<>(); - Index stringIndex = Index.Range(DataType.String); + Index stringIndex = Index.Range(DataType.STRING); stringIndex.set("precision", -1); indexes.add(stringIndex); - Index numberIndex = Index.Range(DataType.Number); + Index numberIndex = Index.Range(DataType.NUMBER); numberIndex.set("precision", -1); indexes.add(numberIndex); - includedPath.setIndexes(indexes); + includedPath.indexes(indexes); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setIndexingPolicy(indexingPolicy); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); collectionDefinition.setPartitionKey(partitionKeyDef); return collectionDefinition; @@ -202,8 +202,8 @@ private void scheduleScaleUp(int delayStartInSeconds, int newThroughput) { // for bulk insert and later queries. return housekeepingClient.queryOffers( String.format("SELECT * FROM r WHERE r.offerResourceId = '%s'", - collection.getResourceId()) - , null).flatMap(page -> Observable.from(page.getResults())) + collection.resourceId()) + , null).flatMap(page -> Observable.from(page.results())) .first().flatMap(offer -> { logger.info("going to scale up collection, newThroughput {}", newThroughput); offer.setThroughput(newThroughput); diff --git a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/Utils.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java similarity index 85% rename from benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/Utils.java rename to benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java index 49517fd05cb50..b96c97760a201 100644 --- a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/Utils.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.benchmark; +package com.azure.data.cosmos.benchmark; /* * The MIT License (MIT) @@ -47,25 +47,25 @@ */ -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.RetryOptions; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.RetryOptions; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.rx.TestConfigurations; import rx.Observable; public class Utils { public static AsyncDocumentClient housekeepingClient() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); RetryOptions options = new RetryOptions(); - options.setMaxRetryAttemptsOnThrottledRequests(100); - options.setMaxRetryWaitTimeInSeconds(60); - connectionPolicy.setRetryOptions(options); + options.maxRetryAttemptsOnThrottledRequests(100); + options.maxRetryWaitTimeInSeconds(60); + connectionPolicy.retryOptions(options); return new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) @@ -73,7 +73,7 @@ public static AsyncDocumentClient housekeepingClient() { } public static String getCollectionLink(Database db, DocumentCollection collection) { - return "dbs/" + db.getId() + "/colls/" + collection; + return "dbs/" + db.id() + "/colls/" + collection; } public static Database createDatabaseForTest(AsyncDocumentClient client) { @@ -88,7 +88,7 @@ public static void safeCleanDatabases(AsyncDocumentClient client) { public static void safeClean(AsyncDocumentClient client, Database database) { if (database != null) { - safeClean(client, database.getId()); + safeClean(client, database.id()); } } diff --git a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/WorkflowTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java similarity index 81% rename from benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/WorkflowTest.java rename to benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java index 6490d47bcb6d2..dab4f32b6c412 100644 --- a/benchmark/src/test/java/com/microsoft/azure/cosmosdb/benchmark/WorkflowTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java @@ -21,19 +21,19 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.benchmark; +package com.azure.data.cosmos.benchmark; import com.beust.jcommander.JCommander; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.Index; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +import com.azure.data.cosmos.DataType; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.IncludedPath; +import com.azure.data.cosmos.Index; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.rx.TestConfigurations; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -56,14 +56,14 @@ public class WorkflowTest { public void readMyWritesCLI() throws Exception { String cmdFormat = "-serviceEndpoint %s -masterKey %s" + " -databaseId %s -collectionId %s" + - " -consistencyLevel Session -concurrency 2 -numberOfOperations 123" + - " -operation ReadMyWrites -connectionMode Direct -numberOfPreCreatedDocuments 100"; + " -consistencyLevel SESSION -concurrency 2 -numberOfOperations 123" + + " -operation ReadMyWrites -connectionMode DIRECT -numberOfPreCreatedDocuments 100"; String cmd = String.format(cmdFormat, TestConfigurations.HOST, TestConfigurations.MASTER_KEY, - database.getId(), - collection.getId()); + database.id(), + collection.id()); Main.main(StringUtils.split(cmd)); } @@ -72,14 +72,14 @@ public void readMyWrites(boolean useNameLink) throws Exception { int numberOfOperations = 123; String cmdFormat = "-serviceEndpoint %s -masterKey %s" + " -databaseId %s -collectionId %s" + - " -consistencyLevel Session -concurrency 2 -numberOfOperations %s" + - " -operation ReadMyWrites -connectionMode Direct -numberOfPreCreatedDocuments 100"; + " -consistencyLevel SESSION -concurrency 2 -numberOfOperations %s" + + " -operation ReadMyWrites -connectionMode DIRECT -numberOfPreCreatedDocuments 100"; String cmd = String.format(cmdFormat, TestConfigurations.HOST, TestConfigurations.MASTER_KEY, - database.getId(), - collection.getId(), + database.id(), + collection.id(), numberOfOperations) + (useNameLink ? " -useNameLink" : ""); @@ -112,14 +112,14 @@ protected void onSuccess() { public void writeLatencyCLI() throws Exception { String cmdFormat = "-serviceEndpoint %s -masterKey %s" + " -databaseId %s -collectionId %s" + - " -consistencyLevel Session -concurrency 2 -numberOfOperations 1000" + - " -operation WriteLatency -connectionMode Direct"; + " -consistencyLevel SESSION -concurrency 2 -numberOfOperations 1000" + + " -operation WriteLatency -connectionMode DIRECT"; String cmd = String.format(cmdFormat, TestConfigurations.HOST, TestConfigurations.MASTER_KEY, - database.getId(), - collection.getId()); + database.id(), + collection.id()); Main.main(StringUtils.split(cmd)); } @@ -128,14 +128,14 @@ public void writeLatency(boolean useNameLink) throws Exception { int numberOfOperations = 123; String cmdFormat = "-serviceEndpoint %s -masterKey %s" + " -databaseId %s -collectionId %s" + - " -consistencyLevel Session -concurrency 2 -numberOfOperations %s" + - " -operation WriteLatency -connectionMode Direct"; + " -consistencyLevel SESSION -concurrency 2 -numberOfOperations %s" + + " -operation WriteLatency -connectionMode DIRECT"; String cmd = String.format(cmdFormat, TestConfigurations.HOST, TestConfigurations.MASTER_KEY, - database.getId(), - collection.getId(), + database.id(), + collection.id(), numberOfOperations) + (useNameLink ? " -useNameLink" : ""); @@ -169,14 +169,14 @@ public void writeThroughput(boolean useNameLink) throws Exception { int numberOfOperations = 123; String cmdFormat = "-serviceEndpoint %s -masterKey %s" + " -databaseId %s -collectionId %s" + - " -consistencyLevel Session -concurrency 2 -numberOfOperations %s" + - " -operation WriteThroughput -connectionMode Direct"; + " -consistencyLevel SESSION -concurrency 2 -numberOfOperations %s" + + " -operation WriteThroughput -connectionMode DIRECT"; String cmd = String.format(cmdFormat, TestConfigurations.HOST, TestConfigurations.MASTER_KEY, - database.getId(), - collection.getId(), + database.id(), + collection.id(), numberOfOperations) + (useNameLink ? " -useNameLink" : ""); @@ -210,14 +210,14 @@ public void readLatency(boolean useNameLink) throws Exception { int numberOfOperations = 123; String cmdFormat = "-serviceEndpoint %s -masterKey %s" + " -databaseId %s -collectionId %s" + - " -consistencyLevel Session -concurrency 2 -numberOfOperations %s" + - " -operation ReadLatency -connectionMode Direct"; + " -consistencyLevel SESSION -concurrency 2 -numberOfOperations %s" + + " -operation ReadLatency -connectionMode DIRECT"; String cmd = String.format(cmdFormat, TestConfigurations.HOST, TestConfigurations.MASTER_KEY, - database.getId(), - collection.getId(), + database.id(), + collection.id(), numberOfOperations) + (useNameLink ? " -useNameLink" : ""); @@ -251,14 +251,14 @@ public void readThroughput(boolean useNameLink) throws Exception { int numberOfOperations = 123; String cmdFormat = "-serviceEndpoint %s -masterKey %s" + " -databaseId %s -collectionId %s" + - " -consistencyLevel Session -concurrency 2 -numberOfOperations %s" + - " -operation ReadThroughput -connectionMode Direct"; + " -consistencyLevel SESSION -concurrency 2 -numberOfOperations %s" + + " -operation ReadThroughput -connectionMode DIRECT"; String cmd = String.format(cmdFormat, TestConfigurations.HOST, TestConfigurations.MASTER_KEY, - database.getId(), - collection.getId(), + database.id(), + collection.id(), numberOfOperations) + (useNameLink ? " -useNameLink" : ""); @@ -293,7 +293,7 @@ public void beforeClass() { options.setOfferThroughput(10000); AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); database = Utils.createDatabaseForTest(housekeepingClient); - collection = housekeepingClient.createCollection("dbs/"+ database.getId(), + collection = housekeepingClient.createCollection("dbs/"+ database.id(), getCollectionDefinitionWithRangeRangeIndex(), options) .toBlocking().single().getResource(); @@ -321,26 +321,26 @@ DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); + includedPath.path("/*"); Collection indexes = new ArrayList<>(); - Index stringIndex = Index.Range(DataType.String); + Index stringIndex = Index.Range(DataType.STRING); stringIndex.set("precision", -1); indexes.add(stringIndex); - Index numberIndex = Index.Range(DataType.Number); + Index numberIndex = Index.Range(DataType.NUMBER); numberIndex.set("precision", -1); indexes.add(numberIndex); - includedPath.setIndexes(indexes); + includedPath.indexes(indexes); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setIndexingPolicy(indexingPolicy); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); collectionDefinition.setPartitionKey(partitionKeyDef); return collectionDefinition; diff --git a/changelog/README.md b/changelog/README.md index f72d0684abc21..7f145864521b5 100644 --- a/changelog/README.md +++ b/changelog/README.md @@ -1,65 +1,75 @@ ## Changelog ### 2.4.3 -* Fixed resource leak issue on closing client + +- Fixed resource leak issue on closing client ### 2.4.2 -* Fixed bugs in continuation token support for cross partition queries + +- Fixed bugs in continuation token support for cross partition queries ### 2.4.1 -* Fixed some bugs in Direct mode. -* Improved logging in Direct mode. -* Improved connection management. + +- Fixed some bugs in Direct mode. +- Improved logging in Direct mode. +- Improved connection management. ### 2.4.0 -* Direct GA. -* Added support for QueryMetrics. -* Changed the APIs accepting java.util.Collection for which order is important to accept java.util.List instead. Now ConnectionPolicy#getPreferredLocations(), JsonSerialization, and PartitionKey(.) accept List. + +- Direct GA. +- Added support for QueryMetrics. +- Changed the APIs accepting java.util.Collection for which order is important to accept java.util.List instead. Now ConnectionPolicy#getPreferredLocations(), JsonSerialization, and PartitionKey(.) accept List. ### 2.4.0-beta1 -* Added support for Direct Https. -* Changed the APIs accepting java.util.Collection for which order is important to accept java.util.List instead. - Now ConnectionPolicy#getPreferredLocations(), JsonSerialization, and PartitionKey(.) accept List. -* Fixed a Session bug for Document query in Gateway mode. -* Upgraded dependencies (netty 0.4.20 [github #79](https://github.com/Azure/azure-cosmosdb-java/issues/79), RxJava 1.3.8). +- Added support for Direct Https. +- Changed the APIs accepting java.util.Collection for which order is important to accept java.util.List instead. + Now ConnectionPolicy#getPreferredLocations(), JsonSerialization, and PartitionKey(.) accept List. +- Fixed a Session bug for Document query in Gateway mode. +- Upgraded dependencies (netty 0.4.20 [github #79](https://github.com/Azure/azure-cosmosdb-java/issues/79), RxJava 1.3.8). ### 2.3.1 -* Fix handling very large query responses. -* Fix resource token handling when instantiating client ([github #78](https://github.com/Azure/azure-cosmosdb-java/issues/78)). -* Upgraded vulnerable dependency jackson-databind ([github #77](https://github.com/Azure/azure-cosmosdb-java/pull/77)). +- Fix handling very large query responses. +- Fix resource token handling when instantiating client ([github #78](https://github.com/Azure/azure-cosmosdb-java/issues/78)). +- Upgraded vulnerable dependency jackson-databind ([github #77](https://github.com/Azure/azure-cosmosdb-java/pull/77)). ### 2.3.0 -* Fixed a resource leak bug. -* Added support for MultiPolygon -* Added support for custom headers in RequestOptions. +- Fixed a resource leak bug. +- Added support for MultiPolygon +- Added support for custom headers in RequestOptions. ### 2.2.2 -* Fixed a packaging bug. + +- Fixed a packaging bug. ### 2.2.1 -* Fixed a NPE bug in write retry path. -* Fixed a NPE bug in endpoint management. -* Upgraded vulnerable dependencies ([github #68](https://github.com/Azure/azure-cosmosdb-java/issues/68)). -* Added support for Netty network logging for troubleshooting. + +- Fixed a NPE bug in write retry path. +- Fixed a NPE bug in endpoint management. +- Upgraded vulnerable dependencies ([github #68](https://github.com/Azure/azure-cosmosdb-java/issues/68)). +- Added support for Netty network logging for troubleshooting. ### 2.2.0 -* Added support for Multi-region write. + +- Added support for Multi-region write. ### 2.1.0 -* Added support for Proxy. -* Added support for resource token authorization. -* Fixed a bug in handling large partition keys ([github #63](https://github.com/Azure/azure-cosmosdb-java/issues/63)). -* Documentation improved. -* SDK restructured into more granular modules. + +- Added support for Proxy. +- Added support for resource token authorization. +- Fixed a bug in handling large partition keys ([github #63](https://github.com/Azure/azure-cosmosdb-java/issues/63)). +- Documentation improved. +- SDK restructured into more granular modules. ### 2.0.1 + - Fixed a bug for non-english locales ([github #51](https://github.com/Azure/azure-cosmosdb-java/issues/51)). - Added helper methods for Conflict resource. ### 2.0.0 + - Replaced org.json dependency by jackson due to performance reasons and licensing ([github #29](https://github.com/Azure/azure-cosmosdb-java/issues/29)). - Removed deprecated OfferV2 class. - Added accessor method to Offer class for throughput content. @@ -70,6 +80,7 @@ - JsonSerializable.toJson (SerializationFormattingPolicy.Indented) now uses two spaces for indentation. ### 1.0.2 + - Added support for Unique Index Policy. - Added support for limiting response continuation token size in feed options. - Added support for Partition Split in Cross Partition Query. @@ -82,6 +93,7 @@ - Syntax improvement ([github #41](https://github.com/Azure/azure-cosmosdb-java/issues/41)), ([github #40](https://github.com/Azure/azure-cosmosdb-java/issues/40)). ### 1.0.1 + - Added back-pressure support in query. - Added support for partition key range id in query. - Changed to allow larger continuation token in request header (bugfix github #24). @@ -92,20 +104,23 @@ - Fixed java header files for proper javadoc generation. ### 1.0.0 + - Release 1.0.0 has fully end to end support for non-blocking IO using netty library in Gateway mode. -- Dependency on ``azure-documentdb`` SDK removed. -- Artifact id changed to ``azure-cosmosdb`` from ``azure-documentdb-rx`` in 0.9.0-rc2. -- Java package name changed to ``com.microsoft.azure.cosmosdb`` from ``com.microsoft.azure.documentdb`` in 0.9.0-rc2. +- Dependency on `azure-documentdb` SDK removed. +- Artifact id changed to `azure-cosmosdb` from `azure-documentdb-rx` in 0.9.0-rc2. +- Java package name changed to `com.azure.data.cosmos` from `com.microsoft.azure.documentdb` in 0.9.0-rc2. ### 0.9.0-rc2 -- ``FeedResponsePage`` renamed to ``FeedReponse`` -- Some minor modifications to ``ConnectionPolicy`` configuration. -All time fields and methods in ConnectionPolicy suffixed with "InMillis" to be more precise of the time unit. -- ``ConnectionPolicy#setProxy()`` removed. -- ``FeedOptions#pageSize`` renamed to -``FeedOptions#maxItemCount`` + +- `FeedResponsePage` renamed to `FeedReponse` +- Some minor modifications to `ConnectionPolicy` configuration. + All time fields and methods in ConnectionPolicy suffixed with "InMillis" to be more precise of the time unit. +- `ConnectionPolicy#setProxy()` removed. +- `FeedOptions#pageSize` renamed to + `FeedOptions#maxItemCount` - Release 1.0.0 deprecates 0.9.x releases. ### 0.9.0-rc1 -- First release of ``azure-documentdb-rx`` SDK. -- CRUD Document API fully non-blocking using netty. Query async API implemented as a wrapper using blocking SDK ``azure-documentdb``. + +- First release of `azure-documentdb-rx` SDK. +- CRUD Document API fully non-blocking using netty. Query async API implemented as a wrapper using blocking SDK `azure-documentdb`. diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/BridgeUtils.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/BridgeUtils.java similarity index 87% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/BridgeUtils.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/BridgeUtils.java index f5e449b53fc92..43afebcdaa69c 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/BridgeUtils.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/BridgeUtils.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.List; @@ -31,8 +31,8 @@ public class BridgeUtils { public static DatabaseAccount createDatabaseAccount(List readLocations, - List writeLocations, - boolean useMultipleWriteLocations) { + List writeLocations, + boolean useMultipleWriteLocations) { DatabaseAccount dbAccount = new DatabaseAccount(); dbAccount.setEnableMultipleWriteLocations(useMultipleWriteLocations); @@ -55,17 +55,17 @@ public static ConflictResolutionPolicy createConflictResolutionPolicy() { } public static ConflictResolutionPolicy setMode(ConflictResolutionPolicy policy, ConflictResolutionMode mode) { - policy.setMode(mode); + policy.mode(mode); return policy; } public static ConflictResolutionPolicy setPath(ConflictResolutionPolicy policy, String path) { - policy.setConflictResolutionPath(path); + policy.conflictResolutionPath(path); return policy; } public static ConflictResolutionPolicy setStoredProc(ConflictResolutionPolicy policy, String storedProcLink) { - policy.setConflictResolutionProcedure(storedProcLink); + policy.conflictResolutionProcedure(storedProcLink); return policy; } } diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/ConfigsBuilder.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/ConfigsBuilder.java similarity index 90% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/ConfigsBuilder.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/ConfigsBuilder.java index ff8ec498a8237..7ce6c9dc8b50a 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/ConfigsBuilder.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/ConfigsBuilder.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; +import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.Configs; import org.mockito.Mockito; /** diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/DatabaseForTest.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java similarity index 89% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/DatabaseForTest.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java index 5711d2fa817e7..f8cd30f025ad9 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/DatabaseForTest.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; @@ -64,11 +64,11 @@ public static String generateId() { } private static DatabaseForTest from(Database db) { - if (db == null || db.getId() == null || db.getSelfLink() == null) { + if (db == null || db.id() == null || db.selfLink() == null) { return null; } - String id = db.getId(); + String id = db.id(); if (id == null) { return null; } @@ -91,7 +91,7 @@ private static DatabaseForTest from(Database db) { public static DatabaseForTest create(DatabaseManager client) { Database dbDef = new Database(); - dbDef.setId(generateId()); + dbDef.id(generateId()); Database db = client.createDatabase(dbDef).toBlocking().single().getResource(); DatabaseForTest dbForTest = DatabaseForTest.from(db); @@ -104,16 +104,16 @@ public static void cleanupStaleTestDatabases(DatabaseManager client) { List dbs = client.queryDatabases( new SqlQuerySpec("SELECT * FROM c WHERE STARTSWITH(c.id, @PREFIX)", new SqlParameterCollection(new SqlParameter("@PREFIX", DatabaseForTest.SHARED_DB_ID_PREFIX)))) - .flatMap(page -> Observable.from(page.getResults())).toList().toBlocking().single(); + .flatMap(page -> Observable.from(page.results())).toList().toBlocking().single(); for (Database db : dbs) { - assertThat(db.getId()).startsWith(DatabaseForTest.SHARED_DB_ID_PREFIX); + assertThat(db.id()).startsWith(DatabaseForTest.SHARED_DB_ID_PREFIX); DatabaseForTest dbForTest = DatabaseForTest.from(db); if (db != null && dbForTest.isStale()) { - logger.info("Deleting database {}", db.getId()); - client.deleteDatabase(db.getId()).toBlocking().single(); + logger.info("Deleting database {}", db.id()); + client.deleteDatabase(db.id()).toBlocking().single(); } } } diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzer.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/RetryAnalyzer.java similarity index 95% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzer.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/RetryAnalyzer.java index 36766d50c9bd4..b256707d13ebe 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/RetryAnalyzer.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/RetryAnalyzer.java @@ -22,9 +22,9 @@ */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +import com.azure.data.cosmos.rx.TestConfigurations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpClientUnderTestWrapper.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUnderTestWrapper.java similarity index 97% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpClientUnderTestWrapper.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUnderTestWrapper.java index ffb118d8d8526..4f6a30ca7e643 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpClientUnderTestWrapper.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUnderTestWrapper.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import io.netty.buffer.ByteBuf; import io.reactivex.netty.client.RxClient; diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponseBuilder.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponseBuilder.java similarity index 96% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponseBuilder.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponseBuilder.java index 5a1c1900d9203..3e9e95d0c614a 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponseBuilder.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponseBuilder.java @@ -21,10 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.azure.data.cosmos.internal.HttpConstants; import java.math.BigDecimal; import java.util.AbstractMap; diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/DocumentServiceRequestContextValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestContextValidator.java similarity index 89% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/DocumentServiceRequestContextValidator.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestContextValidator.java index 5458c36929b98..807b0da136b64 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/DocumentServiceRequestContextValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestContextValidator.java @@ -21,13 +21,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreResponse; -import com.microsoft.azure.cosmosdb.rx.internal.DocumentServiceRequestContext; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import java.util.ArrayList; import java.util.List; diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/DocumentServiceRequestValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestValidator.java similarity index 94% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/DocumentServiceRequestValidator.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestValidator.java index d26d13cd3c570..2f55d6f53ed4f 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/DocumentServiceRequestValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestValidator.java @@ -20,11 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import java.util.ArrayList; import java.util.List; diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FailureValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java similarity index 76% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FailureValidator.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java index 2ad5ec534aa67..76bdc3671a43a 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FailureValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java @@ -20,14 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.WFConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.RMResources; import java.util.ArrayList; import java.util.List; @@ -61,8 +61,8 @@ public Builder statusCode(int statusCode) { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - assertThat(((DocumentClientException) t).getStatusCode()).isEqualTo(statusCode); + assertThat(t).isInstanceOf(CosmosClientException.class); + assertThat(((CosmosClientException) t).statusCode()).isEqualTo(statusCode); } }); return this; @@ -73,8 +73,8 @@ public Builder lsnGreaterThan(long quorumAckedLSN) { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - assertThat(BridgeInternal.getLSN((DocumentClientException) t) > quorumAckedLSN).isTrue(); + assertThat(t).isInstanceOf(CosmosClientException.class); + assertThat(BridgeInternal.getLSN((CosmosClientException) t) > quorumAckedLSN).isTrue(); } }); return this; @@ -85,8 +85,8 @@ public Builder lsnGreaterThanEqualsTo(long quorumAckedLSN) @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - assertThat(BridgeInternal.getLSN((DocumentClientException) t) >= quorumAckedLSN).isTrue(); + assertThat(t).isInstanceOf(CosmosClientException.class); + assertThat(BridgeInternal.getLSN((CosmosClientException) t) >= quorumAckedLSN).isTrue(); } }); return this; @@ -97,11 +97,11 @@ public Builder exceptionQuorumAckedLSNInNotNull() { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - DocumentClientException documentClientException = (DocumentClientException) t; + assertThat(t).isInstanceOf(CosmosClientException.class); + CosmosClientException cosmosClientException = (CosmosClientException) t; long exceptionQuorumAckedLSN = -1; - if (documentClientException.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN) != null) { - exceptionQuorumAckedLSN = Long.parseLong((String) documentClientException.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); + if (cosmosClientException.responseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN) != null) { + exceptionQuorumAckedLSN = Long.parseLong((String) cosmosClientException.responseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); } assertThat(exceptionQuorumAckedLSN).isNotEqualTo(-1); @@ -126,8 +126,8 @@ public Builder notNullActivityId() { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - assertThat(((DocumentClientException) t).getActivityId()).isNotNull(); + assertThat(t).isInstanceOf(CosmosClientException.class); + assertThat(((CosmosClientException) t).message()).isNotNull(); } }); return this; @@ -138,8 +138,8 @@ public Builder error(Error error) { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - assertThat(((DocumentClientException) t).getError().toJson()).isEqualTo(error.toJson()); + assertThat(t).isInstanceOf(CosmosClientException.class); + assertThat(((CosmosClientException) t).error().toJson()).isEqualTo(error.toJson()); } }); return this; @@ -150,8 +150,8 @@ public Builder subStatusCode(Integer substatusCode) { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - assertThat(((DocumentClientException) t).getSubStatusCode()).isEqualTo(substatusCode); + assertThat(t).isInstanceOf(CosmosClientException.class); + assertThat(((CosmosClientException) t).subStatusCode()).isEqualTo(substatusCode); } }); return this; @@ -162,8 +162,8 @@ public Builder unknownSubStatusCode() { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - assertThat(((DocumentClientException) t).getSubStatusCode()).isEqualTo(HttpConstants.SubStatusCodes.UNKNOWN); + assertThat(t).isInstanceOf(CosmosClientException.class); + assertThat(((CosmosClientException) t).subStatusCode()).isEqualTo(HttpConstants.SubStatusCodes.UNKNOWN); } }); return this; @@ -174,8 +174,8 @@ public Builder responseHeader(String key, String value) { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - assertThat(((DocumentClientException) t).getResponseHeaders().get(key)).isEqualTo(value); + assertThat(t).isInstanceOf(CosmosClientException.class); + assertThat(((CosmosClientException) t).responseHeaders().get(key)).isEqualTo(value); } }); return this; @@ -186,8 +186,8 @@ public Builder lsn(long lsn) { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - DocumentClientException ex = (DocumentClientException) t; + assertThat(t).isInstanceOf(CosmosClientException.class); + CosmosClientException ex = (CosmosClientException) t; assertThat(BridgeInternal.getLSN(ex)).isEqualTo(lsn); } }); @@ -199,8 +199,8 @@ public Builder partitionKeyRangeId(String pkrid) { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - DocumentClientException ex = (DocumentClientException) t; + assertThat(t).isInstanceOf(CosmosClientException.class); + CosmosClientException ex = (CosmosClientException) t; assertThat(BridgeInternal.getPartitionKeyRangeId(ex)).isEqualTo(pkrid); } }); @@ -212,8 +212,8 @@ public Builder resourceAddress(String resourceAddress) { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - DocumentClientException ex = (DocumentClientException) t; + assertThat(t).isInstanceOf(CosmosClientException.class); + CosmosClientException ex = (CosmosClientException) t; assertThat(BridgeInternal.getResourceAddress(ex)).isEqualTo(resourceAddress); } }); @@ -247,9 +247,9 @@ public Builder resourceNotFound() { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - DocumentClientException ex = (DocumentClientException) t; - assertThat(ex.getStatusCode()).isEqualTo(404); + assertThat(t).isInstanceOf(CosmosClientException.class); + CosmosClientException ex = (CosmosClientException) t; + assertThat(ex.statusCode()).isEqualTo(404); } }); @@ -275,9 +275,9 @@ public Builder resourceAlreadyExists() { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - DocumentClientException ex = (DocumentClientException) t; - assertThat(ex.getStatusCode()).isEqualTo(409); + assertThat(t).isInstanceOf(CosmosClientException.class); + CosmosClientException ex = (CosmosClientException) t; + assertThat(ex.statusCode()).isEqualTo(409); } }); @@ -314,8 +314,8 @@ public Builder documentClientExceptionHeaderRequestContain @Override public void validate(Throwable t) { assertThat(t).isNotNull(); - assertThat(t).isInstanceOf(DocumentClientException.class); - DocumentClientException ex = (DocumentClientException) t; + assertThat(t).isInstanceOf(CosmosClientException.class); + CosmosClientException ex = (CosmosClientException) t; assertThat(BridgeInternal.getRequestHeaders(ex)).containsEntry(key, value); } }); diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FeedResponseListValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java similarity index 89% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FeedResponseListValidator.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java index ccf6bdd3df98e..7deee6988b3ea 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FeedResponseListValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java @@ -20,26 +20,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.util.ArrayList; -import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.BridgeInternal; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.BridgeInternal; import com.fasterxml.jackson.databind.node.ArrayNode; -import com.microsoft.azure.cosmosdb.CompositePath; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.QueryMetrics; -import com.microsoft.azure.cosmosdb.Resource; +import com.azure.data.cosmos.CompositePath; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.Resource; public interface FeedResponseListValidator { @@ -65,7 +64,7 @@ public Builder totalSize(final int expectedCount) { validators.add(new FeedResponseListValidator() { @Override public void validate(List> feedList) { - int resultCount = feedList.stream().mapToInt(f -> f.getResults().size()).sum(); + int resultCount = feedList.stream().mapToInt(f -> f.results().size()).sum(); assertThat(resultCount) .describedAs("total number of results").isEqualTo(expectedCount); } @@ -79,8 +78,8 @@ public Builder containsExactly(List expectedRids) { public void validate(List> feedList) { List actualIds = feedList .stream() - .flatMap(f -> f.getResults().stream()) - .map(r -> r.getResourceId()) + .flatMap(f -> f.results().stream()) + .map(r -> r.resourceId()) .collect(Collectors.toList()); assertThat(actualIds) .describedAs("Resource IDs of results") @@ -96,8 +95,8 @@ public Builder containsExactlyIds(List expectedIds) { public void validate(List> feedList) { List actualIds = feedList .stream() - .flatMap(f -> f.getResults().stream()) - .map(r -> r.getId()) + .flatMap(f -> f.results().stream()) + .map(r -> r.id()) .collect(Collectors.toList()); assertThat(actualIds) .describedAs("IDs of results") @@ -113,11 +112,11 @@ public Builder validateAllResources(Map> resourc public void validate(List> feedList) { List resources = feedList .stream() - .flatMap(f -> f.getResults().stream()) + .flatMap(f -> f.results().stream()) .collect(Collectors.toList()); for(T r: resources) { - ResourceValidator validator = resourceIDToValidator.get(r.getResourceId()); + ResourceValidator validator = resourceIDToValidator.get(r.resourceId()); assertThat(validator).isNotNull(); validator.validate(r); } @@ -132,8 +131,8 @@ public Builder exactlyContainsInAnyOrder(List expectedIds) { public void validate(List> feedList) { List actualIds = feedList .stream() - .flatMap(f -> f.getResults().stream()) - .map(r -> r.getResourceId()) + .flatMap(f -> f.results().stream()) + .map(r -> r.resourceId()) .collect(Collectors.toList()); assertThat(actualIds) .describedAs("Resource IDs of results") @@ -171,7 +170,7 @@ public Builder totalRequestChargeIsAtLeast(double minimumCharge) { validators.add(new FeedResponseListValidator() { @Override public void validate(List> feedList) { - assertThat(feedList.stream().mapToDouble(p -> p.getRequestCharge()).sum()) + assertThat(feedList.stream().mapToDouble(p -> p.requestCharge()).sum()) .describedAs("total request charge") .isGreaterThanOrEqualTo(minimumCharge); } @@ -204,11 +203,11 @@ public void validate(List> feedList) { } public Builder withAggregateValue(Object value) { - validators.add(new FeedResponseListValidator() { + validators.add(new FeedResponseListValidator() { @Override - public void validate(List> feedList) { - List list = feedList.get(0).getResults(); - CosmosItemSettings result = list.size() > 0 ? list.get(0) : null; + public void validate(List> feedList) { + List list = feedList.get(0).results(); + CosmosItemProperties result = list.size() > 0 ? list.get(0) : null; if (result != null) { if (value instanceof Double) { @@ -241,21 +240,21 @@ public void validate(List> feedList) { return this; } - public Builder withOrderedResults(ArrayList expectedOrderedList, + public Builder withOrderedResults(ArrayList expectedOrderedList, ArrayList compositeIndex) { - validators.add(new FeedResponseListValidator() { + validators.add(new FeedResponseListValidator() { @Override - public void validate(List> feedList) { + public void validate(List> feedList) { - List resultOrderedList = feedList.stream() - .flatMap(f -> f.getResults().stream()) + List resultOrderedList = feedList.stream() + .flatMap(f -> f.results().stream()) .collect(Collectors.toList()); assertThat(expectedOrderedList.size()).isEqualTo(resultOrderedList.size()); ArrayList paths = new ArrayList(); Iterator compositeIndexIterator = compositeIndex.iterator(); while (compositeIndexIterator.hasNext()) { - paths.add(compositeIndexIterator.next().getPath().replace("/", "")); + paths.add(compositeIndexIterator.next().path().replace("/", "")); } for (int i = 0; i < resultOrderedList.size(); i ++) { ArrayNode resultValues = (ArrayNode) resultOrderedList.get(i).get("$1"); @@ -285,7 +284,7 @@ public Builder pageLengths(int[] pageLengths) { public void validate(List> feedList) { assertThat(feedList).hasSize(pageLengths.length); for (int i = 0; i < pageLengths.length; i++) - assertThat(feedList.get(i).getResults().size()).isEqualTo(pageLengths[i]); + assertThat(feedList.get(i).results().size()).isEqualTo(pageLengths[i]); } }); return this; @@ -297,7 +296,7 @@ public Builder hasValidQueryMetrics(boolean shouldHaveMetrics) { public void validate(List> feedList) { for(FeedResponse feedPage: feedList) { if (shouldHaveMetrics) { - QueryMetrics queryMetrics = BridgeInternal.createQueryMetricsFromCollection(feedPage.getQueryMetrics().values()); + QueryMetrics queryMetrics = BridgeInternal.createQueryMetricsFromCollection(feedPage.queryMetrics().values()); assertThat(queryMetrics.getIndexHitDocumentCount()).isGreaterThanOrEqualTo(0); assertThat(queryMetrics.getRetrievedDocumentSize()).isGreaterThan(0); assertThat(queryMetrics.getTotalQueryExecutionTime().compareTo(Duration.ZERO)).isGreaterThan(0); @@ -312,7 +311,7 @@ public void validate(List> feedList) { assertThat(queryMetrics.getRuntimeExecutionTimes().getQueryEngineExecutionTime().compareTo(Duration.ZERO)).isGreaterThanOrEqualTo(0); assertThat(BridgeInternal.getClientSideMetrics(queryMetrics).getRequestCharge()).isGreaterThan(0); } else { - assertThat(feedPage.getQueryMetrics().isEmpty()); + assertThat(feedPage.queryMetrics().isEmpty()); } } } diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FeedResponseValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseValidator.java similarity index 82% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FeedResponseValidator.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseValidator.java index d245f6f49593d..24465d3d6fb29 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/FeedResponseValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseValidator.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -28,9 +28,9 @@ import java.util.List; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.HttpConstants; public interface FeedResponseValidator { @@ -57,7 +57,7 @@ public Builder pageSizeIsLessThanOrEqualTo(final int maxPageSize) { validators.add(new FeedResponseValidator() { @Override public void validate(FeedResponse feedPage) { - assertThat(feedPage.getResults().size()).isLessThanOrEqualTo(maxPageSize); + assertThat(feedPage.results().size()).isLessThanOrEqualTo(maxPageSize); } }); return this; @@ -68,7 +68,7 @@ public Builder pageSizeOf(final int expectedCount) { validators.add(new FeedResponseValidator() { @Override public void validate(FeedResponse feedPage) { - assertThat(feedPage.getResults()).hasSize(expectedCount); + assertThat(feedPage.results()).hasSize(expectedCount); } }); return this; @@ -79,7 +79,7 @@ public Builder positiveRequestCharge() { validators.add(new FeedResponseValidator() { @Override public void validate(FeedResponse feedPage) { - assertThat(feedPage.getRequestCharge()).isPositive(); + assertThat(feedPage.requestCharge()).isPositive(); } }); return this; @@ -90,7 +90,7 @@ public Builder requestChargeGreaterThanOrEqualTo(double minRequestCharge) { validators.add(new FeedResponseValidator() { @Override public void validate(FeedResponse feedPage) { - assertThat(feedPage.getRequestCharge()).isGreaterThanOrEqualTo(minRequestCharge); + assertThat(feedPage.requestCharge()).isGreaterThanOrEqualTo(minRequestCharge); } }); return this; @@ -101,7 +101,7 @@ public Builder requestChargeLessThanOrEqualTo(double maxRequestCharge) { validators.add(new FeedResponseValidator() { @Override public void validate(FeedResponse feedPage) { - assertThat(feedPage.getRequestCharge()).isLessThanOrEqualTo(maxRequestCharge); + assertThat(feedPage.requestCharge()).isLessThanOrEqualTo(maxRequestCharge); } }); return this; @@ -112,7 +112,7 @@ public Builder hasHeader(String headerKey) { validators.add(new FeedResponseValidator() { @Override public void validate(FeedResponse feedPage) { - assertThat(feedPage.getResponseHeaders()).containsKey(headerKey); + assertThat(feedPage.responseHeaders()).containsKey(headerKey); } }); return this; @@ -123,7 +123,7 @@ public Builder hasRequestChargeHeader() { validators.add(new FeedResponseValidator() { @Override public void validate(FeedResponse feedPage) { - assertThat(feedPage.getResponseHeaders()).containsKey(HttpConstants.HttpHeaders.REQUEST_CHARGE); + assertThat(feedPage.responseHeaders()).containsKey(HttpConstants.HttpHeaders.REQUEST_CHARGE); } }); return this; @@ -134,8 +134,8 @@ public Builder idsExactlyAre(final List expectedIds) { @Override public void validate(FeedResponse feedPage) { assertThat(feedPage - .getResults().stream() - .map(r -> r.getResourceId()) + .results().stream() + .map(r -> r.resourceId()) .collect(Collectors.toList())) .containsExactlyElementsOf(expectedIds); } diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceResponseValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java similarity index 88% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceResponseValidator.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java index 1af8ef372b6da..ea54984a7bfce 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceResponseValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -35,23 +35,22 @@ import org.assertj.core.api.Condition; -import com.microsoft.azure.cosmosdb.Attachment; -import com.microsoft.azure.cosmosdb.CompositePath; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.IndexingMode; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.PermissionMode; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.SpatialSpec; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.Trigger; -import com.microsoft.azure.cosmosdb.TriggerOperation; -import com.microsoft.azure.cosmosdb.TriggerType; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import com.microsoft.azure.cosmosdb.SpatialType; -import org.assertj.core.data.Offset; +import com.azure.data.cosmos.Attachment; +import com.azure.data.cosmos.CompositePath; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.IndexingMode; +import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.PermissionMode; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.SpatialSpec; +import com.azure.data.cosmos.StoredProcedure; +import com.azure.data.cosmos.Trigger; +import com.azure.data.cosmos.TriggerOperation; +import com.azure.data.cosmos.TriggerType; +import com.azure.data.cosmos.UserDefinedFunction; +import com.azure.data.cosmos.SpatialType; public interface ResourceResponseValidator { @@ -83,7 +82,7 @@ public Builder withId(final String resourceId) { @Override public void validate(ResourceResponse resourceResponse) { assertThat(resourceResponse.getResource()).isNotNull(); - assertThat(resourceResponse.getResource().getId()).as("check Resource Id").isEqualTo(resourceId); + assertThat(resourceResponse.getResource().id()).as("check Resource Id").isEqualTo(resourceId); } }); return this; @@ -133,8 +132,8 @@ public Builder withTimestampIsAfterOrEqualTo(Instant time) { @Override public void validate(ResourceResponse resourceResponse) { assertThat(resourceResponse.getResource()).isNotNull(); - assertThat(resourceResponse.getResource().getTimestamp()).isNotNull(); - OffsetDateTime d = resourceResponse.getResource().getTimestamp(); + assertThat(resourceResponse.getResource().timestamp()).isNotNull(); + OffsetDateTime d = resourceResponse.getResource().timestamp(); System.out.println(d.toString()); assertThat(d.toInstant()).isAfterOrEqualTo(time); } @@ -148,8 +147,8 @@ public Builder withTimestampIsBeforeOrEqualTo(Instant time) { @Override public void validate(ResourceResponse resourceResponse) { assertThat(resourceResponse.getResource()).isNotNull(); - assertThat(resourceResponse.getResource().getTimestamp()).isNotNull(); - OffsetDateTime d = resourceResponse.getResource().getTimestamp(); + assertThat(resourceResponse.getResource().timestamp()).isNotNull(); + OffsetDateTime d = resourceResponse.getResource().timestamp(); assertThat(d.toInstant()).isBeforeOrEqualTo(time); } }); @@ -185,7 +184,7 @@ public Builder indexingMode(IndexingMode mode) { public void validate(ResourceResponse resourceResponse) { assertThat(resourceResponse.getResource()).isNotNull(); assertThat(resourceResponse.getResource().getIndexingPolicy()).isNotNull(); - assertThat(resourceResponse.getResource().getIndexingPolicy().getIndexingMode()).isEqualTo(mode); + assertThat(resourceResponse.getResource().getIndexingPolicy().indexingMode()).isEqualTo(mode); } }); return this; @@ -231,7 +230,7 @@ public Builder notNullEtag() { @Override public void validate(ResourceResponse resourceResponse) { assertThat(resourceResponse.getResource()).isNotNull(); - assertThat(resourceResponse.getResource().getETag()).isNotNull(); + assertThat(resourceResponse.getResource().etag()).isNotNull(); } }); return this; @@ -243,7 +242,7 @@ public Builder notEmptySelfLink() { @Override public void validate(ResourceResponse resourceResponse) { assertThat(resourceResponse.getResource()).isNotNull(); - assertThat(resourceResponse.getResource().getSelfLink()).isNotEmpty(); + assertThat(resourceResponse.getResource().selfLink()).isNotEmpty(); } }); return this; @@ -303,7 +302,7 @@ public Builder withCompositeIndexes(Collection> comp @Override public void validate(ResourceResponse resourceResponse) { Iterator> compositeIndexesReadIterator = resourceResponse.getResource() - .getIndexingPolicy().getCompositeIndexes().iterator(); + .getIndexingPolicy().compositeIndexes().iterator(); Iterator> compositeIndexesWrittenIterator = compositeIndexesWritten.iterator(); ArrayList readIndexesStrings = new ArrayList(); @@ -320,8 +319,8 @@ public void validate(ResourceResponse resourceResponse) { CompositePath compositePathRead = compositeIndexReadIterator.next(); CompositePath compositePathWritten = compositeIndexWrittenIterator.next(); - readIndexesString.append(compositePathRead.getPath() + ":" + compositePathRead.getOrder() + ";"); - writtenIndexesString.append(compositePathWritten.getPath() + ":" + compositePathRead.getOrder() + ";"); + readIndexesString.append(compositePathRead.path() + ":" + compositePathRead.order() + ";"); + writtenIndexesString.append(compositePathWritten.path() + ":" + compositePathRead.order() + ";"); } readIndexesStrings.add(readIndexesString.toString()); @@ -340,7 +339,7 @@ public Builder withSpatialIndexes(Collection spatialIndexes) { @Override public void validate(ResourceResponse resourceResponse) { Iterator spatialIndexesReadIterator = resourceResponse.getResource() - .getIndexingPolicy().getSpatialIndexes().iterator(); + .getIndexingPolicy().spatialIndexes().iterator(); Iterator spatialIndexesWrittenIterator = spatialIndexes.iterator(); HashMap> readIndexMap = new HashMap>(); @@ -350,14 +349,14 @@ public void validate(ResourceResponse resourceResponse) { SpatialSpec spatialSpecRead = spatialIndexesReadIterator.next(); SpatialSpec spatialSpecWritten = spatialIndexesWrittenIterator.next(); - String readPath = spatialSpecRead.getPath() + ":"; - String writtenPath = spatialSpecWritten.getPath() + ":"; + String readPath = spatialSpecRead.path() + ":"; + String writtenPath = spatialSpecWritten.path() + ":"; ArrayList readSpatialTypes = new ArrayList(); ArrayList writtenSpatialTypes = new ArrayList(); - Iterator spatialTypesReadIterator = spatialSpecRead.getSpatialTypes().iterator(); - Iterator spatialTypesWrittenIterator = spatialSpecWritten.getSpatialTypes().iterator(); + Iterator spatialTypesReadIterator = spatialSpecRead.spatialTypes().iterator(); + Iterator spatialTypesWrittenIterator = spatialSpecWritten.spatialTypes().iterator(); while (spatialTypesReadIterator.hasNext() && spatialTypesWrittenIterator.hasNext()) { readSpatialTypes.add(spatialTypesReadIterator.next()); diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceValidator.java similarity index 96% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceValidator.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceValidator.java index d2bba2e3cd837..38c72309d5417 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/ResourceValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceValidator.java @@ -20,14 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; -import com.microsoft.azure.cosmosdb.Resource; +import com.azure.data.cosmos.Resource; interface ResourceValidator { diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java similarity index 96% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java index a6847021992e5..0acb0438ef6db 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/TestConfigurations.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import org.apache.commons.lang3.StringUtils; @@ -40,7 +40,7 @@ * If none of the above is set, emulator endpoint will be used. */ public final class TestConfigurations { - // Replace MASTER_KEY and HOST with values from your Azure Cosmos DB account. + // REPLACE MASTER_KEY and HOST with values from your Azure Cosmos DB account. // The default values are credentials of the local emulator, which are not used in any production environment. // public static String MASTER_KEY = @@ -58,7 +58,7 @@ public final class TestConfigurations { public static String CONSISTENCY = System.getProperty("ACCOUNT_CONSISTENCY", StringUtils.defaultString(Strings.emptyToNull( - System.getenv().get("ACCOUNT_CONSISTENCY")), "Strong")); + System.getenv().get("ACCOUNT_CONSISTENCY")), "STRONG")); public static String PREFERRED_LOCATIONS = System.getProperty("PREFERRED_LOCATIONS", diff --git a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/Utils.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/Utils.java similarity index 92% rename from commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/Utils.java rename to commons-test-utils/src/main/java/com/azure/data/cosmos/rx/Utils.java index 9bc18381d95da..8c9a897eb508f 100644 --- a/commons-test-utils/src/main/java/com/microsoft/azure/cosmosdb/rx/Utils.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/Utils.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; -import com.microsoft.azure.cosmosdb.Database; +import com.azure.data.cosmos.Database; public class Utils { private static final String DATABASES_PATH_SEGMENT = "dbs"; @@ -32,9 +32,9 @@ public class Utils { public static String getDatabaseLink(Database database, boolean isNameBased) { if (isNameBased) { - return getDatabaseNameLink(database.getId()); + return getDatabaseNameLink(database.id()); } else { - return database.getSelfLink(); + return database.selfLink(); } } diff --git a/commons-test-utils/src/main/tests/java/com/microsoft/azure/cosmosdb/ConfigsBuilderTest.java b/commons-test-utils/src/main/tests/java/com/azure/data/cosmos/ConfigsBuilderTest.java similarity index 91% rename from commons-test-utils/src/main/tests/java/com/microsoft/azure/cosmosdb/ConfigsBuilderTest.java rename to commons-test-utils/src/main/tests/java/com/azure/data/cosmos/ConfigsBuilderTest.java index cf49065ef5bfc..4e38ffcade804 100644 --- a/commons-test-utils/src/main/tests/java/com/microsoft/azure/cosmosdb/ConfigsBuilderTest.java +++ b/commons-test-utils/src/main/tests/java/com/azure/data/cosmos/ConfigsBuilderTest.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; +import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.internal.Configs; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/AccessCondition.java b/commons/src/main/java/com/azure/data/cosmos/AccessCondition.java similarity index 86% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/AccessCondition.java rename to commons/src/main/java/com/azure/data/cosmos/AccessCondition.java index ecf664d5795a9..93e79486db4f3 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/AccessCondition.java +++ b/commons/src/main/java/com/azure/data/cosmos/AccessCondition.java @@ -21,14 +21,14 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Represents a set of access conditions to be used for operations against the Azure Cosmos DB database service. */ public final class AccessCondition { - private AccessConditionType type = AccessConditionType.IfMatch; + private AccessConditionType type = AccessConditionType.IF_MATCH; private String condition; /** @@ -36,7 +36,7 @@ public final class AccessCondition { * * @return the condition type. */ - public AccessConditionType getType() { + public AccessConditionType type() { return this.type; } @@ -45,8 +45,9 @@ public AccessConditionType getType() { * * @param type the condition type to use. */ - public void setType(AccessConditionType type) { + public AccessCondition type(AccessConditionType type) { this.type = type; + return this; } /** @@ -55,7 +56,7 @@ public void setType(AccessConditionType type) { * * @return the condition. */ - public String getCondition() { + public String condition() { return this.condition; } @@ -65,7 +66,8 @@ public String getCondition() { * * @param condition the condition to use. */ - public void setCondition(String condition) { + public AccessCondition condition(String condition) { this.condition = condition; + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/AccessConditionType.java b/commons/src/main/java/com/azure/data/cosmos/AccessConditionType.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/AccessConditionType.java rename to commons/src/main/java/com/azure/data/cosmos/AccessConditionType.java index 1366079dfe2aa..7dd4538e76c75 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/AccessConditionType.java +++ b/commons/src/main/java/com/azure/data/cosmos/AccessConditionType.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Specifies the set of access condition types that can be used for operations in the Azure Cosmos DB database service. @@ -30,10 +30,10 @@ public enum AccessConditionType { /** * Check if the resource's ETag value matches the ETag value performed. */ - IfMatch, + IF_MATCH, /** * Check if the resource's ETag value does not match ETag value performed. */ - IfNoneMatch + IF_NONE_MATCH } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Attachment.java b/commons/src/main/java/com/azure/data/cosmos/Attachment.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Attachment.java rename to commons/src/main/java/com/azure/data/cosmos/Attachment.java index 203c778242d3c..c3a370050ba8a 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Attachment.java +++ b/commons/src/main/java/com/azure/data/cosmos/Attachment.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents a document attachment in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/BridgeInternal.java b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java similarity index 64% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/BridgeInternal.java rename to commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java index f7c90034da6c1..e883125bd9cec 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/BridgeInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java @@ -21,15 +21,15 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.query.metrics.ClientSideMetrics; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.Strings; import java.net.URI; import java.util.Collection; @@ -39,12 +39,11 @@ import java.util.Map; import java.util.concurrent.ConcurrentMap; -import static com.microsoft.azure.cosmosdb.internal.Constants.QueryExecutionContext.INCREMENTAL_FEED_HEADER_VALUE; - +import static com.azure.data.cosmos.internal.Constants.QueryExecutionContext.INCREMENTAL_FEED_HEADER_VALUE; /** * This is meant to be used only internally as a bridge access to classes in - * com.microsoft.azure.cosmosdb + * com.azure.data.cosmos **/ public class BridgeInternal { @@ -61,7 +60,8 @@ public static ResourceResponse toResourceResponse(RxDocu return new ResourceResponse(response, cls); } - public static MediaResponse toMediaResponse(RxDocumentServiceResponse response, boolean willBuffer) { + public static MediaResponse toMediaResponse(RxDocumentServiceResponse response, + boolean willBuffer) { return new MediaResponse(response, willBuffer); } @@ -72,7 +72,8 @@ public static FeedResponse toFeedResponsePage(RxDocument public static FeedResponse toChaneFeedResponsePage(RxDocumentServiceResponse response, Class cls) { - return new FeedResponse(noChanges(response) ? Collections.emptyList(): response.getQueryResponse(cls), response.getResponseHeaders(), noChanges(response)); + return new FeedResponse(noChanges(response) ? Collections.emptyList() : response.getQueryResponse(cls), + response.getResponseHeaders(), noChanges(response)); } public static StoredProcedureResponse toStoredProcedureResponse(RxDocumentServiceResponse response) { @@ -100,62 +101,62 @@ public static Map getFeedHeaders(FeedOptionsBase options) { Map headers = new HashMap<>(); - if (options.getMaxItemCount() != null) { - headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, options.getMaxItemCount().toString()); + if (options.maxItemCount() != null) { + headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, options.maxItemCount().toString()); } if (options instanceof ChangeFeedOptions) { ChangeFeedOptions changeFeedOptions = (ChangeFeedOptions) options; String ifNoneMatchValue = null; - if (changeFeedOptions.getRequestContinuation() != null) { - ifNoneMatchValue = changeFeedOptions.getRequestContinuation(); - } else if (!changeFeedOptions.isStartFromBeginning()) { + if (changeFeedOptions.requestContinuation() != null) { + ifNoneMatchValue = changeFeedOptions.requestContinuation(); + } else if (!changeFeedOptions.startFromBeginning()) { ifNoneMatchValue = "*"; } - // On REST level, change feed is using IfNoneMatch/ETag instead of + // On REST level, change feed is using IF_NONE_MATCH/ETag instead of // continuation. if (ifNoneMatchValue != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, ifNoneMatchValue); } headers.put(HttpConstants.HttpHeaders.A_IM, INCREMENTAL_FEED_HEADER_VALUE); - } else if (options.getRequestContinuation() != null) { - headers.put(HttpConstants.HttpHeaders.CONTINUATION, options.getRequestContinuation()); + } else if (options.requestContinuation() != null) { + headers.put(HttpConstants.HttpHeaders.CONTINUATION, options.requestContinuation()); } FeedOptions feedOptions = options instanceof FeedOptions ? (FeedOptions) options : null; if (feedOptions != null) { - if (feedOptions.getSessionToken() != null) { - headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, feedOptions.getSessionToken()); + if (feedOptions.sessionToken() != null) { + headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, feedOptions.sessionToken()); } - if (feedOptions.getEnableScanInQuery() != null) { - headers.put(HttpConstants.HttpHeaders.ENABLE_SCAN_IN_QUERY, - feedOptions.getEnableScanInQuery().toString()); + if (feedOptions.enableScanInQuery() != null) { + headers.put(HttpConstants.HttpHeaders.ENABLE_SCAN_IN_QUERY, feedOptions.enableScanInQuery().toString()); } - if (feedOptions.getEmitVerboseTracesInQuery() != null) { + if (feedOptions.emitVerboseTracesInQuery() != null) { headers.put(HttpConstants.HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY, - feedOptions.getEmitVerboseTracesInQuery().toString()); + feedOptions.emitVerboseTracesInQuery().toString()); } - if (feedOptions.getEnableCrossPartitionQuery() != null) { + if (feedOptions.enableCrossPartitionQuery() != null) { headers.put(HttpConstants.HttpHeaders.ENABLE_CROSS_PARTITION_QUERY, - feedOptions.getEnableCrossPartitionQuery().toString()); + feedOptions.enableCrossPartitionQuery().toString()); } - if (feedOptions.getMaxDegreeOfParallelism() != 0) { + if (feedOptions.maxDegreeOfParallelism() != 0) { headers.put(HttpConstants.HttpHeaders.PARALLELIZE_CROSS_PARTITION_QUERY, Boolean.TRUE.toString()); } - if (feedOptions.getResponseContinuationTokenLimitInKb() > 0) { + if (feedOptions.responseContinuationTokenLimitInKb() > 0) { headers.put(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, - Strings.toString(feedOptions.getResponseContinuationTokenLimitInKb())); + Strings.toString(feedOptions.responseContinuationTokenLimitInKb())); } - if(feedOptions.getPopulateQueryMetrics()){ - headers.put(HttpConstants.HttpHeaders.POPULATE_QUERY_METRICS, String.valueOf(feedOptions.getPopulateQueryMetrics())); + if (feedOptions.populateQueryMetrics()) { + headers.put(HttpConstants.HttpHeaders.POPULATE_QUERY_METRICS, + String.valueOf(feedOptions.populateQueryMetrics())); } } @@ -170,37 +171,39 @@ public static boolean noChanges(RxDocumentServiceResponse r return rsp.getStatusCode() == HttpConstants.StatusCodes.NOT_MODIFIED; } - public static FeedResponse createFeedResponse(List results, Map headers) { + public static FeedResponse createFeedResponse(List results, + Map headers) { return new FeedResponse<>(results, headers); } - - public static FeedResponse createFeedResponseWithQueryMetrics(List results, Map headers, ConcurrentMap queryMetricsMap) { + + public static FeedResponse createFeedResponseWithQueryMetrics(List results, + Map headers, ConcurrentMap queryMetricsMap) { return new FeedResponse<>(results, headers, queryMetricsMap); } - public static E setResourceAddress(E e, String resourceAddress) { + public static E setResourceAddress(E e, String resourceAddress) { e.resourceAddress = resourceAddress; return e; } - public static long getLSN(E e) { + public static long getLSN(E e) { return e.lsn; } - public static String getPartitionKeyRangeId(E e) { + public static String getPartitionKeyRangeId(E e) { return e.partitionKeyRangeId; } - public static String getResourceAddress(E e) { + public static String getResourceAddress(E e) { return e.resourceAddress; } - public static E setLSN(E e, long lsn) { + public static E setLSN(E e, long lsn) { e.lsn = lsn; return e; } - public static E setPartitionKeyRangeId(E e, String partitionKeyRangeId) { + public static E setPartitionKeyRangeId(E e, String partitionKeyRangeId) { e.partitionKeyRangeId = partitionKeyRangeId; return e; } @@ -210,23 +213,25 @@ public static boolean isEnableMultipleWriteLocations(DatabaseAccount account) { } public static boolean getUseMultipleWriteLocations(ConnectionPolicy policy) { - return policy.isUsingMultipleWriteLocations(); + return policy.usingMultipleWriteLocations(); } public static void setUseMultipleWriteLocations(ConnectionPolicy policy, boolean value) { - policy.setUsingMultipleWriteLocations(value); + policy.usingMultipleWriteLocations(value); } - public static URI getRequestUri(DocumentClientException documentClientException) { - return documentClientException.requestUri; + public static URI getRequestUri(CosmosClientException cosmosClientException) { + return cosmosClientException.requestUri; } - public static void setRequestHeaders(DocumentClientException documentClientException, Map requestHeaders) { - documentClientException.requestHeaders = requestHeaders; + public static void setRequestHeaders(CosmosClientException cosmosClientException, + Map requestHeaders) { + cosmosClientException.requestHeaders = requestHeaders; } - public static Map getRequestHeaders(DocumentClientException documentClientException) { - return documentClientException.requestHeaders; + public static Map getRequestHeaders( + CosmosClientException cosmosClientException) { + return cosmosClientException.requestHeaders; } public static Map getQueryEngineConfiuration(DatabaseAccount databaseAccount) { @@ -246,48 +251,47 @@ public static ConsistencyPolicy getConsistencyPolicy(DatabaseAccount databaseAcc } public static String getAltLink(Resource resource) { - return resource.getAltLink(); + return resource.altLink(); } public static void setAltLink(Resource resource, String altLink) { - resource.setAltLink(altLink); + resource.altLink(altLink); } public static void setMaxReplicaSetSize(ReplicationPolicy replicationPolicy, int value) { replicationPolicy.setMaxReplicaSetSize(value); } - public static void putQueryMetricsIntoMap(FeedResponse response, - String partitionKeyRangeId, - QueryMetrics queryMetrics){ - response.getQueryMetricsMap().put(partitionKeyRangeId, queryMetrics); + public static void putQueryMetricsIntoMap(FeedResponse response, String partitionKeyRangeId, + QueryMetrics queryMetrics) { + response.queryMetricsMap().put(partitionKeyRangeId, queryMetrics); } - public static QueryMetrics createQueryMetricsFromDelimitedStringAndClientSideMetrics(String queryMetricsDelimitedString, - ClientSideMetrics clientSideMetrics, - String activityId) { - return QueryMetrics.createFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, clientSideMetrics, activityId); + public static QueryMetrics createQueryMetricsFromDelimitedStringAndClientSideMetrics( + String queryMetricsDelimitedString, ClientSideMetrics clientSideMetrics, String activityId) { + return QueryMetrics.createFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, + clientSideMetrics, activityId); } public static QueryMetrics createQueryMetricsFromCollection(Collection queryMetricsCollection) { return QueryMetrics.createFromCollection(queryMetricsCollection); } - public static ClientSideMetrics getClientSideMetrics(QueryMetrics queryMetrics){ + public static ClientSideMetrics getClientSideMetrics(QueryMetrics queryMetrics) { return queryMetrics.getClientSideMetrics(); } - public static String getInnerErrorMessage(DocumentClientException documentClientException) { - if (documentClientException == null) { + public static String getInnerErrorMessage(CosmosClientException cosmosClientException) { + if (cosmosClientException == null) { return null; } - return documentClientException.getInnerErrorMessage(); + return cosmosClientException.innerErrorMessage(); } - + public static PartitionKeyInternal getNonePartitionKey(PartitionKeyDefinition partitionKeyDefinition) { return partitionKeyDefinition.getNonePartitionKeyValue(); } - + public static PartitionKey getPartitionKey(PartitionKeyInternal partitionKeyInternal) { return new PartitionKey(partitionKeyInternal); } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ChangeFeedOptions.java b/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java similarity index 73% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ChangeFeedOptions.java rename to commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java index a52595d594434..9341a1279ae5c 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ChangeFeedOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java @@ -21,19 +21,21 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import java.time.ZonedDateTime; +import java.time.OffsetDateTime; /** - * Specifies the options associated with change feed methods (enumeration operations) in the Azure Cosmos DB database service. + * Specifies the options associated with change feed methods (enumeration + * operations) in the Azure Cosmos DB database service. */ public final class ChangeFeedOptions extends FeedOptionsBase { private String partitionKeyRangeId; private boolean startFromBeginning; - private ZonedDateTime startDateTime; + private OffsetDateTime startDateTime; - public ChangeFeedOptions() {} + public ChangeFeedOptions() { + } public ChangeFeedOptions(ChangeFeedOptions options) { super(options); @@ -42,68 +44,80 @@ public ChangeFeedOptions(ChangeFeedOptions options) { this.startDateTime = options.startDateTime; } + // TODO: Make private /** * Get the partition key range id for the current request *

* ChangeFeed requests can be executed against specific partition key ranges. - * This is used to process the change feed in parallel across multiple consumers. + * This is used to process the change feed in parallel across multiple + * consumers. *

* * @return a string indicating the partition key range ID * @see PartitionKeyRange */ - public String getPartitionKeyRangeId() { + public String partitionKeyRangeId() { return partitionKeyRangeId; } + // TODO: Make private /** * Set the partition key range id for the current request *

* ChangeFeed requests can be executed against specific partition key ranges. - * This is used to process the change feed in parallel across multiple consumers. + * This is used to process the change feed in parallel across multiple + * consumers. *

* * @param partitionKeyRangeId a string indicating the partition key range ID * @see PartitionKeyRange */ - public void setPartitionKeyRangeId(String partitionKeyRangeId) { + public ChangeFeedOptions partitionKeyRangeId(String partitionKeyRangeId) { this.partitionKeyRangeId = partitionKeyRangeId; + return this; } /** - * Get whether change feed should start from beginning (true) or from current (false). - * By default it's start from current (false). + * Get whether change feed should start from beginning (true) or from current + * (false). By default it's start from current (false). * - * @return a boolean value indicating change feed should start from beginning or not + * @return a boolean value indicating change feed should start from beginning or + * not */ - public boolean isStartFromBeginning() { + public boolean startFromBeginning() { return startFromBeginning; } /** - * Set whether change feed should start from beginning (true) or from current (false). - * By default it's start from current (false). + * Set whether change feed should start from beginning (true) or from current + * (false). By default it's start from current (false). * - * @param startFromBeginning a boolean value indicating change feed should start from beginning or not + * @param startFromBeginning a boolean value indicating change feed should start + * from beginning or not */ - public void setStartFromBeginning(boolean startFromBeginning) { + public ChangeFeedOptions startFromBeginning(boolean startFromBeginning) { this.startFromBeginning = startFromBeginning; + return this; } /** * Gets the zoned date time to start looking for changes after. - * @return a zoned date time to start looking for changes after, if set or null otherwise + * + * @return a zoned date time to start looking for changes after, if set or null + * otherwise */ - public ZonedDateTime getStartDateTime() { + public OffsetDateTime startDateTime() { return startDateTime; } /** - * Sets the zoned date time (exclusive) to start looking for changes after. - * If this is specified, startFromBeginning is ignored. + * Sets the zoned date time (exclusive) to start looking for changes after. If + * this is specified, startFromBeginning is ignored. + * * @param startDateTime a zoned date time to start looking for changes after. */ - public void setStartDateTime(ZonedDateTime startDateTime) { + public ChangeFeedOptions startDateTime(OffsetDateTime startDateTime) { this.startDateTime = startDateTime; + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ClientSideRequestStatistics.java b/commons/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ClientSideRequestStatistics.java rename to commons/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java index cc71e6b391f5b..96bfff7d5bea3 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ClientSideRequestStatistics.java +++ b/commons/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.net.URI; import java.net.URISyntaxException; @@ -37,11 +37,11 @@ import java.util.Map; import java.util.Set; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreResult; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.directconnectivity.StoreResult; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.StringUtils; public class ClientSideRequestStatistics { @@ -171,7 +171,7 @@ public String toString() { .append("Duration: ") .append(Duration.between(requestStartTime, requestEndTime).toMillis()) .append(" ms, ") - .append("Number of regions attempted: ") + .append("NUMBER of regions attempted: ") .append(this.regionsContacted.isEmpty() ? 1 : this.regionsContacted.size()) .append(System.lineSeparator()); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/CommonsBridgeInternal.java b/commons/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java similarity index 86% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/CommonsBridgeInternal.java rename to commons/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java index 20009de704a80..6c6a72a5d8608 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/CommonsBridgeInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java @@ -21,14 +21,14 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; public class CommonsBridgeInternal { public static boolean isV2(PartitionKeyDefinition pkd) { - return pkd.getVersion() != null && PartitionKeyDefinitionVersion.V2.val == pkd.getVersion().val; + return pkd.version() != null && PartitionKeyDefinitionVersion.V2.val == pkd.version().val; } public static void setV2(PartitionKeyDefinition pkd) { - pkd.setVersion(PartitionKeyDefinitionVersion.V2); + pkd.version(PartitionKeyDefinitionVersion.V2); } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/CompositePath.java b/commons/src/main/java/com/azure/data/cosmos/CompositePath.java similarity index 84% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/CompositePath.java rename to commons/src/main/java/com/azure/data/cosmos/CompositePath.java index ea9fcb67b175d..5b61db6640d63 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/CompositePath.java +++ b/commons/src/main/java/com/azure/data/cosmos/CompositePath.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import org.apache.commons.lang3.StringUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; import org.apache.commons.text.WordUtils; /** @@ -56,7 +56,7 @@ public CompositePath(String jsonString) { * * @return the path. */ - public String getPath() { + public String path() { return super.getString(Constants.Properties.PATH); } @@ -65,8 +65,9 @@ public String getPath() { * * @param path the path. */ - public void setPath(String path) { + public CompositePath path(String path) { super.set(Constants.Properties.PATH, path); + return this; } /** @@ -77,17 +78,17 @@ public void setPath(String path) { * * @return the sort order. */ - public CompositePathSortOrder getOrder() { + public CompositePathSortOrder order() { String strValue = super.getString(Constants.Properties.ORDER); if (!StringUtils.isEmpty(strValue)) { try { - return CompositePathSortOrder.valueOf(WordUtils.capitalize(super.getString(Constants.Properties.ORDER))); + return CompositePathSortOrder.valueOf(StringUtils.upperCase(super.getString(Constants.Properties.ORDER))); } catch (IllegalArgumentException e) { - this.getLogger().warn("Invalid indexingMode value {}.", super.getString(Constants.Properties.ORDER)); - return CompositePathSortOrder.Ascending; + this.getLogger().warn("INVALID indexingMode value {}.", super.getString(Constants.Properties.ORDER)); + return CompositePathSortOrder.ASCENDING; } } - return CompositePathSortOrder.Ascending; + return CompositePathSortOrder.ASCENDING; } /** @@ -98,7 +99,8 @@ public CompositePathSortOrder getOrder() { * * @param order the sort order. */ - public void setOrder(CompositePathSortOrder order) { + public CompositePath order(CompositePathSortOrder order) { super.set(Constants.Properties.ORDER, order.toString()); + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/CompositePathSortOrder.java b/commons/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java similarity index 90% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/CompositePathSortOrder.java rename to commons/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java index fdb123abb0f8c..7440421065c5d 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/CompositePathSortOrder.java +++ b/commons/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Represents the sorting order for a path in a composite index, for a @@ -29,18 +29,18 @@ */ public enum CompositePathSortOrder { /** - * Ascending sort order for composite paths. + * ASCENDING sort order for composite paths. */ - Ascending { + ASCENDING { public String toString() { return "ascending"; } }, /** - * Descending sort order for composite paths. + * DESCENDING sort order for composite paths. */ - Descending { + DESCENDING { public String toString() { return "descending"; } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Conflict.java b/commons/src/main/java/com/azure/data/cosmos/Conflict.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Conflict.java rename to commons/src/main/java/com/azure/data/cosmos/Conflict.java index 21650fe6331a6..26de0dc92e861 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Conflict.java +++ b/commons/src/main/java/com/azure/data/cosmos/Conflict.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.Strings; import java.lang.reflect.InvocationTargetException; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConflictResolutionMode.java b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java similarity index 74% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ConflictResolutionMode.java rename to commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java index 8e605c5a09511..7f504fdea2990 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConflictResolutionMode.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java @@ -21,33 +21,33 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; public enum ConflictResolutionMode { /** * Last writer wins conflict resolution mode * - * Setting the ConflictResolutionMode to "LastWriterWins" indicates that conflict resolution should be done by inspecting a field in the conflicting documents - * and picking the document which has the higher value in that path. See {@link ConflictResolutionPolicy#getConflictResolutionPath()} for details on how to specify the path + * Setting the ConflictResolutionMode to "LAST_WRITER_WINS" indicates that conflict resolution should be done by inspecting a field in the conflicting documents + * and picking the document which has the higher value in that path. See {@link ConflictResolutionPolicy#conflictResolutionPath()} for details on how to specify the path * to be checked for conflict resolution. Also note that Deletes win. */ - LastWriterWins, + LAST_WRITER_WINS, /** - * Custom conflict resolution mode + * CUSTOM conflict resolution mode * - * Setting the ConflictResolutionMode to "Custom" indicates that conflict resolution is custom handled by a user. + * Setting the ConflictResolutionMode to "CUSTOM" indicates that conflict resolution is custom handled by a user. * The user could elect to register a user specified {@link StoredProcedure} for handling conflicting resources. * Should the user not register a user specified StoredProcedure, conflicts will default to being made available as {@link Conflict} resources, * which the user can inspect and manually resolve. - * See {@link ConflictResolutionPolicy#getConflictResolutionProcedure()} for details on how to specify the stored procedure + * See {@link ConflictResolutionPolicy#conflictResolutionProcedure()} for details on how to specify the stored procedure * to run for conflict resolution. */ - Custom, + CUSTOM, /** - * Invalid or unknown mode. + * INVALID or unknown mode. */ - Invalid + INVALID } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConflictResolutionPolicy.java b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java similarity index 76% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ConflictResolutionPolicy.java rename to commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java index 291b24d326b9d..286bbd66b33f8 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConflictResolutionPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java @@ -1,8 +1,9 @@ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.Strings; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; @@ -13,10 +14,10 @@ * A collection with custom conflict resolution with no user-registered stored procedure. *
{@code
  * DocumentCollection collectionSpec = new DocumentCollection();
- * collectionSpec.setId("Multi-master collection");
+ * collectionSpec.id("Multi-master collection");
  *
  * ConflictResolutionPolicy policy = ConflictResolutionPolicy.createCustomPolicy();
- * collectionSpec.setConflictResolutionPolicy(policy);
+ * collectionSpec.conflictResolutionPolicy(policy);
  *
  * DocumentCollection collection = client.createCollection(databaseLink, collectionSpec, null)
  *         .toBlocking().single().getResource();
@@ -27,10 +28,10 @@
  * A collection with custom conflict resolution with a user-registered stored procedure.
  * 
{@code
  * DocumentCollection collectionSpec = new DocumentCollection();
- * collectionSpec.setId("Multi-master collection");
+ * collectionSpec.id("Multi-master collection");
  *
  * ConflictResolutionPolicy policy = ConflictResolutionPolicy.createCustomPolicy(conflictResolutionSprocName);
- * collectionSpec.setConflictResolutionPolicy(policy);
+ * collectionSpec.conflictResolutionPolicy(policy);
  *
  * DocumentCollection collection = client.createCollection(databaseLink, collectionSpec, null)
  *         .toBlocking().single().getResource();
@@ -42,10 +43,10 @@
  * A collection with custom conflict resolution with a user-registered stored procedure.
  * 
{@code
  * DocumentCollection collectionSpec = new DocumentCollection();
- * collectionSpec.setId("Multi-master collection");
+ * collectionSpec.id("Multi-master collection");
  *
  * ConflictResolutionPolicy policy = ConflictResolutionPolicy.createLastWriterWinsPolicy("/path/for/conflict/resolution");
- * collectionSpec.setConflictResolutionPolicy(policy);
+ * collectionSpec.conflictResolutionPolicy(policy);
  *
  * DocumentCollection collection = client.createCollection(databaseLink, collectionSpec, null)
  *         .toBlocking().single().getResource();
@@ -56,22 +57,22 @@
 public class ConflictResolutionPolicy extends JsonSerializable {
 
     /**
-     * Creates a LastWriterWins {@link ConflictResolutionPolicy} with "/_ts" as the resolution path.
+     * Creates a LAST_WRITER_WINS {@link ConflictResolutionPolicy} with "/_ts" as the resolution path.
      *
      * In case of a conflict occurring on a document, the document with the higher integer value in the default path
-     * {@link Resource#getTimestamp()}, i.e., "/_ts" will be used.
+     * {@link Resource#timestamp()}, i.e., "/_ts" will be used.
      *
      * @return ConflictResolutionPolicy.
      */
     public static ConflictResolutionPolicy createLastWriterWinsPolicy() {
         ConflictResolutionPolicy policy = new ConflictResolutionPolicy();
-        policy.setMode(ConflictResolutionMode.LastWriterWins);
+        policy.mode(ConflictResolutionMode.LAST_WRITER_WINS);
         return policy;
     }
 
     /**
      *
-     * Creates a LastWriterWins {@link ConflictResolutionPolicy} with path as the resolution path.
+     * Creates a LAST_WRITER_WINS {@link ConflictResolutionPolicy} with path as the resolution path.
      *
      * The specified path must be present in each document and must be an integer value.
      * In case of a conflict occurring on a document, the document with the higher integer value in the specified path
@@ -83,15 +84,15 @@ public static ConflictResolutionPolicy createLastWriterWinsPolicy() {
      */
     public static ConflictResolutionPolicy createLastWriterWinsPolicy(String conflictResolutionPath) {
         ConflictResolutionPolicy policy = new ConflictResolutionPolicy();
-        policy.setMode(ConflictResolutionMode.LastWriterWins);
+        policy.mode(ConflictResolutionMode.LAST_WRITER_WINS);
         if (conflictResolutionPath != null) {
-            policy.setConflictResolutionPath(conflictResolutionPath);
+            policy.conflictResolutionPath(conflictResolutionPath);
         }
         return policy;
     }
 
     /**
-     * Creates a Custom {@link ConflictResolutionPolicy} which uses the specified stored procedure
+     * Creates a CUSTOM {@link ConflictResolutionPolicy} which uses the specified stored procedure
      * to perform conflict resolution
      *
      * This stored procedure may be created after the {@link DocumentCollection} is created and can be changed as required.
@@ -99,22 +100,22 @@ public static ConflictResolutionPolicy createLastWriterWinsPolicy(String conflic
      * 
    *
  • In case the stored procedure fails or throws an exception, * the conflict resolution will default to registering conflicts in the conflicts feed
  • - *
  • The user can provide the stored procedure @see {@link Resource#getId()}
  • + *
  • The user can provide the stored procedure @see {@link Resource#id()}
  • *
* @param conflictResolutionSprocName stored procedure to perform conflict resolution. * @return ConflictResolutionPolicy. */ public static ConflictResolutionPolicy createCustomPolicy(String conflictResolutionSprocName) { ConflictResolutionPolicy policy = new ConflictResolutionPolicy(); - policy.setMode(ConflictResolutionMode.Custom); + policy.mode(ConflictResolutionMode.CUSTOM); if (conflictResolutionSprocName != null) { - policy.setConflictResolutionProcedure(conflictResolutionSprocName); + policy.conflictResolutionProcedure(conflictResolutionSprocName); } return policy; } /** - * Creates a Custom {@link ConflictResolutionPolicy} without any {@link StoredProcedure}. User manually + * Creates a CUSTOM {@link ConflictResolutionPolicy} without any {@link StoredProcedure}. User manually * should resolve conflicts. * * The conflicts will be registered in the conflicts feed and the user should manually resolve them. @@ -123,7 +124,7 @@ public static ConflictResolutionPolicy createCustomPolicy(String conflictResolut */ public static ConflictResolutionPolicy createCustomPolicy() { ConflictResolutionPolicy policy = new ConflictResolutionPolicy(); - policy.setMode(ConflictResolutionMode.Custom); + policy.mode(ConflictResolutionMode.CUSTOM); return policy; } @@ -138,48 +139,49 @@ public ConflictResolutionPolicy(String jsonString) { /** * Gets the {@link ConflictResolutionMode} in the Azure Cosmos DB service. - * By default it is {@link ConflictResolutionMode#LastWriterWins}. + * By default it is {@link ConflictResolutionMode#LAST_WRITER_WINS}. * * @return ConflictResolutionMode. */ - public ConflictResolutionMode getConflictResolutionMode() { + public ConflictResolutionMode mode() { String strValue = super.getString(Constants.Properties.MODE); if (!Strings.isNullOrEmpty(strValue)) { try { - return ConflictResolutionMode.valueOf(WordUtils.capitalize(super.getString(Constants.Properties.MODE))); + return ConflictResolutionMode.valueOf(StringUtils.upperCase(super.getString(Constants.Properties.MODE))); } catch (IllegalArgumentException e) { - this.getLogger().warn("Invalid ConflictResolutionMode value {}.", super.getString(Constants.Properties.MODE)); - return ConflictResolutionMode.Invalid; + this.getLogger().warn("INVALID ConflictResolutionMode value {}.", super.getString(Constants.Properties.MODE)); + return ConflictResolutionMode.INVALID; } } - return ConflictResolutionMode.Invalid; + return ConflictResolutionMode.INVALID; } /** * Sets the {@link ConflictResolutionMode} in the Azure Cosmos DB service. - * By default it is {@link ConflictResolutionMode#LastWriterWins}. + * By default it is {@link ConflictResolutionMode#LAST_WRITER_WINS}. * * @param mode One of the values of the {@link ConflictResolutionMode} enum. */ - void setMode(ConflictResolutionMode mode) { + ConflictResolutionPolicy mode(ConflictResolutionMode mode) { super.set(Constants.Properties.MODE, mode.name()); + return this; } /** * Gets the path which is present in each document in the Azure Cosmos DB service for last writer wins conflict-resolution. * This path must be present in each document and must be an integer value. * In case of a conflict occurring on a document, the document with the higher integer value in the specified path will be picked. - * If the path is unspecified, by default the {@link Resource#getTimestamp()} path will be used. + * If the path is unspecified, by default the {@link Resource#timestamp()} path will be used. * - * This value should only be set when using {@link ConflictResolutionMode#LastWriterWins} + * This value should only be set when using {@link ConflictResolutionMode#LAST_WRITER_WINS} * * @return The path to check values for last-writer wins conflict resolution. * That path is a rooted path of the property in the document, such as "/name/first". */ - public String getConflictResolutionPath() { + public String conflictResolutionPath() { return super.getString(Constants.Properties.CONFLICT_RESOLUTION_PATH); } @@ -187,15 +189,16 @@ public String getConflictResolutionPath() { * Sets the path which is present in each document in the Azure Cosmos DB service for last writer wins conflict-resolution. * This path must be present in each document and must be an integer value. * In case of a conflict occurring on a document, the document with the higher integer value in the specified path will be picked. - * If the path is unspecified, by default the {@link Resource#getTimestamp()} path will be used. + * If the path is unspecified, by default the {@link Resource#timestamp()} path will be used. * - * This value should only be set when using {@link ConflictResolutionMode#LastWriterWins} + * This value should only be set when using {@link ConflictResolutionMode#LAST_WRITER_WINS} * * @param value The path to check values for last-writer wins conflict resolution. * That path is a rooted path of the property in the document, such as "/name/first". */ - void setConflictResolutionPath(String value) { + ConflictResolutionPolicy conflictResolutionPath(String value) { super.set(Constants.Properties.CONFLICT_RESOLUTION_PATH, value); + return this; } /** @@ -203,19 +206,20 @@ void setConflictResolutionPath(String value) { * This stored procedure may be created after the {@link DocumentCollection} is created and can be changed as required. * *
    - *
  • This value should only be set when using {@link ConflictResolutionMode#Custom}
  • + *
  • This value should only be set when using {@link ConflictResolutionMode#CUSTOM}
  • *
  • In case the stored procedure fails or throws an exception, * the conflict resolution will default to registering conflicts in the conflicts feed
  • - *
  • The user can provide the stored procedure @see {@link Resource#getId()}
  • + *
  • The user can provide the stored procedure @see {@link Resource#id()}
  • *
** * @return the stored procedure to perform conflict resolution.] */ - public String getConflictResolutionProcedure() { + public String conflictResolutionProcedure() { return super.getString(Constants.Properties.CONFLICT_RESOLUTION_PROCEDURE); } - void setConflictResolutionProcedure(String value) { + ConflictResolutionPolicy conflictResolutionProcedure(String value) { super.set(Constants.Properties.CONFLICT_RESOLUTION_PROCEDURE, value); + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConnectionMode.java b/commons/src/main/java/com/azure/data/cosmos/ConnectionMode.java similarity index 89% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ConnectionMode.java rename to commons/src/main/java/com/azure/data/cosmos/ConnectionMode.java index c534ef3394b7e..cc6d367d0af50 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConnectionMode.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConnectionMode.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Represents the connection mode to be used by the client in the Azure Cosmos DB database service. *

- * Direct and Gateway connectivity modes are supported. Gateway is the default. + * DIRECT and GATEWAY connectivity modes are supported. GATEWAY is the default. * Refer to <see>http://azure.microsoft.com/documentation/articles/documentdb- * interactions-with-resources/#connectivity-options</see> for additional * details. @@ -37,15 +37,15 @@ public enum ConnectionMode { /** * Specifies that requests to server resources are made through a gateway proxy using HTTPS. *

- * In Gateway mode, all requests are made through a gateway proxy. + * In GATEWAY mode, all requests are made through a gateway proxy. *

*/ - Gateway, + GATEWAY, /** * Specifies that requests to server resources are made directly to the data nodes. *

- * In Direct mode, all requests to server resources within a collection, such as documents, stored procedures + * In DIRECT mode, all requests to server resources within a collection, such as documents, stored procedures * and user-defined functions, etc., are made directly to the data nodes within the target Cosmos DB cluster * using either the HTTPS or TCP/SSL transport protocol. *

@@ -53,5 +53,5 @@ public enum ConnectionMode { * are always routed through the gateway using HTTPS. *

*/ - Direct + DIRECT } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConnectionPolicy.java b/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java similarity index 81% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ConnectionPolicy.java rename to commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java index 6409218e0515c..3e1ec68dbe8f2 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConnectionPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java @@ -21,10 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.net.InetSocketAddress; -import java.util.Collection; import java.util.Collections; import java.util.List; @@ -60,7 +59,7 @@ public final class ConnectionPolicy { * Constructor. */ public ConnectionPolicy() { - this.connectionMode = ConnectionMode.Gateway; + this.connectionMode = ConnectionMode.GATEWAY; this.enableReadRequestsFallback = null; this.idleConnectionTimeoutInMillis = DEFAULT_IDLE_CONNECTION_TIMEOUT_IN_MILLIS; this.maxPoolSize = DEFAULT_MAX_POOL_SIZE; @@ -76,7 +75,7 @@ public ConnectionPolicy() { * * @return the default connection policy. */ - public static ConnectionPolicy GetDefault() { + public static ConnectionPolicy defaultPolicy() { if (ConnectionPolicy.default_policy == null) { ConnectionPolicy.default_policy = new ConnectionPolicy(); } @@ -89,7 +88,7 @@ public static ConnectionPolicy GetDefault() { * * @return the request timeout in milliseconds. */ - public int getRequestTimeoutInMillis() { + public int requestTimeoutInMillis() { return this.requestTimeoutInMillis; } @@ -99,28 +98,9 @@ public int getRequestTimeoutInMillis() { * * @param requestTimeoutInMillis the request timeout in milliseconds. */ - public void setRequestTimeoutInMillis(int requestTimeoutInMillis) { + public ConnectionPolicy requestTimeoutInMillis(int requestTimeoutInMillis) { this.requestTimeoutInMillis = requestTimeoutInMillis; - } - - /** - * Gets or sets time to wait for response from network peer for attachment - * content (aka media) operations. - * - * @return the media request timeout in milliseconds. - */ - public int getMediaRequestTimeoutInMillis() { - return this.mediaRequestTimeoutInMillis; - } - - /** - * Gets or sets Time to wait for response from network peer for attachment - * content (aka media) operations. - * - * @param mediaRequestTimeoutInMillis the media request timeout in milliseconds. - */ - public void setMediaRequestTimeoutInMillis(int mediaRequestTimeoutInMillis) { - this.mediaRequestTimeoutInMillis = mediaRequestTimeoutInMillis; + return this; } /** @@ -128,7 +108,7 @@ public void setMediaRequestTimeoutInMillis(int mediaRequestTimeoutInMillis) { * * @return the connection mode. */ - public ConnectionMode getConnectionMode() { + public ConnectionMode connectionMode() { return this.connectionMode; } @@ -137,26 +117,9 @@ public ConnectionMode getConnectionMode() { * * @param connectionMode the connection mode. */ - public void setConnectionMode(ConnectionMode connectionMode) { + public ConnectionPolicy connectionMode(ConnectionMode connectionMode) { this.connectionMode = connectionMode; - } - - /** - * Gets the attachment content (aka media) download mode. - * - * @return the media read mode. - */ - public MediaReadMode getMediaReadMode() { - return this.mediaReadMode; - } - - /** - * Sets the attachment content (aka media) download mode. - * - * @param mediaReadMode the media read mode. - */ - public void setMediaReadMode(MediaReadMode mediaReadMode) { - this.mediaReadMode = mediaReadMode; + return this; } /** @@ -164,7 +127,7 @@ public void setMediaReadMode(MediaReadMode mediaReadMode) { * * @return connection pool size. */ - public int getMaxPoolSize() { + public int maxPoolSize() { return this.maxPoolSize; } @@ -174,8 +137,9 @@ public int getMaxPoolSize() { * * @param maxPoolSize The value of the connection pool size. */ - public void setMaxPoolSize(int maxPoolSize) { + public ConnectionPolicy maxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; + return this; } /** @@ -184,7 +148,7 @@ public void setMaxPoolSize(int maxPoolSize) { * * @return Idle connection timeout. */ - public int getIdleConnectionTimeoutInMillis() { + public int idleConnectionTimeoutInMillis() { return this.idleConnectionTimeoutInMillis; } @@ -194,8 +158,9 @@ public int getIdleConnectionTimeoutInMillis() { * * @param idleConnectionTimeoutInMillis the timeout for an idle connection in seconds. */ - public void setIdleConnectionTimeoutInMillis(int idleConnectionTimeoutInMillis) { + public ConnectionPolicy idleConnectionTimeoutInMillis(int idleConnectionTimeoutInMillis) { this.idleConnectionTimeoutInMillis = idleConnectionTimeoutInMillis; + return this; } /** @@ -203,7 +168,7 @@ public void setIdleConnectionTimeoutInMillis(int idleConnectionTimeoutInMillis) * * @return the value of user-agent suffix. */ - public String getUserAgentSuffix() { + public String userAgentSuffix() { return this.userAgentSuffix; } @@ -213,8 +178,9 @@ public String getUserAgentSuffix() { * @param userAgentSuffix The value to be appended to the user-agent header, this is * used for monitoring purposes. */ - public void setUserAgentSuffix(String userAgentSuffix) { + public ConnectionPolicy userAgentSuffix(String userAgentSuffix) { this.userAgentSuffix = userAgentSuffix; + return this; } /** @@ -222,7 +188,7 @@ public void setUserAgentSuffix(String userAgentSuffix) { * * @return the RetryOptions instance. */ - public RetryOptions getRetryOptions() { + public RetryOptions retryOptions() { return this.retryOptions; } @@ -236,12 +202,13 @@ public RetryOptions getRetryOptions() { * * @param retryOptions the RetryOptions instance. */ - public void setRetryOptions(RetryOptions retryOptions) { + public ConnectionPolicy retryOptions(RetryOptions retryOptions) { if (retryOptions == null) { throw new IllegalArgumentException("retryOptions value must not be null."); } this.retryOptions = retryOptions; + return this; } /** @@ -249,7 +216,7 @@ public void setRetryOptions(RetryOptions retryOptions) { * * @return whether endpoint discovery is enabled. */ - public boolean getEnableEndpointDiscovery() { + public boolean enableEndpointDiscovery() { return this.enableEndpointDiscovery; } @@ -264,8 +231,9 @@ public boolean getEnableEndpointDiscovery() { * * @param enableEndpointDiscovery true if EndpointDiscovery is enabled. */ - public void setEnableEndpointDiscovery(boolean enableEndpointDiscovery) { + public ConnectionPolicy enableEndpointDiscovery(boolean enableEndpointDiscovery) { this.enableEndpointDiscovery = enableEndpointDiscovery; + return this; } /** @@ -277,19 +245,19 @@ public void setEnableEndpointDiscovery(boolean enableEndpointDiscovery) { * to true has no effect until EnableMultipleWriteLocations in DatabaseAccount * is also set to true. * - * Default value is false indicating that writes are only directed to + * DEFAULT value is false indicating that writes are only directed to * first region in PreferredLocations property. * * @return flag to enable writes on any locations (regions) for geo-replicated database accounts. */ - public boolean isUsingMultipleWriteLocations() { + public boolean usingMultipleWriteLocations() { return this.usingMultipleWriteLocations; } /** * Gets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. * - * Default value is null. + * DEFAULT value is null. * * If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, * The default is false for Bounded Staleness. @@ -298,7 +266,7 @@ public boolean isUsingMultipleWriteLocations() { * * @return flag to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. */ - public Boolean isEnableReadRequestsFallback() { + public Boolean enableReadRequestsFallback() { return this.enableReadRequestsFallback; } @@ -311,19 +279,20 @@ public Boolean isEnableReadRequestsFallback() { * to true has no effect until EnableMultipleWriteLocations in DatabaseAccount * is also set to true. * - * Default value is false indicating that writes are only directed to + * DEFAULT value is false indicating that writes are only directed to * first region in PreferredLocations property. * * @param usingMultipleWriteLocations flag to enable writes on any locations (regions) for geo-replicated database accounts. */ - public void setUsingMultipleWriteLocations(boolean usingMultipleWriteLocations) { + public ConnectionPolicy usingMultipleWriteLocations(boolean usingMultipleWriteLocations) { this.usingMultipleWriteLocations = usingMultipleWriteLocations; + return this; } /** * Sets whether to allow for reads to go to multiple regions configured on an account of Azure Cosmos DB service. * - * Default value is null. + * DEFAULT value is null. * * If this property is not set, the default is true for all Consistency Levels other than Bounded Staleness, * The default is false for Bounded Staleness. @@ -332,8 +301,9 @@ public void setUsingMultipleWriteLocations(boolean usingMultipleWriteLocations) * * @param enableReadRequestsFallback flag to enable reads to go to multiple regions configured on an account of Azure Cosmos DB service. */ - public void setEnableReadRequestsFallback(Boolean enableReadRequestsFallback) { + public ConnectionPolicy enableReadRequestsFallback(Boolean enableReadRequestsFallback) { this.enableReadRequestsFallback = enableReadRequestsFallback; + return this; } /** @@ -341,7 +311,7 @@ public void setEnableReadRequestsFallback(Boolean enableReadRequestsFallback) { * * @return the list of preferred location. */ - public List getPreferredLocations() { + public List preferredLocations() { return this.preferredLocations != null ? preferredLocations : Collections.emptyList(); } @@ -357,8 +327,9 @@ public List getPreferredLocations() { * * @param preferredLocations the list of preferred locations. */ - public void setPreferredLocations(List preferredLocations) { + public ConnectionPolicy preferredLocations(List preferredLocations) { this.preferredLocations = preferredLocations; + return this; } /** @@ -366,7 +337,7 @@ public void setPreferredLocations(List preferredLocations) { * * @return the value of proxyHost. */ - public InetSocketAddress getProxy() { + public InetSocketAddress proxy() { return this.inetSocketProxyAddress; } @@ -376,8 +347,9 @@ public InetSocketAddress getProxy() { * @param proxyHost The proxy server host. * @param proxyPort The proxy server port. */ - public void setProxy(String proxyHost, int proxyPort) { + public ConnectionPolicy proxy(String proxyHost, int proxyPort) { this.inetSocketProxyAddress = new InetSocketAddress(proxyHost, proxyPort); + return this; } @Override diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConsistencyLevel.java b/commons/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java similarity index 78% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ConsistencyLevel.java rename to commons/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java index a7da6d28eb8a9..bafdb8803b952 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConsistencyLevel.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java @@ -21,43 +21,43 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Represents the consistency levels supported for Cosmos DB client operations in the Azure Cosmos DB database service. *

* The requested ConsistencyLevel must match or be weaker than that provisioned for the database account. Consistency - * levels by order of strength are Strong, BoundedStaleness, Session and Eventual. + * levels by order of strength are STRONG, BOUNDED_STALENESS, SESSION and EVENTUAL. */ public enum ConsistencyLevel { /** - * Strong Consistency guarantees that read operations always return the value that was last written. + * STRONG Consistency guarantees that read operations always return the value that was last written. */ - Strong, + STRONG, /** * Bounded Staleness guarantees that reads are not too out-of-date. This can be configured based on number of * operations (MaxStalenessPrefix) or time (MaxStalenessIntervalInSeconds) */ - BoundedStaleness, + BOUNDED_STALENESS, /** - * Session Consistency guarantees monotonic reads (you never read old data, then new, then old again), monotonic + * SESSION Consistency guarantees monotonic reads (you never read old data, then new, then old again), monotonic * writes (writes are ordered) and read your writes (your writes are immediately visible to your reads) within * any single session. */ - Session, + SESSION, /** - * Eventual Consistency guarantees that reads will return a subset of writes. All writes will be eventually be + * EVENTUAL Consistency guarantees that reads will return a subset of writes. ALL writes will be eventually be * available for reads. */ - Eventual, + EVENTUAL, /** - * ConsistentPrefix Consistency guarantees that reads will return some prefix of all writes with no gaps. All writes + * CONSISTENT_PREFIX Consistency guarantees that reads will return some prefix of all writes with no gaps. ALL writes * will be eventually be available for reads. */ - ConsistentPrefix + CONSISTENT_PREFIX } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConsistencyPolicy.java b/commons/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java similarity index 85% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ConsistencyPolicy.java rename to commons/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java index 141a6b1967958..f034eb8babb80 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ConsistencyPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java @@ -21,19 +21,20 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Encapsulates the settings for consistency policy in the Azure Cosmos DB database service. */ public final class ConsistencyPolicy extends JsonSerializable { private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL = - ConsistencyLevel.Session; + ConsistencyLevel.SESSION; private static final int DEFAULT_MAX_STALENESS_INTERVAL = 5; private static final int DEFAULT_MAX_STALENESS_PREFIX = 100; @@ -42,7 +43,7 @@ public final class ConsistencyPolicy extends JsonSerializable { /** * Constructor. */ - ConsistencyPolicy() { + public ConsistencyPolicy() { } /** @@ -64,7 +65,7 @@ public ConsistencyLevel getDefaultConsistencyLevel() { ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL; try { result = ConsistencyLevel.valueOf( - WordUtils.capitalize(super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL))); + StringUtils.upperCase(super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL))); } catch (IllegalArgumentException e) { // ignore the exception and return the default this.getLogger().warn("Unknown consistency level {}, value ignored.", super.getString(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL)); @@ -77,8 +78,9 @@ public ConsistencyLevel getDefaultConsistencyLevel() { * * @param level the consistency level. */ - public void setDefaultConsistencyLevel(ConsistencyLevel level) { + public ConsistencyPolicy defaultConsistencyLevel(ConsistencyLevel level) { super.set(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL, level.name()); + return this; } /** @@ -87,7 +89,7 @@ public void setDefaultConsistencyLevel(ConsistencyLevel level) { * * @return the max staleness prefix. */ - public int getMaxStalenessPrefix() { + public int maxStalenessPrefix() { Integer value = super.getInt(Constants.Properties.MAX_STALENESS_PREFIX); if (value == null) { return ConsistencyPolicy.DEFAULT_MAX_STALENESS_PREFIX; @@ -101,8 +103,9 @@ public int getMaxStalenessPrefix() { * * @param maxStalenessPrefix the max staleness prefix. */ - public void setMaxStalenessPrefix(int maxStalenessPrefix) { + public ConsistencyPolicy maxStalenessPrefix(int maxStalenessPrefix) { super.set(Constants.Properties.MAX_STALENESS_PREFIX, maxStalenessPrefix); + return this; } /** @@ -110,7 +113,7 @@ public void setMaxStalenessPrefix(int maxStalenessPrefix) { * * @return the max staleness prefix. */ - public int getMaxStalenessIntervalInSeconds() { + public int maxStalenessIntervalInSeconds() { Integer value = super.getInt(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS); if (value == null) { return ConsistencyPolicy.DEFAULT_MAX_STALENESS_INTERVAL; @@ -123,7 +126,8 @@ public int getMaxStalenessIntervalInSeconds() { * * @param maxStalenessIntervalInSeconds the max staleness interval in seconds. */ - public void setMaxStalenessIntervalInSeconds(int maxStalenessIntervalInSeconds) { + public ConsistencyPolicy maxStalenessIntervalInSeconds(int maxStalenessIntervalInSeconds) { super.set(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS, maxStalenessIntervalInSeconds); + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/DocumentClientException.java b/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java similarity index 73% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/DocumentClientException.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java index c9b6d4a99fd90..328d35d5b1db6 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/DocumentClientException.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.net.URI; import java.util.HashMap; @@ -29,24 +29,26 @@ import org.apache.commons.lang3.StringUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.HttpConstants; /** * This class defines a custom exception type for all operations on - * DocumentClient in the Azure Cosmos DB database service. Applications are expected to catch DocumentClientException - * and handle errors as appropriate when calling methods on DocumentClient. + * DocumentClient in the Azure Cosmos DB database service. Applications are + * expected to catch CosmosClientException and handle errors as appropriate when + * calling methods on DocumentClient. *

* Errors coming from the service during normal execution are converted to - * DocumentClientException before returning to the application with the following exception: + * CosmosClientException before returning to the application with the following + * exception: *

- * When a BE error is encountered during a QueryIterable<T> iteration, an IllegalStateException - * is thrown instead of DocumentClientException. + * When a BE error is encountered during a QueryIterable<T> iteration, an + * IllegalStateException is thrown instead of CosmosClientException. *

- * When a transport level error happens that request is not able to reach the service, - * an IllegalStateException is thrown instead of DocumentClientException. + * When a transport level error happens that request is not able to reach the + * service, an IllegalStateException is thrown instead of CosmosClientException. */ -public class DocumentClientException extends Exception { +public class CosmosClientException extends Exception { private static final long serialVersionUID = 1L; private Error error; @@ -60,22 +62,22 @@ public class DocumentClientException extends Exception { Map requestHeaders; /** - * Creates a new instance of the DocumentClientException class. + * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. */ - public DocumentClientException(int statusCode) { + public CosmosClientException(int statusCode) { this.statusCode = statusCode; this.responseHeaders = new HashMap<>(); } /** - * Creates a new instance of the DocumentClientException class. + * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. * @param errorMessage the error message. */ - public DocumentClientException(int statusCode, String errorMessage) { + public CosmosClientException(int statusCode, String errorMessage) { Error error = new Error(); error.set(Constants.Properties.MESSAGE, errorMessage); this.statusCode = statusCode; @@ -84,38 +86,40 @@ public DocumentClientException(int statusCode, String errorMessage) { } /** - * Creates a new instance of the DocumentClientException class. + * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. * @param innerException the original exception. */ - public DocumentClientException(int statusCode, Exception innerException) { + public CosmosClientException(int statusCode, Exception innerException) { super(innerException); this.statusCode = statusCode; this.responseHeaders = new HashMap<>(); } /** - * Creates a new instance of the DocumentClientException class. + * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. * @param errorResource the error resource object. * @param responseHeaders the response headers. */ - public DocumentClientException(int statusCode, Error errorResource, Map responseHeaders) { + public CosmosClientException(int statusCode, Error errorResource, Map responseHeaders) { this(null, statusCode, errorResource, responseHeaders); } /** - * Creates a new instance of the DocumentClientException class. + * Creates a new instance of the CosmosClientException class. * - * @param resourceAddress the address of the resource the request is associated with. + * @param resourceAddress the address of the resource the request is associated + * with. * @param statusCode the http status code of the response. * @param errorResource the error resource object. * @param responseHeaders the response headers. */ - public DocumentClientException(String resourceAddress, int statusCode, Error errorResource, Map responseHeaders) { + public CosmosClientException(String resourceAddress, int statusCode, Error errorResource, + Map responseHeaders) { super(errorResource == null ? null : errorResource.getMessage()); @@ -125,14 +129,18 @@ public DocumentClientException(String resourceAddress, int statusCode, Error err this.error = errorResource; } - /** Creates a new instance of the DocumentClientException class. + /** + * Creates a new instance of the CosmosClientException class. + * * @param message the string message. * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. - * @param resourceAddress the address of the resource the request is associated with. + * @param resourceAddress the address of the resource the request is associated + * with. */ - public DocumentClientException(String message, Exception exception, Map responseHeaders, int statusCode, String resourceAddress) { + public CosmosClientException(String message, Exception exception, Map responseHeaders, + int statusCode, String resourceAddress) { super(message, exception); @@ -144,9 +152,9 @@ public DocumentClientException(String message, Exception exception, Map getResponseHeaders() { + public Map responseHeaders() { return this.responseHeaders; } @@ -252,28 +260,24 @@ String getResourceAddress() { * * @return Client side request statistics associated with this exception. */ - public ClientSideRequestStatistics getClientSideRequestStatistics() { + public ClientSideRequestStatistics clientSideRequestStatistics() { return clientSideRequestStatistics; } - public void setClientSideRequestStatistics(ClientSideRequestStatistics clientSideRequestStatistics) { + // TODO: make private + public CosmosClientException clientSideRequestStatistics(ClientSideRequestStatistics clientSideRequestStatistics) { this.clientSideRequestStatistics = clientSideRequestStatistics; + return this; } @Override public String toString() { - return getClass().getSimpleName() + "{" + - "error=" + error + - ", resourceAddress='" + resourceAddress + '\'' + - ", statusCode=" + statusCode + - ", message=" + getMessage() + - ", getCauseInfo=" + getCauseInfo() + - ", responseHeaders=" + responseHeaders + - ", requestHeaders=" + requestHeaders + - '}'; + return getClass().getSimpleName() + "{" + "error=" + error + ", resourceAddress='" + resourceAddress + '\'' + + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + requestHeaders + '}'; } - String getInnerErrorMessage() { + String innerErrorMessage() { String innerErrorMessage = super.getMessage(); if (error != null) { innerErrorMessage = error.getMessage(); @@ -284,7 +288,7 @@ String getInnerErrorMessage() { return innerErrorMessage; } - private String getCauseInfo() { + private String causeInfo() { Throwable cause = getCause(); if (cause != null) { return String.format("[class: %s, message: %s]", cause.getClass(), cause.getMessage()); diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java similarity index 93% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java index cbed66e3bc830..5b0f7f2145e37 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java @@ -20,10 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.RequestOptions; +package com.azure.data.cosmos; /** * Encapsulates options that can be specified for a request issued to cosmos container. @@ -39,7 +36,7 @@ public class CosmosContainerRequestOptions extends CosmosRequestOptions { * * @return the throughput value. */ - public Integer getOfferThroughput() { + public Integer offerThroughput() { return offerThroughput; } @@ -61,7 +58,7 @@ public CosmosContainerRequestOptions offerThroughput(Integer offerThroughput) { * * @return true if PopulateQuotaInfo is enabled */ - public boolean isPopulateQuotaInfo() { + public boolean populateQuotaInfo() { return populateQuotaInfo; } @@ -83,7 +80,7 @@ public CosmosContainerRequestOptions populateQuotaInfo(boolean populateQuotaInfo * * @return the consistency level. */ - public ConsistencyLevel getConsistencyLevel() { + public ConsistencyLevel consistencyLevel() { return consistencyLevel; } @@ -103,7 +100,7 @@ public CosmosContainerRequestOptions consistencyLevel(ConsistencyLevel consisten * * @return the session token. */ - public String getSessionToken() { + public String sessionToken() { return sessionToken; } diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerSettings.java similarity index 85% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosContainerSettings.java index b5256f1915b71..420c6ad1f79b8 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosContainerSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerSettings.java @@ -20,16 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.ConflictResolutionPolicy; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.UniqueKeyPolicy; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; import java.util.ArrayList; import java.util.List; @@ -55,11 +48,11 @@ public class CosmosContainerSettings extends Resource { * @param partitionKeyPath partition key path */ public CosmosContainerSettings(String id, String partitionKeyPath) { - super.setId(id); + super.id(id); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add(partitionKeyPath); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); setPartitionKey(partitionKeyDef); } @@ -69,7 +62,7 @@ public CosmosContainerSettings(String id, String partitionKeyPath) { * @param partitionKeyDefinition the (@link PartitionKeyDefinition) */ public CosmosContainerSettings(String id, PartitionKeyDefinition partitionKeyDefinition) { - super.setId(id); + super.id(id); setPartitionKey(partitionKeyDefinition); } @@ -91,7 +84,7 @@ static List getFromV2Results(List r * * @return the indexing policy. */ - public IndexingPolicy getIndexingPolicy() { + public IndexingPolicy indexingPolicy() { if (this.indexingPolicy == null) { if (super.has(Constants.Properties.INDEXING_POLICY)) { this.indexingPolicy = super.getObject(Constants.Properties.INDEXING_POLICY, IndexingPolicy.class); @@ -108,12 +101,13 @@ public IndexingPolicy getIndexingPolicy() { * * @param indexingPolicy {@link IndexingPolicy} the indexing policy */ - public void setIndexingPolicy(IndexingPolicy indexingPolicy) { + public CosmosContainerSettings indexingPolicy(IndexingPolicy indexingPolicy) { if (indexingPolicy == null) { throw new IllegalArgumentException("IndexingPolicy cannot be null."); } this.indexingPolicy = indexingPolicy; super.set(Constants.Properties.INDEXING_POLICY, indexingPolicy); + return this; } /** @@ -121,7 +115,7 @@ public void setIndexingPolicy(IndexingPolicy indexingPolicy) { * * @return the unique key policy */ - public UniqueKeyPolicy getUniqueKeyPolicy() { + public UniqueKeyPolicy uniqueKeyPolicy() { // Thread safe lazy initialization for case when collection is cached (and is basically readonly). if (this.uniqueKeyPolicy == null) { @@ -140,13 +134,14 @@ public UniqueKeyPolicy getUniqueKeyPolicy() { * * @param uniqueKeyPolicy the unique key policy */ - public void setUniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) { + public CosmosContainerSettings uniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) { if (uniqueKeyPolicy == null) { throw new IllegalArgumentException("uniqueKeyPolicy cannot be null."); } this.uniqueKeyPolicy = uniqueKeyPolicy; super.set(Constants.Properties.UNIQUE_KEY_POLICY, uniqueKeyPolicy); + return this; } /** @@ -154,7 +149,7 @@ public void setUniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) { * * @return the partition key definition. */ - public PartitionKeyDefinition getPartitionKey() { + public PartitionKeyDefinition partitionKey() { if (this.partitionKeyDefinition == null) { if (super.has(Constants.Properties.PARTITION_KEY)) { @@ -172,12 +167,13 @@ public PartitionKeyDefinition getPartitionKey() { * * @param partitionKeyDefinition the partition key definition. */ - public void setPartitionKey(PartitionKeyDefinition partitionKeyDefinition) { + public CosmosContainerSettings setPartitionKey(PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition == null) { throw new IllegalArgumentException("partitionKey cannot be null."); } this.partitionKeyDefinition = partitionKeyDefinition; + return this; } /** @@ -186,7 +182,7 @@ public void setPartitionKey(PartitionKeyDefinition partitionKeyDefinition) { * * @return ConflictResolutionPolicy */ - public ConflictResolutionPolicy getConflictResolutionPolicy() { + public ConflictResolutionPolicy conflictResolutionPolicy() { return super.getObject(Constants.Properties.CONFLICT_RESOLUTION_POLICY, ConflictResolutionPolicy.class); } @@ -196,18 +192,19 @@ public ConflictResolutionPolicy getConflictResolutionPolicy() { * * @param value ConflictResolutionPolicy to be used. */ - public void setConflictResolutionPolicy(ConflictResolutionPolicy value) { + public CosmosContainerSettings conflictResolutionPolicy(ConflictResolutionPolicy value) { if (value == null) { throw new IllegalArgumentException("CONFLICT_RESOLUTION_POLICY cannot be null."); } super.set(Constants.Properties.CONFLICT_RESOLUTION_POLICY, value); + return this; } DocumentCollection getV2Collection(){ DocumentCollection collection = new DocumentCollection(this.toJson()); - collection.setPartitionKey(this.getPartitionKey()); - collection.setIndexingPolicy(this.getIndexingPolicy()); + collection.setPartitionKey(this.partitionKey()); + collection.setIndexingPolicy(this.indexingPolicy()); return collection; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java similarity index 94% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java index 8047375213272..d1586f31e21ac 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java @@ -20,9 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.RequestOptions; +package com.azure.data.cosmos; /** * Encapsulates options that can be specified for a request issued to cosmos database. @@ -35,7 +33,7 @@ public class CosmosDatabaseRequestOptions extends CosmosRequestOptions{ * * @return the throughput value. */ - public Integer getOfferThroughput() { + public Integer offerThroughput() { return offerThroughput; } diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseSettings.java similarity index 92% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseSettings.java index 6415bd16753b2..335c6758025eb 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseSettings.java @@ -20,11 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; +package com.azure.data.cosmos; import java.util.List; import java.util.stream.Collectors; @@ -44,7 +40,7 @@ public class CosmosDatabaseSettings extends Resource { * @param id id of the database */ public CosmosDatabaseSettings(String id) { - super.setId(id); + super.id(id); } CosmosDatabaseSettings(ResourceResponse response) { diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java b/commons/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java similarity index 90% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java index 1d286bc10dbc0..23c164d4e9fff 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosFeedResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java @@ -20,10 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Resource; +package com.azure.data.cosmos; import java.lang.reflect.InvocationTargetException; import java.util.List; @@ -34,7 +31,7 @@ public class CosmosFeedResponse { //Temporary code. Used for testing conversion(one old resource type to new in feed) CosmosFeedResponse(FeedResponse feedResponse, Class klass) { - results = feedResponse.getResults().stream().map(resource -> { + results = feedResponse.results().stream().map(resource -> { T item = null; try { item = klass.getConstructor(Resource.class).newInstance(resource); diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java similarity index 70% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java index 050d5136b373b..162685273ed5e 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java @@ -20,35 +20,34 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; import com.fasterxml.jackson.databind.ObjectMapper; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.Utils; +import com.azure.data.cosmos.internal.Utils; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; -public class CosmosItemSettings extends Resource { +public class CosmosItemProperties extends Resource { private static final ObjectMapper mapper = Utils.getSimpleObjectMapper(); /** - * Initialize an empty CosmosItemSettings object. + * Initialize an empty CosmosItemProperties object. */ - public CosmosItemSettings() {} + public CosmosItemProperties() { + } /** - * Initialize a CosmosItemSettings object from json string. + * Initialize a CosmosItemProperties object from json string. * * @param jsonString the json string that represents the document object. */ - public CosmosItemSettings(String jsonString) { + public CosmosItemProperties(String jsonString) { super(jsonString); } - + /** * fromObject returns Document for compatibility with V2 sdk * @@ -57,11 +56,11 @@ public CosmosItemSettings(String jsonString) { */ static Document fromObject(Object cosmosItem) { Document typedItem; - if (cosmosItem instanceof CosmosItemSettings) { - typedItem = new Document(((CosmosItemSettings) cosmosItem).toJson()); + if (cosmosItem instanceof CosmosItemProperties) { + typedItem = new Document(((CosmosItemProperties) cosmosItem).toJson()); } else { try { - return new Document(CosmosItemSettings.mapper.writeValueAsString(cosmosItem)); + return new Document(CosmosItemProperties.mapper.writeValueAsString(cosmosItem)); } catch (IOException e) { throw new IllegalArgumentException("Can't serialize the object into the json string", e); } @@ -69,8 +68,9 @@ static Document fromObject(Object cosmosItem) { return typedItem; } - static List getFromV2Results(List results) { - return results.stream().map(document -> new CosmosItemSettings(document.toJson())).collect(Collectors.toList()); + static List getFromV2Results(List results) { + return results.stream().map(document -> new CosmosItemProperties(document.toJson())) + .collect(Collectors.toList()); } public T getObject(Class klass) throws IOException { diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java similarity index 79% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java index bce7b56e5fcff..3b711d222d8fe 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosItemRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java @@ -20,12 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.IndexingDirective; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.RequestOptions; +package com.azure.data.cosmos; import java.util.List; @@ -54,9 +49,9 @@ public CosmosItemRequestOptions(){ public CosmosItemRequestOptions(Object partitionKey){ super(); if (partitionKey instanceof PartitionKey) { - setPartitionKey((PartitionKey) partitionKey); + partitionKey((PartitionKey) partitionKey); } else { - setPartitionKey(new PartitionKey(partitionKey)); + partitionKey(new PartitionKey(partitionKey)); } } @@ -65,7 +60,7 @@ public CosmosItemRequestOptions(Object partitionKey){ * * @return the consistency level. */ - public ConsistencyLevel getConsistencyLevel() { + public ConsistencyLevel consistencyLevel() { return consistencyLevel; } @@ -74,8 +69,9 @@ public ConsistencyLevel getConsistencyLevel() { * * @param consistencyLevel the consistency level. */ - public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { + public CosmosItemRequestOptions consistencyLevel(ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; + return this; } /** @@ -83,7 +79,7 @@ public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { * * @return the indexing directive. */ - public IndexingDirective getIndexingDirective() { + public IndexingDirective indexingDirective() { return indexingDirective; } @@ -92,8 +88,9 @@ public IndexingDirective getIndexingDirective() { * * @param indexingDirective the indexing directive. */ - public void setIndexingDirective(IndexingDirective indexingDirective) { + public CosmosItemRequestOptions indexingDirective(IndexingDirective indexingDirective) { this.indexingDirective = indexingDirective; + return this; } /** @@ -101,7 +98,7 @@ public void setIndexingDirective(IndexingDirective indexingDirective) { * * @return the triggers to be invoked before the operation. */ - public List getPreTriggerInclude() { + public List preTriggerInclude() { return preTriggerInclude; } @@ -110,8 +107,9 @@ public List getPreTriggerInclude() { * * @param preTriggerInclude the triggers to be invoked before the operation. */ - public void setPreTriggerInclude(List preTriggerInclude) { + public CosmosItemRequestOptions preTriggerInclude(List preTriggerInclude) { this.preTriggerInclude = preTriggerInclude; + return this; } /** @@ -119,7 +117,7 @@ public void setPreTriggerInclude(List preTriggerInclude) { * * @return the triggers to be invoked after the operation. */ - public List getPostTriggerInclude() { + public List postTriggerInclude() { return postTriggerInclude; } @@ -128,8 +126,9 @@ public List getPostTriggerInclude() { * * @param postTriggerInclude the triggers to be invoked after the operation. */ - public void setPostTriggerInclude(List postTriggerInclude) { + public CosmosItemRequestOptions postTriggerInclude(List postTriggerInclude) { this.postTriggerInclude = postTriggerInclude; + return this; } /** @@ -137,7 +136,7 @@ public void setPostTriggerInclude(List postTriggerInclude) { * * @return the session token. */ - public String getSessionToken() { + public String sessionToken() { return sessionToken; } @@ -146,23 +145,25 @@ public String getSessionToken() { * * @param sessionToken the session token. */ - public void setSessionToken(String sessionToken) { + public CosmosItemRequestOptions sessionToken(String sessionToken) { this.sessionToken = sessionToken; + return this; } /** * Sets the partition key * @param partitionKey the partition key */ - public void setPartitionKey(PartitionKey partitionKey) { + public CosmosItemRequestOptions partitionKey(PartitionKey partitionKey) { this.partitionKey = partitionKey; + return this; } /** * Gets the partition key * @return the partition key */ - public PartitionKey getPartitionKey() { + public PartitionKey partitionKey() { return partitionKey; } @@ -170,8 +171,8 @@ public PartitionKey getPartitionKey() { protected RequestOptions toRequestOptions() { //TODO: Should we set any default values instead of nulls? super.toRequestOptions(); - requestOptions.setAccessCondition(getAccessCondition()); - requestOptions.setConsistencyLevel(getConsistencyLevel()); + requestOptions.setAccessCondition(accessCondition()); + requestOptions.setConsistencyLevel(consistencyLevel()); requestOptions.setIndexingDirective(indexingDirective); requestOptions.setPreTriggerInclude(preTriggerInclude); requestOptions.setPostTriggerInclude(postTriggerInclude); diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java similarity index 91% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java index fb9df401c432f..df280140e774b 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java @@ -20,10 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.AccessCondition; -import com.microsoft.azure.cosmosdb.RequestOptions; +package com.azure.data.cosmos; /** * Encapsulates options that can be specified for a request @@ -37,7 +34,7 @@ public class CosmosRequestOptions { * * @return the access condition. */ - public AccessCondition getAccessCondition() { + public AccessCondition accessCondition() { return accessCondition; } diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java b/commons/src/main/java/com/azure/data/cosmos/CosmosResource.java similarity index 73% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosResource.java index 46e4c120e20bd..a6870a1cc17dd 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosResource.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosResource.java @@ -20,9 +20,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.Resource; import org.apache.commons.lang3.StringUtils; public abstract class CosmosResource { @@ -33,35 +32,36 @@ public CosmosResource(String id) { this.id = id; } - public String getId() { + public String id() { return id; } - protected void setId(String id) { + protected CosmosResource id(String id) { this.id = id; + return this; } - protected abstract String getURIPathSegment(); - protected abstract String getParentLink(); + protected abstract String URIPathSegment(); + protected abstract String parentLink(); String getLink() { StringBuilder builder = new StringBuilder(); - builder.append(getParentLink()); + builder.append(parentLink()); builder.append("/"); - builder.append(getURIPathSegment()); + builder.append(URIPathSegment()); builder.append("/"); - builder.append(getId()); + builder.append(id()); return builder.toString(); } protected static void validateResource(Resource resource) { - if (!StringUtils.isEmpty(resource.getId())) { - if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || - resource.getId().indexOf('?') != -1 || resource.getId().indexOf('#') != -1) { + if (!StringUtils.isEmpty(resource.id())) { + if (resource.id().indexOf('/') != -1 || resource.id().indexOf('\\') != -1 || + resource.id().indexOf('?') != -1 || resource.id().indexOf('#') != -1) { throw new IllegalArgumentException("Id contains illegal chars."); } - if (resource.getId().endsWith(" ")) { + if (resource.id().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/CosmosResourceType.java b/commons/src/main/java/com/azure/data/cosmos/CosmosResourceType.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/CosmosResourceType.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosResourceType.java index 11029c770a91e..dce4aa8475c12 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/CosmosResourceType.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosResourceType.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Resource types in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java b/commons/src/main/java/com/azure/data/cosmos/CosmosResponse.java similarity index 74% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosResponse.java index 8a74e286daacd..4ba731c3abe7f 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosResponse.java @@ -20,18 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ClientSideRequestStatistics; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.StoredProcedureResponse; +package com.azure.data.cosmos; import java.time.Duration; import java.util.Map; -import org.apache.commons.lang3.StringUtils; - public class CosmosResponse { private T resourceSettings; protected ResourceResponse resourceResponseWrapper; @@ -48,12 +41,13 @@ public class CosmosResponse { CosmosResponse(StoredProcedureResponse response) { } - protected T getResourceSettings() { + protected T resourceSettings() { return resourceSettings; } - protected void setResourceSettings(T resourceSettings){ + protected CosmosResponse resourceSettings(T resourceSettings){ this.resourceSettings = resourceSettings; + return this; } /** @@ -62,7 +56,7 @@ protected void setResourceSettings(T resourceSettings){ * * @return the max resource quota. */ - public String getMaxResourceQuota() { + public String maxResourceQuota() { return resourceResponseWrapper.getMaxResourceQuota(); } @@ -71,7 +65,7 @@ public String getMaxResourceQuota() { * * @return the current resource quota usage. */ - public String getCurrentResourceQuotaUsage() { + public String currentResourceQuotaUsage() { return resourceResponseWrapper.getCurrentResourceQuotaUsage(); } @@ -80,7 +74,7 @@ public String getCurrentResourceQuotaUsage() { * * @return the activity id. */ - public String getActivityId() { + public String activityId() { return resourceResponseWrapper.getActivityId(); } @@ -89,34 +83,16 @@ public String getActivityId() { * * @return the request charge. */ - public double getRequestCharge() { + public double requestCharge() { return resourceResponseWrapper.getRequestCharge(); } - /** - * Gets the progress of an index transformation, if one is underway. - * - * @return the progress of an index transformation. - */ - public long getIndexTransformationProgress() { - return resourceResponseWrapper.getIndexTransformationProgress(); - } - - /** - * Gets the progress of lazy indexing. - * - * @return the progress of lazy indexing. - */ - public long getLazyIndexingProgress() { - return resourceResponseWrapper.getLazyIndexingProgress(); - } - /** * Gets the HTTP status code associated with the response. * * @return the status code. */ - public int getStatusCode() { + public int statusCode() { return resourceResponseWrapper.getStatusCode(); } @@ -125,7 +101,7 @@ public int getStatusCode() { * * @return the session token. */ - public String getSessionToken(){ + public String sessionToken(){ return resourceResponseWrapper.getSessionToken(); } @@ -134,7 +110,7 @@ public String getSessionToken(){ * * @return the response headers. */ - public Map getResponseHeaders() { + public Map responseHeaders() { return resourceResponseWrapper.getResponseHeaders(); } @@ -143,7 +119,7 @@ public Map getResponseHeaders() { * * @return diagnostics information for the current request to Azure Cosmos DB service. */ - public String getRequestDiagnosticsString() { + public String requestDiagnosticsString() { return resourceResponseWrapper.getRequestDiagnosticsString(); } @@ -152,7 +128,7 @@ public String getRequestDiagnosticsString() { * * @return end-to-end request latency for the current request to Azure Cosmos DB service. */ - public Duration getRequestLatency() { + public Duration requestLatency() { return resourceResponseWrapper.getRequestLatency(); } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java similarity index 82% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java index 8294c4b4e6550..97b401dbab585 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java @@ -20,11 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.RequestOptions; +package com.azure.data.cosmos; /** * Encapsulates options that can be specified for a request issued to cosmos stored procedure. @@ -39,7 +35,7 @@ public class CosmosStoredProcedureRequestOptions extends CosmosRequestOptions { * * @return the consistency level. */ - public ConsistencyLevel getConsistencyLevel() { + public ConsistencyLevel consistencyLevel() { return consistencyLevel; } @@ -48,8 +44,9 @@ public ConsistencyLevel getConsistencyLevel() { * * @param consistencyLevel the consistency level. */ - public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { + public CosmosStoredProcedureRequestOptions consistencyLevel(ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; + return this; } /** @@ -57,7 +54,7 @@ public void setConsistencyLevel(ConsistencyLevel consistencyLevel) { * * @return the partition key value. */ - public PartitionKey getPartitionKey() { + public PartitionKey partitionKey() { return partitionKey; } @@ -66,8 +63,9 @@ public PartitionKey getPartitionKey() { * * @param partitionKey the partition key value. */ - public void setPartitionKey(PartitionKey partitionKey) { + public CosmosStoredProcedureRequestOptions partitionKey(PartitionKey partitionKey) { this.partitionKey = partitionKey; + return this; } /** @@ -75,7 +73,7 @@ public void setPartitionKey(PartitionKey partitionKey) { * * @return the session token. */ - public String getSessionToken() { + public String sessionToken() { return sessionToken; } @@ -84,14 +82,15 @@ public String getSessionToken() { * * @param sessionToken the session token. */ - public void setSessionToken(String sessionToken) { + public CosmosStoredProcedureRequestOptions sessionToken(String sessionToken) { this.sessionToken = sessionToken; + return this; } @Override protected RequestOptions toRequestOptions() { super.toRequestOptions(); - requestOptions.setConsistencyLevel(getConsistencyLevel()); + requestOptions.setConsistencyLevel(consistencyLevel()); requestOptions.setPartitionKey(partitionKey); requestOptions.setSessionToken(sessionToken); return requestOptions; diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureSettings.java similarity index 68% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureSettings.java index 3cd5ccda352ff..1df8bf20f89a7 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureSettings.java @@ -20,18 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.StoredProcedure; +import com.azure.data.cosmos.internal.Constants; import java.util.List; import java.util.stream.Collectors; -public class CosmosStoredProcedureSettings extends StoredProcedure { +public class CosmosStoredProcedureSettings extends Resource { /** - * Constructor + * Constructor. + * */ public CosmosStoredProcedureSettings() { super(); @@ -46,10 +46,40 @@ public CosmosStoredProcedureSettings(String jsonString) { super(jsonString); } + /** + * Constructor. + * + * @param id the id of the stored procedure + * @param body the body of the stored procedure + */ + public CosmosStoredProcedureSettings(String id, String body) { + super(); + super.id(id); + this.body(body); + } + CosmosStoredProcedureSettings(ResourceResponse response) { super(response.getResource().toJson()); } + /** + * Get the body of the stored procedure. + * + * @return the body of the stored procedure. + */ + public String body() { + return super.getString(Constants.Properties.BODY); + } + + /** + * Set the body of the stored procedure. + * + * @param body the body of the stored procedure. + */ + public void body(String body) { + super.set(Constants.Properties.BODY, body); + } + static List getFromV2Results(List results) { return results.stream().map(sproc -> new CosmosStoredProcedureSettings(sproc.toJson())).collect(Collectors.toList()); diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java new file mode 100644 index 0000000000000..9b091919d0ae7 --- /dev/null +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java @@ -0,0 +1,130 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +import com.azure.data.cosmos.internal.Constants; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.WordUtils; + +import java.util.List; +import java.util.stream.Collectors; + +public class CosmosTriggerSettings extends Resource { + + /** + * Constructor + */ + public CosmosTriggerSettings(){ + super(); + } + + /** + * Constructor. + * + * @param jsonString the json string that represents the trigger settings. + */ + public CosmosTriggerSettings(String jsonString){ + super(jsonString); + } + + CosmosTriggerSettings(ResourceResponse response) { + super(response.getResource().toJson()); + } + + /** + * Get the body of the trigger. + * + * @return the body of the trigger. + */ + public String body() { + return super.getString(Constants.Properties.BODY); + } + + /** + * Set the body of the trigger. + * + * @param body the body of the trigger. + */ + public CosmosTriggerSettings body(String body) { + super.set(Constants.Properties.BODY, body); + return this; + } + + /** + * Get the type of the trigger. + * + * @return the trigger type. + */ + public TriggerType triggerType() { + TriggerType result = TriggerType.PRE; + try { + result = TriggerType.valueOf( + StringUtils.upperCase(super.getString(Constants.Properties.TRIGGER_TYPE))); + } catch (IllegalArgumentException e) { + // ignore the exception and return the default + this.getLogger().warn("INVALID triggerType value {}.", super.getString(Constants.Properties.TRIGGER_TYPE)); + } + return result; + } + + /** + * Set the type of the resource. + * + * @param triggerType the trigger type. + */ + public CosmosTriggerSettings triggerType(TriggerType triggerType) { + super.set(Constants.Properties.TRIGGER_TYPE, triggerType.name()); + return this; + } + + /** + * Get the operation type of the trigger. + * + * @return the trigger operation. + */ + public TriggerOperation triggerOperation() { + TriggerOperation result = TriggerOperation.CREATE; + try { + result = TriggerOperation.valueOf( + StringUtils.upperCase(super.getString(Constants.Properties.TRIGGER_OPERATION))); + } catch (IllegalArgumentException e) { + // ignore the exception and return the default + this.getLogger().warn("INVALID triggerOperation value {}.", super.getString(Constants.Properties.TRIGGER_OPERATION)); + } + return result; + } + + /** + * Set the operation type of the trigger. + * + * @param triggerOperation the trigger operation. + */ + public CosmosTriggerSettings triggerOperation(TriggerOperation triggerOperation) { + super.set(Constants.Properties.TRIGGER_OPERATION, triggerOperation.name()); + return this; + } + + static List getFromV2Results(List results) { + return results.stream().map(trigger -> new CosmosTriggerSettings(trigger.toJson())).collect(Collectors.toList()); + } +} diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java similarity index 76% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java index f85cd6f765e00..4b5618af7f15c 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java @@ -20,15 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; +import com.azure.data.cosmos.internal.Constants; import java.util.List; import java.util.stream.Collectors; -public class CosmosUserDefinedFunctionSettings extends UserDefinedFunction { +public class CosmosUserDefinedFunctionSettings extends Resource { /** * Constructor @@ -50,6 +49,25 @@ public CosmosUserDefinedFunctionSettings(String jsonString) { super(jsonString); } + /** + * Get the body of the user defined function. + * + * @return the body. + */ + public String body() { + return super.getString(Constants.Properties.BODY); + } + + /** + * Set the body of the user defined function. + * + * @param body the body. + */ + public CosmosUserDefinedFunctionSettings body(String body) { + super.set(Constants.Properties.BODY, body); + return this; + } + static List getFromV2Results(List results) { return results.stream().map(udf -> new CosmosUserDefinedFunctionSettings(udf.toJson())).collect(Collectors.toList()); } diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java similarity index 80% rename from commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java index cc81ad0d96e6d..cbc7003a99c6d 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java @@ -1,13 +1,9 @@ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; import java.util.List; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; public class CosmosUserSettings extends Resource { /** @@ -41,7 +37,7 @@ public CosmosUserSettings(String jsonString) { * @return the permissions link. */ public String getPermissionsLink() { - String selfLink = this.getSelfLink(); + String selfLink = this.selfLink(); if (selfLink.endsWith("/")) { return selfLink + super.getString(Constants.Properties.PERMISSIONS_LINK); } else { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/DataType.java b/commons/src/main/java/com/azure/data/cosmos/DataType.java similarity index 93% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/DataType.java rename to commons/src/main/java/com/azure/data/cosmos/DataType.java index 9ff43f876835b..d5a7a211ffd77 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/DataType.java +++ b/commons/src/main/java/com/azure/data/cosmos/DataType.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Data types in the Azure Cosmos DB database service. @@ -30,30 +30,30 @@ public enum DataType { /** * Represents a numeric data type. */ - Number, + NUMBER, /** * Represents a string data type. */ - String, + STRING, /** * Represent a point data type. */ - Point, + POINT, /** * Represents a line string data type. */ - LineString, + LINE_STRING, /** * Represent a polygon data type. */ - Polygon, + POLYGON, /** * Represent a multi-polygon data type. */ - MultiPolygon + MULTI_POLYGON } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Database.java b/commons/src/main/java/com/azure/data/cosmos/Database.java similarity index 92% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Database.java rename to commons/src/main/java/com/azure/data/cosmos/Database.java index 118eef88cf388..cd9c47da17777 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Database.java +++ b/commons/src/main/java/com/azure/data/cosmos/Database.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import org.apache.commons.lang3.StringUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents a Database in the Azure Cosmos DB database service. A database manages users, permissions and a set of collections @@ -60,7 +60,7 @@ public Database(String jsonString) { */ public String getCollectionsLink() { return String.format("%s/%s", - StringUtils.stripEnd(super.getSelfLink(), "/"), + StringUtils.stripEnd(super.selfLink(), "/"), super.getString(Constants.Properties.COLLECTIONS_LINK)); } @@ -71,7 +71,7 @@ public String getCollectionsLink() { */ public String getUsersLink() { return String.format("%s/%s", - StringUtils.stripEnd(super.getSelfLink(), "/"), + StringUtils.stripEnd(super.selfLink(), "/"), super.getString(Constants.Properties.USERS_LINK)); } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/DatabaseAccount.java b/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/DatabaseAccount.java rename to commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java index a8ce58bb977a4..7aba691ef7450 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/DatabaseAccount.java +++ b/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import com.fasterxml.jackson.core.type.TypeReference; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.Utils; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.Utils; import java.io.IOException; import java.util.HashMap; @@ -50,7 +50,7 @@ public class DatabaseAccount extends Resource { * Constructor. */ DatabaseAccount() { - this.setSelfLink(""); + this.selfLink(""); } /** diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/DatabaseAccountLocation.java b/commons/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java similarity index 94% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/DatabaseAccountLocation.java rename to commons/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java index 2ee1cca92a09d..bf743f7f8d69b 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/DatabaseAccountLocation.java +++ b/commons/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents the location of a database account in the Azure Cosmos DB database service. @@ -31,7 +31,7 @@ public class DatabaseAccountLocation extends JsonSerializable { /** - * Default Constructor. Creates a new instance of the + * DEFAULT Constructor. Creates a new instance of the * DatabaseAccountLocation object. */ DatabaseAccountLocation() { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Document.java b/commons/src/main/java/com/azure/data/cosmos/Document.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Document.java rename to commons/src/main/java/com/azure/data/cosmos/Document.java index 59e77a5ede98f..cb6db23dda37d 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Document.java +++ b/commons/src/main/java/com/azure/data/cosmos/Document.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents a document in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/DocumentCollection.java b/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/DocumentCollection.java rename to commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java index 351b483e0dc5d..a352b0184e457 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/DocumentCollection.java +++ b/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; import org.apache.commons.lang3.StringUtils; /** @@ -215,7 +215,7 @@ public void setConflictResolutionPolicy(ConflictResolutionPolicy value) { */ public String getDocumentsLink() { return String.format("%s/%s", - StringUtils.stripEnd(super.getSelfLink(), "/"), + StringUtils.stripEnd(super.selfLink(), "/"), super.getString(Constants.Properties.DOCUMENTS_LINK)); } @@ -226,7 +226,7 @@ public String getDocumentsLink() { */ public String getStoredProceduresLink() { return String.format("%s/%s", - StringUtils.stripEnd(super.getSelfLink(), "/"), + StringUtils.stripEnd(super.selfLink(), "/"), super.getString(Constants.Properties.STORED_PROCEDURES_LINK)); } @@ -236,7 +236,7 @@ public String getStoredProceduresLink() { * @return the trigger link. */ public String getTriggersLink() { - return StringUtils.removeEnd(this.getSelfLink(), "/") + + return StringUtils.removeEnd(this.selfLink(), "/") + "/" + super.getString(Constants.Properties.TRIGGERS_LINK); } @@ -246,7 +246,7 @@ public String getTriggersLink() { * @return the user defined functions link. */ public String getUserDefinedFunctionsLink() { - return StringUtils.removeEnd(this.getSelfLink(), "/") + + return StringUtils.removeEnd(this.selfLink(), "/") + "/" + super.getString(Constants.Properties.USER_DEFINED_FUNCTIONS_LINK); } @@ -256,7 +256,7 @@ public String getUserDefinedFunctionsLink() { * @return the conflicts link. */ public String getConflictsLink() { - return StringUtils.removeEnd(this.getSelfLink(), "/") + + return StringUtils.removeEnd(this.selfLink(), "/") + "/" + super.getString(Constants.Properties.CONFLICTS_LINK); } @@ -287,11 +287,11 @@ public boolean equals(Object obj) { } DocumentCollection typedObj = (DocumentCollection) obj; - return typedObj.getResourceId().equals(this.getResourceId()); + return typedObj.resourceId().equals(this.resourceId()); } @Override public int hashCode() { - return this.getResourceId().hashCode(); + return this.resourceId().hashCode(); } } \ No newline at end of file diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Error.java b/commons/src/main/java/com/azure/data/cosmos/Error.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Error.java rename to commons/src/main/java/com/azure/data/cosmos/Error.java index 8923700be3c2c..80480af7dba68 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Error.java +++ b/commons/src/main/java/com/azure/data/cosmos/Error.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Encapsulates error related details in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ExcludedPath.java b/commons/src/main/java/com/azure/data/cosmos/ExcludedPath.java similarity index 91% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ExcludedPath.java rename to commons/src/main/java/com/azure/data/cosmos/ExcludedPath.java index 58cb1835d70d4..0aa4a9edaf630 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ExcludedPath.java +++ b/commons/src/main/java/com/azure/data/cosmos/ExcludedPath.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents an excluded path of the IndexingPolicy in the Azure Cosmos DB database service. @@ -51,7 +51,7 @@ public ExcludedPath(String jsonString) { * * @return the path. */ - public String getPath() { + public String path() { return super.getString(Constants.Properties.PATH); } @@ -60,7 +60,8 @@ public String getPath() { * * @param path the path. */ - public void setPath(String path) { + public ExcludedPath path(String path) { super.set(Constants.Properties.PATH, path); + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/FeedOptions.java b/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java similarity index 67% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/FeedOptions.java rename to commons/src/main/java/com/azure/data/cosmos/FeedOptions.java index d0fd538ade3ba..4a656f2182aeb 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/FeedOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java @@ -21,10 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** - * Specifies the options associated with feed methods (enumeration operations) in the Azure Cosmos DB database service. + * Specifies the options associated with feed methods (enumeration operations) + * in the Azure Cosmos DB database service. */ public final class FeedOptions extends FeedOptionsBase { private String sessionToken; @@ -36,7 +37,8 @@ public final class FeedOptions extends FeedOptionsBase { private int maxBufferedItemCount; private int responseContinuationTokenLimitInKb; - public FeedOptions() {} + public FeedOptions() { + } public FeedOptions(FeedOptions options) { super(options); @@ -55,18 +57,19 @@ public FeedOptions(FeedOptions options) { * * @return the partitionKeyRangeId. */ - public String getPartitionKeyRangeIdInternal() { + public String partitionKeyRangeIdInternal() { return this.partitionKeyRangeId; } + // TODO: make private /** * Sets the partitionKeyRangeId. * - * @param partitionKeyRangeId - * the partitionKeyRangeId. + * @param partitionKeyRangeId the partitionKeyRangeId. */ - public void setPartitionKeyRangeIdInternal(String partitionKeyRangeId) { + public FeedOptions partitionKeyRangeIdInternal(String partitionKeyRangeId) { this.partitionKeyRangeId = partitionKeyRangeId; + return this; } /** @@ -74,18 +77,18 @@ public void setPartitionKeyRangeIdInternal(String partitionKeyRangeId) { * * @return the session token. */ - public String getSessionToken() { + public String sessionToken() { return this.sessionToken; } /** * Sets the session token for use with session consistency. * - * @param sessionToken - * the session token. + * @param sessionToken the session token. */ - public void setSessionToken(String sessionToken) { + public FeedOptions sessionToken(String sessionToken) { this.sessionToken = sessionToken; + return this; } /** @@ -94,7 +97,7 @@ public void setSessionToken(String sessionToken) { * * @return the option of enable scan in query. */ - public Boolean getEnableScanInQuery() { + public Boolean enableScanInQuery() { return this.enableScanInQuery; } @@ -102,11 +105,11 @@ public Boolean getEnableScanInQuery() { * Sets the option to allow scan on the queries which couldn't be served as * indexing was opted out on the requested paths. * - * @param enableScanInQuery - * the option of enable scan in query. + * @param enableScanInQuery the option of enable scan in query. */ - public void setEnableScanInQuery(Boolean enableScanInQuery) { + public FeedOptions enableScanInQuery(Boolean enableScanInQuery) { this.enableScanInQuery = enableScanInQuery; + return this; } /** @@ -115,7 +118,7 @@ public void setEnableScanInQuery(Boolean enableScanInQuery) { * * @return the emit verbose traces in query. */ - public Boolean getEmitVerboseTracesInQuery() { + public Boolean emitVerboseTracesInQuery() { return this.emitVerboseTracesInQuery; } @@ -123,11 +126,11 @@ public Boolean getEmitVerboseTracesInQuery() { * Sets the option to allow queries to emit out verbose traces for * investigation. * - * @param emitVerboseTracesInQuery - * the emit verbose traces in query. + * @param emitVerboseTracesInQuery the emit verbose traces in query. */ - public void setEmitVerboseTracesInQuery(Boolean emitVerboseTracesInQuery) { + public FeedOptions emitVerboseTracesInQuery(Boolean emitVerboseTracesInQuery) { this.emitVerboseTracesInQuery = emitVerboseTracesInQuery; + return this; } /** @@ -137,7 +140,7 @@ public void setEmitVerboseTracesInQuery(Boolean emitVerboseTracesInQuery) { * @return whether to allow queries to run across all partitions of the * collection. */ - public Boolean getEnableCrossPartitionQuery() { + public Boolean enableCrossPartitionQuery() { return this.enableCrossPartitionQuery; } @@ -145,22 +148,22 @@ public Boolean getEnableCrossPartitionQuery() { * Sets the option to allow queries to run across all partitions of the * collection. * - * @param enableCrossPartitionQuery - * whether to allow queries to run across all partitions of the - * collection. + * @param enableCrossPartitionQuery whether to allow queries to run across all + * partitions of the collection. */ - public void setEnableCrossPartitionQuery(Boolean enableCrossPartitionQuery) { + public FeedOptions enableCrossPartitionQuery(Boolean enableCrossPartitionQuery) { this.enableCrossPartitionQuery = enableCrossPartitionQuery; + return this; } /** * Gets the number of concurrent operations run client side during parallel * query execution. * - * @return number of concurrent operations run client side during parallel - * query execution. + * @return number of concurrent operations run client side during parallel query + * execution. */ - public int getMaxDegreeOfParallelism() { + public int maxDegreeOfParallelism() { return maxDegreeOfParallelism; } @@ -168,11 +171,11 @@ public int getMaxDegreeOfParallelism() { * Sets the number of concurrent operations run client side during parallel * query execution. * - * @param maxDegreeOfParallelism - * number of concurrent operations. + * @param maxDegreeOfParallelism number of concurrent operations. */ - public void setMaxDegreeOfParallelism(int maxDegreeOfParallelism) { + public FeedOptions maxDegreeOfParallelism(int maxDegreeOfParallelism) { this.maxDegreeOfParallelism = maxDegreeOfParallelism; + return this; } /** @@ -182,7 +185,7 @@ public void setMaxDegreeOfParallelism(int maxDegreeOfParallelism) { * @return maximum number of items that can be buffered client side during * parallel query execution. */ - public int getMaxBufferedItemCount() { + public int maxBufferedItemCount() { return maxBufferedItemCount; } @@ -190,43 +193,47 @@ public int getMaxBufferedItemCount() { * Sets the maximum number of items that can be buffered client side during * parallel query execution. * - * @param maxBufferedItemCount - * maximum number of items. + * @param maxBufferedItemCount maximum number of items. */ - public void setMaxBufferedItemCount(int maxBufferedItemCount) { + public FeedOptions maxBufferedItemCount(int maxBufferedItemCount) { this.maxBufferedItemCount = maxBufferedItemCount; + return this; } /** - * Sets the ResponseContinuationTokenLimitInKb request option for document query requests - * in the Azure Cosmos DB service. + * Sets the ResponseContinuationTokenLimitInKb request option for document query + * requests in the Azure Cosmos DB service. * - * ResponseContinuationTokenLimitInKb is used to limit the length of continuation token in the query response. - * Valid values are >= 1. + * ResponseContinuationTokenLimitInKb is used to limit the length of + * continuation token in the query response. Valid values are >= 1. * - * The continuation token contains both required and optional fields. - * The required fields are necessary for resuming the execution from where it was stooped. - * The optional fields may contain serialized index lookup work that was done but not yet utilized. - * This avoids redoing the work again in subsequent continuations and hence improve the query performance. - * Setting the maximum continuation size to 1KB, the Azure Cosmos DB service will only serialize required fields. - * Starting from 2KB, the Azure Cosmos DB service would serialize as much as it could fit till it reaches the maximum specified size. + * The continuation token contains both required and optional fields. The + * required fields are necessary for resuming the execution from where it was + * stooped. The optional fields may contain serialized index lookup work that + * was done but not yet utilized. This avoids redoing the work again in + * subsequent continuations and hence improve the query performance. Setting the + * maximum continuation size to 1KB, the Azure Cosmos DB service will only + * serialize required fields. Starting from 2KB, the Azure Cosmos DB service + * would serialize as much as it could fit till it reaches the maximum specified + * size. * * @param limitInKb continuation token size limit. */ - public void setResponseContinuationTokenLimitInKb(int limitInKb) { + public FeedOptions responseContinuationTokenLimitInKb(int limitInKb) { this.responseContinuationTokenLimitInKb = limitInKb; + return this; } /** - * Gets the ResponseContinuationTokenLimitInKb request option for document query requests - * in the Azure Cosmos DB service. If not already set returns 0. + * Gets the ResponseContinuationTokenLimitInKb request option for document query + * requests in the Azure Cosmos DB service. If not already set returns 0. * - * ResponseContinuationTokenLimitInKb is used to limit the length of continuation token in the query response. - * Valid values are >= 1. + * ResponseContinuationTokenLimitInKb is used to limit the length of + * continuation token in the query response. Valid values are >= 1. * * @return return set ResponseContinuationTokenLimitInKb, or 0 if not set */ - public int getResponseContinuationTokenLimitInKb() { + public int responseContinuationTokenLimitInKb() { return responseContinuationTokenLimitInKb; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/FeedOptionsBase.java b/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java similarity index 84% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/FeedOptionsBase.java rename to commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java index d2edb4cf433fa..304b7c32b236a 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/FeedOptionsBase.java +++ b/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.Map; @@ -50,7 +50,7 @@ protected FeedOptionsBase() {} * * @return the max number of items. */ - public Integer getMaxItemCount() { + public Integer maxItemCount() { return this.maxItemCount; } @@ -60,8 +60,9 @@ public Integer getMaxItemCount() { * * @param maxItemCount the max number of items. */ - public void setMaxItemCount(Integer maxItemCount) { + public FeedOptionsBase maxItemCount(Integer maxItemCount) { this.maxItemCount = maxItemCount; + return this; } /** @@ -69,7 +70,7 @@ public void setMaxItemCount(Integer maxItemCount) { * * @return the request continuation. */ - public String getRequestContinuation() { + public String requestContinuation() { return this.requestContinuation; } @@ -79,8 +80,9 @@ public String getRequestContinuation() { * @param requestContinuation * the request continuation. */ - public void setRequestContinuation(String requestContinuation) { + public FeedOptionsBase requestContinuation(String requestContinuation) { this.requestContinuation = requestContinuation; + return this; } /** @@ -89,7 +91,7 @@ public void setRequestContinuation(String requestContinuation) { * * @return the partition key. */ - public PartitionKey getPartitionKey() { + public PartitionKey partitionKey() { return this.partitionkey; } @@ -100,15 +102,16 @@ public PartitionKey getPartitionKey() { * @param partitionkey * the partition key value. */ - public void setPartitionKey(PartitionKey partitionkey) { + public FeedOptionsBase partitionKey(PartitionKey partitionkey) { this.partitionkey = partitionkey; + return this; } /** * Gets the option to enable populate query metrics * @return whether to enable populate query metrics */ - public boolean getPopulateQueryMetrics() { + public boolean populateQueryMetrics() { return populateQueryMetrics; } @@ -116,8 +119,9 @@ public boolean getPopulateQueryMetrics() { * Sets the option to enable/disable getting metrics relating to query execution on document query requests * @param populateQueryMetrics whether to enable or disable query metrics */ - public void setPopulateQueryMetrics(boolean populateQueryMetrics) { + public FeedOptionsBase populateQueryMetrics(boolean populateQueryMetrics) { this.populateQueryMetrics = populateQueryMetrics; + return this; } /** @@ -125,7 +129,7 @@ public void setPopulateQueryMetrics(boolean populateQueryMetrics) { * * @return Map of request options properties */ - public Map getProperties() { + public Map properties() { return properties; } @@ -134,7 +138,8 @@ public Map getProperties() { * * @param properties the properties. */ - public void setProperties(Map properties) { + public FeedOptionsBase properties(Map properties) { this.properties = properties; + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/FeedResponse.java b/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java similarity index 78% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/FeedResponse.java rename to commons/src/main/java/com/azure/data/cosmos/FeedResponse.java index 3ce9c19ed4eca..38b17e5a8c5c8 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/FeedResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.HashMap; import java.util.List; @@ -31,10 +31,10 @@ import org.apache.commons.lang3.StringUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.HttpConstants; -public class FeedResponse { +public class FeedResponse { private final List results; private final Map header; @@ -79,7 +79,7 @@ private FeedResponse( * * @return the list of results. */ - public List getResults() { + public List results() { return results; } @@ -88,8 +88,8 @@ public List getResults() { * * @return The maximum quota for the account. */ - public long getDatabaseQuota() { - return this.getMaxQuotaHeader(Constants.Quota.DATABASE); + public long databaseQuota() { + return this.maxQuotaHeader(Constants.Quota.DATABASE); } /** @@ -97,8 +97,8 @@ public long getDatabaseQuota() { * * @return The current number of databases. */ - public long getDatabaseUsage() { - return this.getCurrentQuotaHeader(Constants.Quota.DATABASE); + public long databaseUsage() { + return this.currentQuotaHeader(Constants.Quota.DATABASE); } /** @@ -106,8 +106,8 @@ public long getDatabaseUsage() { * * @return The maximum quota for the account. */ - public long getCollectionQuota() { - return this.getMaxQuotaHeader(Constants.Quota.COLLECTION); + public long collectionQuota() { + return this.maxQuotaHeader(Constants.Quota.COLLECTION); } /** @@ -115,8 +115,8 @@ public long getCollectionQuota() { * * @return The current number of collections. */ - public long getCollectionUsage() { - return this.getCurrentQuotaHeader(Constants.Quota.COLLECTION); + public long collectionUsage() { + return this.currentQuotaHeader(Constants.Quota.COLLECTION); } /** @@ -124,8 +124,8 @@ public long getCollectionUsage() { * * @return The maximum quota for the account. */ - public long getUserQuota() { - return this.getMaxQuotaHeader(Constants.Quota.USER); + public long userQuota() { + return this.maxQuotaHeader(Constants.Quota.USER); } /** @@ -133,8 +133,8 @@ public long getUserQuota() { * * @return The current number of users. */ - public long getUserUsage() { - return this.getCurrentQuotaHeader(Constants.Quota.USER); + public long userUsage() { + return this.currentQuotaHeader(Constants.Quota.USER); } /** @@ -142,8 +142,8 @@ public long getUserUsage() { * * @return The maximum quota for the account. */ - public long getPermissionQuota() { - return this.getMaxQuotaHeader(Constants.Quota.PERMISSION); + public long permissionQuota() { + return this.maxQuotaHeader(Constants.Quota.PERMISSION); } /** @@ -151,8 +151,8 @@ public long getPermissionQuota() { * * @return The current number of permissions. */ - public long getPermissionUsage() { - return this.getCurrentQuotaHeader(Constants.Quota.PERMISSION); + public long permissionUsage() { + return this.currentQuotaHeader(Constants.Quota.PERMISSION); } /** @@ -160,8 +160,8 @@ public long getPermissionUsage() { * * @return The maximum quota in kilobytes. */ - public long getCollectionSizeQuota() { - return this.getMaxQuotaHeader(Constants.Quota.COLLECTION_SIZE); + public long collectionSizeQuota() { + return this.maxQuotaHeader(Constants.Quota.COLLECTION_SIZE); } /** @@ -169,8 +169,8 @@ public long getCollectionSizeQuota() { * * @return The current size of a collection in kilobytes. */ - public long getCollectionSizeUsage() { - return this.getCurrentQuotaHeader(Constants.Quota.COLLECTION_SIZE); + public long collectionSizeUsage() { + return this.currentQuotaHeader(Constants.Quota.COLLECTION_SIZE); } /** @@ -178,8 +178,8 @@ public long getCollectionSizeUsage() { * * @return The maximum stored procedure quota. */ - public long getStoredProceduresQuota() { - return this.getMaxQuotaHeader(Constants.Quota.STORED_PROCEDURE); + public long storedProceduresQuota() { + return this.maxQuotaHeader(Constants.Quota.STORED_PROCEDURE); } /** @@ -187,8 +187,8 @@ public long getStoredProceduresQuota() { * * @return The current number of stored procedures. */ - public long getStoredProceduresUsage() { - return this.getCurrentQuotaHeader(Constants.Quota.STORED_PROCEDURE); + public long storedProceduresUsage() { + return this.currentQuotaHeader(Constants.Quota.STORED_PROCEDURE); } /** @@ -196,8 +196,8 @@ public long getStoredProceduresUsage() { * * @return The maximum triggers quota. */ - public long getTriggersQuota() { - return this.getMaxQuotaHeader(Constants.Quota.TRIGGER); + public long triggersQuota() { + return this.maxQuotaHeader(Constants.Quota.TRIGGER); } /** @@ -205,8 +205,8 @@ public long getTriggersQuota() { * * @return The current number of triggers. */ - public long getTriggersUsage() { - return this.getCurrentQuotaHeader(Constants.Quota.TRIGGER); + public long triggersUsage() { + return this.currentQuotaHeader(Constants.Quota.TRIGGER); } /** @@ -214,8 +214,8 @@ public long getTriggersUsage() { * * @return The maximum user defined functions quota. */ - public long getUserDefinedFunctionsQuota() { - return this.getMaxQuotaHeader(Constants.Quota.USER_DEFINED_FUNCTION); + public long userDefinedFunctionsQuota() { + return this.maxQuotaHeader(Constants.Quota.USER_DEFINED_FUNCTION); } /** @@ -223,8 +223,8 @@ public long getUserDefinedFunctionsQuota() { * * @return the current number of user defined functions. */ - public long getUserDefinedFunctionsUsage() { - return this.getCurrentQuotaHeader(Constants.Quota.USER_DEFINED_FUNCTION); + public long userDefinedFunctionsUsage() { + return this.currentQuotaHeader(Constants.Quota.USER_DEFINED_FUNCTION); } /** @@ -233,7 +233,7 @@ public long getUserDefinedFunctionsUsage() { * @return the maximum size limit for this entity. * Measured in kilobytes for document resources and in counts for other resources. */ - public String getMaxResourceQuota() { + public String maxResourceQuota() { return getValueOrNull(header, HttpConstants.HttpHeaders.MAX_RESOURCE_QUOTA); } @@ -244,7 +244,7 @@ public String getMaxResourceQuota() { * @return the current size for this entity. Measured in kilobytes for document resources * and in counts for other resources. */ - public String getCurrentResourceQuotaUsage() { + public String currentResourceQuotaUsage() { return getValueOrNull(header, HttpConstants.HttpHeaders.CURRENT_RESOURCE_QUOTA_USAGE); } @@ -254,7 +254,7 @@ public String getCurrentResourceQuotaUsage() { * * @return the request charge. */ - public double getRequestCharge() { + public double requestCharge() { String value = getValueOrNull(header, HttpConstants.HttpHeaders.REQUEST_CHARGE); if (StringUtils.isEmpty(value)) { @@ -268,7 +268,7 @@ public double getRequestCharge() { * * @return the activity id. */ - public String getActivityId() { + public String activityId() { return getValueOrNull(header, HttpConstants.HttpHeaders.ACTIVITY_ID); } @@ -277,7 +277,7 @@ public String getActivityId() { * * @return the response continuation. */ - public String getResponseContinuation() { + public String continuationToken() { String headerName = useEtagAsContinuation ? HttpConstants.HttpHeaders.E_TAG : HttpConstants.HttpHeaders.CONTINUATION; @@ -289,7 +289,7 @@ public String getResponseContinuation() { * * @return the session token. */ - public String getSessionToken() { + public String sessionToken() { return getValueOrNull(header, HttpConstants.HttpHeaders.SESSION_TOKEN); } @@ -298,12 +298,12 @@ public String getSessionToken() { * * @return the response headers. */ - public Map getResponseHeaders() { + public Map responseHeaders() { return header; } - private String getQueryMetricsString(){ - return getValueOrNull(getResponseHeaders(), + private String queryMetricsString(){ + return getValueOrNull(responseHeaders(), HttpConstants.HttpHeaders.QUERY_METRICS); } @@ -312,28 +312,28 @@ private String getQueryMetricsString(){ * * @return the QueryMetrics for each partition. */ - public ConcurrentMap getQueryMetrics() { + public ConcurrentMap queryMetrics() { if (queryMetricsMap != null && !queryMetricsMap.isEmpty()) { return queryMetricsMap; } //We parse query metrics for un-partitioned collection here - if (!StringUtils.isEmpty(getQueryMetricsString())) { - String qm = getQueryMetricsString(); - qm += String.format(";%s=%.2f", QueryMetricsConstants.RequestCharge, getRequestCharge()); + if (!StringUtils.isEmpty(queryMetricsString())) { + String qm = queryMetricsString(); + qm += String.format(";%s=%.2f", QueryMetricsConstants.RequestCharge, requestCharge()); queryMetricsMap.put(DefaultPartition, QueryMetrics.createFromDelimitedString(qm)); } return queryMetricsMap; } - ConcurrentMap getQueryMetricsMap(){ + ConcurrentMap queryMetricsMap(){ return queryMetricsMap; } - private long getCurrentQuotaHeader(String headerName) { - if (this.usageHeaders.size() == 0 && !StringUtils.isEmpty(this.getMaxResourceQuota()) && - !StringUtils.isEmpty(this.getCurrentResourceQuotaUsage())) { - this.populateQuotaHeader(this.getMaxResourceQuota(), this.getCurrentResourceQuotaUsage()); + private long currentQuotaHeader(String headerName) { + if (this.usageHeaders.size() == 0 && !StringUtils.isEmpty(this.maxResourceQuota()) && + !StringUtils.isEmpty(this.currentResourceQuotaUsage())) { + this.populateQuotaHeader(this.maxResourceQuota(), this.currentResourceQuotaUsage()); } if (this.usageHeaders.containsKey(headerName)) { @@ -343,11 +343,11 @@ private long getCurrentQuotaHeader(String headerName) { return 0; } - private long getMaxQuotaHeader(String headerName) { + private long maxQuotaHeader(String headerName) { if (this.quotaHeaders.size() == 0 && - !StringUtils.isEmpty(this.getMaxResourceQuota()) && - !StringUtils.isEmpty(this.getCurrentResourceQuotaUsage())) { - this.populateQuotaHeader(this.getMaxResourceQuota(), this.getCurrentResourceQuotaUsage()); + !StringUtils.isEmpty(this.maxResourceQuota()) && + !StringUtils.isEmpty(this.currentResourceQuotaUsage())) { + this.populateQuotaHeader(this.maxResourceQuota(), this.currentResourceQuotaUsage()); } if (this.quotaHeaders.containsKey(headerName)) { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/HashIndex.java b/commons/src/main/java/com/azure/data/cosmos/HashIndex.java similarity index 79% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/HashIndex.java rename to commons/src/main/java/com/azure/data/cosmos/HashIndex.java index 2c351733dec81..791146bd7d0ed 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/HashIndex.java +++ b/commons/src/main/java/com/azure/data/cosmos/HashIndex.java @@ -21,11 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents a hash index in the Azure Cosmos DB database service. @@ -39,7 +40,7 @@ public final class HashIndex extends Index { *

      * {@code
      *
-     * HashIndex hashIndex = new HashIndex(DataType.String);
+     * HashIndex hashIndex = new HashIndex(DataType.STRING);
      *
      * }
      * 
@@ -47,8 +48,8 @@ public final class HashIndex extends Index { * @param dataType the data type. */ public HashIndex(DataType dataType) { - super(IndexKind.Hash); - this.setDataType(dataType); + super(IndexKind.HASH); + this.dataType(dataType); } /** @@ -58,7 +59,7 @@ public HashIndex(DataType dataType) { *
      * {@code
      *
-     * HashIndex hashIndex = new HashIndex(DataType.String, 3);
+     * HashIndex hashIndex = new HashIndex(DataType.STRING, 3);
      *
      * }
      * 
@@ -67,9 +68,9 @@ public HashIndex(DataType dataType) { * @param precision the precision. */ public HashIndex(DataType dataType, int precision) { - super(IndexKind.Hash); - this.setDataType(dataType); - this.setPrecision(precision); + super(IndexKind.HASH); + this.dataType(dataType); + this.precision(precision); } /** @@ -78,8 +79,8 @@ public HashIndex(DataType dataType, int precision) { * @param jsonString the json string that represents the index. */ public HashIndex(String jsonString) { - super(jsonString, IndexKind.Hash); - if (this.getDataType() == null) { + super(jsonString, IndexKind.HASH); + if (this.dataType() == null) { throw new IllegalArgumentException("The jsonString doesn't contain a valid 'dataType'."); } } @@ -89,13 +90,13 @@ public HashIndex(String jsonString) { * * @return the data type. */ - public DataType getDataType() { + public DataType dataType() { DataType result = null; try { - result = DataType.valueOf(WordUtils.capitalize(super.getString(Constants.Properties.DATA_TYPE))); + result = DataType.valueOf(StringUtils.upperCase(super.getString(Constants.Properties.DATA_TYPE))); } catch (IllegalArgumentException e) { // Ignore exception and let the caller handle null value. - this.getLogger().warn("Invalid index dataType value {}.", super.getString(Constants.Properties.DATA_TYPE)); + this.getLogger().warn("INVALID index dataType value {}.", super.getString(Constants.Properties.DATA_TYPE)); } return result; } @@ -105,8 +106,9 @@ public DataType getDataType() { * * @param dataType the data type. */ - public void setDataType(DataType dataType) { + public HashIndex dataType(DataType dataType) { super.set(Constants.Properties.DATA_TYPE, dataType.name()); + return this; } /** @@ -114,7 +116,7 @@ public void setDataType(DataType dataType) { * * @return the precision. */ - public int getPrecision() { + public int precision() { return super.getInt(Constants.Properties.PRECISION); } @@ -123,8 +125,9 @@ public int getPrecision() { * * @param precision the precision. */ - public void setPrecision(int precision) { + public HashIndex precision(int precision) { super.set(Constants.Properties.PRECISION, precision); + return this; } boolean hasPrecision() { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/IncludedPath.java b/commons/src/main/java/com/azure/data/cosmos/IncludedPath.java similarity index 85% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/IncludedPath.java rename to commons/src/main/java/com/azure/data/cosmos/IncludedPath.java index 3a630102fde87..0ff05623e8d0d 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/IncludedPath.java +++ b/commons/src/main/java/com/azure/data/cosmos/IncludedPath.java @@ -21,16 +21,17 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.ArrayList; import java.util.Collection; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents an included path of the IndexingPolicy in the Azure Cosmos DB database service. @@ -60,7 +61,7 @@ public IncludedPath(String jsonString) { * * @return the path. */ - public String getPath() { + public String path() { return super.getString(Constants.Properties.PATH); } @@ -69,8 +70,9 @@ public String getPath() { * * @param path the path. */ - public void setPath(String path) { + public IncludedPath path(String path) { super.set(Constants.Properties.PATH, path); + return this; } /** @@ -78,9 +80,9 @@ public void setPath(String path) { * * @return the included paths. */ - public Collection getIndexes() { + public Collection indexes() { if (this.indexes == null) { - this.indexes = this.getIndexCollection(); + this.indexes = this.indexCollection(); if (this.indexes == null) { this.indexes = new ArrayList(); @@ -90,11 +92,12 @@ public Collection getIndexes() { return this.indexes; } - public void setIndexes(Collection indexes) { + public IncludedPath indexes(Collection indexes) { this.indexes = indexes; + return this; } - private Collection getIndexCollection() { + private Collection indexCollection() { if (this.propertyBag != null && this.propertyBag.has(Constants.Properties.INDEXES)) { ArrayNode jsonArray = (ArrayNode) this.propertyBag.get(Constants.Properties.INDEXES); Collection result = new ArrayList(); @@ -102,16 +105,16 @@ private Collection getIndexCollection() { for (int i = 0; i < jsonArray.size(); i++) { JsonNode jsonObject = jsonArray.get(i); - IndexKind indexKind = IndexKind.valueOf(WordUtils.capitalize( + IndexKind indexKind = IndexKind.valueOf(StringUtils.upperCase( jsonObject.get(Constants.Properties.INDEX_KIND).asText())); switch (indexKind) { - case Hash: + case HASH: result.add(new HashIndex(jsonObject.toString())); break; - case Range: + case RANGE: result.add(new RangeIndex(jsonObject.toString())); break; - case Spatial: + case SPATIAL: result.add(new SpatialIndex(jsonObject.toString())); break; } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Index.java b/commons/src/main/java/com/azure/data/cosmos/Index.java similarity index 86% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Index.java rename to commons/src/main/java/com/azure/data/cosmos/Index.java index 7a3b00a6dc976..de6d8ac14915d 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Index.java +++ b/commons/src/main/java/com/azure/data/cosmos/Index.java @@ -21,11 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents the index of a collection in the Azure Cosmos DB database service. @@ -39,7 +40,7 @@ public abstract class Index extends JsonSerializable { */ protected Index(IndexKind indexKind) { super(); - this.setKind(indexKind); + this.kind(indexKind); } /** @@ -50,7 +51,7 @@ protected Index(IndexKind indexKind) { */ protected Index(String jsonString, IndexKind indexKind) { super(jsonString); - this.setKind(indexKind); + this.kind(indexKind); } /** @@ -60,7 +61,7 @@ protected Index(String jsonString, IndexKind indexKind) { *
      * {@code
      *
-     * RangeIndex rangeIndex = Index.Range(DataType.Number);
+     * RangeIndex rangeIndex = Index.RANGE(DataType.NUMBER);
      *
      * }
      * 
@@ -79,7 +80,7 @@ public static RangeIndex Range(DataType dataType) { *
      * {@code
      *
-     * RangeIndex rangeIndex = Index.Range(DataType.Number, -1);
+     * RangeIndex rangeIndex = Index.RANGE(DataType.NUMBER, -1);
      *
      * }
      * 
@@ -99,7 +100,7 @@ public static RangeIndex Range(DataType dataType, int precision) { *
      * {@code
      *
-     * HashIndex hashIndex = Index.Hash(DataType.String);
+     * HashIndex hashIndex = Index.HASH(DataType.STRING);
      * }
      * 
* @@ -115,7 +116,7 @@ public static HashIndex Hash(DataType dataType) { *

* Here is an example to create HashIndex instance passing in the DataType and precision: *

- * HashIndex hashIndex = Index.Hash(DataType.String, 3); + * HashIndex hashIndex = Index.HASH(DataType.STRING, 3); * * @param dataType specifies the target data type for the index path specification. * @param precision specifies the precision to be used for the data type associated with this index. @@ -130,7 +131,7 @@ public static HashIndex Hash(DataType dataType, int precision) { *

* Here is an example to create SpatialIndex instance passing in the DataType: *

- * SpatialIndex spatialIndex = Index.Spatial(DataType.Point); + * SpatialIndex spatialIndex = Index.SPATIAL(DataType.POINT); * * @param dataType specifies the target data type for the index path specification. * @return an instance of SpatialIndex type. @@ -144,12 +145,12 @@ public static SpatialIndex Spatial(DataType dataType) { * * @return the index kind. */ - public IndexKind getKind() { + public IndexKind kind() { IndexKind result = null; try { - result = IndexKind.valueOf(WordUtils.capitalize(super.getString(Constants.Properties.INDEX_KIND))); + result = IndexKind.valueOf(StringUtils.upperCase(super.getString(Constants.Properties.INDEX_KIND))); } catch (IllegalArgumentException e) { - this.getLogger().warn("Invalid index kind value %s.", super.getString(Constants.Properties.INDEX_KIND)); + this.getLogger().warn("INVALID index kind value %s.", super.getString(Constants.Properties.INDEX_KIND)); } return result; @@ -160,7 +161,8 @@ public IndexKind getKind() { * * @param indexKind the index kind. */ - private void setKind(IndexKind indexKind) { + private Index kind(IndexKind indexKind) { super.set(Constants.Properties.INDEX_KIND, indexKind.name()); + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/IndexKind.java b/commons/src/main/java/com/azure/data/cosmos/IndexKind.java similarity index 90% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/IndexKind.java rename to commons/src/main/java/com/azure/data/cosmos/IndexKind.java index 4e63ba4679721..8c2139103deab 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/IndexKind.java +++ b/commons/src/main/java/com/azure/data/cosmos/IndexKind.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * These are the indexing types available for indexing a path in the Azure Cosmos DB database service. @@ -31,14 +31,14 @@ public enum IndexKind { // The index entries are hashed to serve point look up queries. // Can be used to serve queries like: SELECT * FROM docs d WHERE d.prop = 5 - Hash, + HASH, - // The index entries are ordered. Range indexes are optimized for inequality predicate queries with efficient range + // The index entries are ordered. RANGE indexes are optimized for inequality predicate queries with efficient range // scans. // Can be used to serve queries like: SELECT * FROM docs d WHERE d.prop > 5 - Range, + RANGE, // The index entries are indexed to serve spatial queries like below: - // SELECT * FROM Root r WHERE ST_DISTANCE({"type":"Point","coordinates":[71.0589,42.3601]}, r.location) $LE 10000 - Spatial + // SELECT * FROM Root r WHERE ST_DISTANCE({"type":"POINT","coordinates":[71.0589,42.3601]}, r.location) $LE 10000 + SPATIAL } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/IndexingDirective.java b/commons/src/main/java/com/azure/data/cosmos/IndexingDirective.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/IndexingDirective.java rename to commons/src/main/java/com/azure/data/cosmos/IndexingDirective.java index 603191cc05c8b..cdec2ce598d17 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/IndexingDirective.java +++ b/commons/src/main/java/com/azure/data/cosmos/IndexingDirective.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Specifies whether or not the resource is to be indexed in the Azure Cosmos DB database service. @@ -31,15 +31,15 @@ public enum IndexingDirective { /** * Use any pre-defined/pre-configured defaults. */ - Default, + DEFAULT, /** * Index the resource. */ - Include, + INCLUDE, /** * Do not index the resource. */ - Exclude + EXCLUDE } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/IndexingMode.java b/commons/src/main/java/com/azure/data/cosmos/IndexingMode.java similarity index 93% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/IndexingMode.java rename to commons/src/main/java/com/azure/data/cosmos/IndexingMode.java index 54bd9b96a99e4..b11d01b94247a 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/IndexingMode.java +++ b/commons/src/main/java/com/azure/data/cosmos/IndexingMode.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Specifies the supported indexing modes in the Azure Cosmos DB database service. @@ -33,21 +33,21 @@ public enum IndexingMode { * With consistent indexing, query behavior is the same as the default consistency level for the collection. The * index is always kept up to date with the data. */ - Consistent, + CONSISTENT, /** * Index is updated asynchronously with respect to a create or update operation. *

* With lazy indexing, queries are eventually consistent. The index is updated when the collection is idle. */ - Lazy, + LAZY, /** * No index is provided. *

- * Setting IndexingMode to "None" drops the index. Use this if you don't want to maintain the index for a document + * Setting IndexingMode to "NONE" drops the index. Use this if you don't want to maintain the index for a document * collection, to save the storage cost or improve the write throughput. Your queries will degenerate to scans of * the entire collection. */ - None + NONE } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/IndexingPolicy.java b/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java similarity index 80% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/IndexingPolicy.java rename to commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java index 41650c03a5627..f75a217c412a9 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/IndexingPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java @@ -21,10 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import com.fasterxml.jackson.databind.node.ArrayNode; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; import java.util.ArrayList; @@ -47,8 +48,8 @@ public final class IndexingPolicy extends JsonSerializable { * Constructor. */ public IndexingPolicy() { - this.setAutomatic(true); - this.setIndexingMode(IndexingMode.Consistent); + this.automatic(true); + this.indexingMode(IndexingMode.CONSISTENT); } /** @@ -58,9 +59,9 @@ public IndexingPolicy() { * The following example shows how to override the default indexingPolicy for root path: *

      * {@code
-     * HashIndex hashIndexOverride = Index.Hash(DataType.String, 5);
-     * RangeIndex rangeIndexOverride = Index.Range(DataType.Number, 2);
-     * SpatialIndex spatialIndexOverride = Index.Spatial(DataType.Point);
+     * HashIndex hashIndexOverride = Index.HASH(DataType.STRING, 5);
+     * RangeIndex rangeIndexOverride = Index.RANGE(DataType.NUMBER, 2);
+     * SpatialIndex spatialIndexOverride = Index.SPATIAL(DataType.POINT);
      *
      * IndexingPolicy indexingPolicy = new IndexingPolicy(hashIndexOverride, rangeIndexOverride, spatialIndexOverride);
      * }
@@ -69,7 +70,7 @@ public IndexingPolicy() {
      * If you would like to just override the indexingPolicy for Numbers you can specify just that:
      * 
      * {@code
-     * RangeIndex rangeIndexOverride = Index.Range(DataType.Number, 2);
+     * RangeIndex rangeIndexOverride = Index.RANGE(DataType.NUMBER, 2);
      *
      * IndexingPolicy indexingPolicy = new IndexingPolicy(rangeIndexOverride);
      * }
@@ -85,9 +86,9 @@ public IndexingPolicy(Index[] defaultIndexOverrides) {
         }
 
         IncludedPath includedPath = new IncludedPath();
-        includedPath.setPath(IndexingPolicy.DEFAULT_PATH);
-        includedPath.setIndexes(new ArrayList(Arrays.asList(defaultIndexOverrides)));
-        this.getIncludedPaths().add(includedPath);
+        includedPath.path(IndexingPolicy.DEFAULT_PATH);
+        includedPath.indexes(new ArrayList(Arrays.asList(defaultIndexOverrides)));
+        this.includedPaths().add(includedPath);
     }
 
     /**
@@ -107,7 +108,7 @@ public IndexingPolicy(String jsonString) {
      *
      * @return the automatic
      */
-    public Boolean getAutomatic() {
+    public Boolean automatic() {
         return super.getBoolean(Constants.Properties.AUTOMATIC);
     }
 
@@ -119,8 +120,9 @@ public Boolean getAutomatic() {
      *
      * @param automatic the automatic
      */
-    public void setAutomatic(boolean automatic) {
+    public IndexingPolicy automatic(boolean automatic) {
         super.set(Constants.Properties.AUTOMATIC, automatic);
+        return this;
     }
 
     /**
@@ -128,12 +130,12 @@ public void setAutomatic(boolean automatic) {
      *
      * @return the indexing mode.
      */
-    public IndexingMode getIndexingMode() {
-        IndexingMode result = IndexingMode.Lazy;
+    public IndexingMode indexingMode() {
+        IndexingMode result = IndexingMode.LAZY;
         try {
-            result = IndexingMode.valueOf(WordUtils.capitalize(super.getString(Constants.Properties.INDEXING_MODE)));
+            result = IndexingMode.valueOf(StringUtils.upperCase(super.getString(Constants.Properties.INDEXING_MODE)));
         } catch (IllegalArgumentException e) {
-            this.getLogger().warn("Invalid indexingMode value {}.", super.getString(Constants.Properties.INDEXING_MODE));
+            this.getLogger().warn("INVALID indexingMode value {}.", super.getString(Constants.Properties.INDEXING_MODE));
         }
         return result;
     }
@@ -143,8 +145,9 @@ public IndexingMode getIndexingMode() {
      *
      * @param indexingMode the indexing mode.
      */
-    public void setIndexingMode(IndexingMode indexingMode) {
+    public IndexingPolicy indexingMode(IndexingMode indexingMode) {
         super.set(Constants.Properties.INDEXING_MODE, indexingMode.name());
+        return this;
     }
 
     /**
@@ -152,7 +155,7 @@ public void setIndexingMode(IndexingMode indexingMode) {
      *
      * @return the included paths.
      */
-    public Collection getIncludedPaths() {
+    public Collection includedPaths() {
         if (this.includedPaths == null) {
             this.includedPaths = super.getCollection(Constants.Properties.INCLUDED_PATHS, IncludedPath.class);
 
@@ -173,7 +176,7 @@ public void setIncludedPaths(Collection includedPaths) {
      *
      * @return the excluded paths.
      */
-    public Collection getExcludedPaths() {
+    public Collection excludedPaths() {
         if (this.excludedPaths == null) {
             this.excludedPaths = super.getCollection(Constants.Properties.EXCLUDED_PATHS, ExcludedPath.class);
 
@@ -185,8 +188,9 @@ public Collection getExcludedPaths() {
         return this.excludedPaths;
     }
 
-    public void setExcludedPaths(Collection excludedPaths) {
+    public IndexingPolicy excludedPaths(Collection excludedPaths) {
         this.excludedPaths = excludedPaths;
+        return this;
     }
 
     /**
@@ -194,7 +198,7 @@ public void setExcludedPaths(Collection excludedPaths) {
      *
      * @return the composite indexes.
      */
-    public Collection> getCompositeIndexes() {
+    public Collection> compositeIndexes() {
         if (this.compositeIndexes == null) {
             this.compositeIndexes = new ArrayList>();
             ArrayNode compositeIndexes = (ArrayNode) super.get(Constants.Properties.COMPOSITE_INDEXES);
@@ -217,9 +221,10 @@ public Collection> getCompositeIndexes() {
      *
      * @param compositeIndexes the composite indexes.
      */
-    public void setCompositeIndexes(Collection> compositeIndexes) {
+    public IndexingPolicy compositeIndexes(Collection> compositeIndexes) {
         this.compositeIndexes = compositeIndexes;
         super.set(Constants.Properties.COMPOSITE_INDEXES, this.compositeIndexes);
+        return this;
     }
 
     /**
@@ -227,7 +232,7 @@ public void setCompositeIndexes(Collection> compositeIn
      *
      * @return the spatial indexes.
      */
-    public Collection getSpatialIndexes() {
+    public Collection spatialIndexes() {
         if (this.spatialIndexes == null) {
             this.spatialIndexes = super.getCollection(Constants.Properties.SPATIAL_INDEXES, SpatialSpec.class);
 
@@ -244,19 +249,20 @@ public Collection getSpatialIndexes() {
      *
      * @param spatialIndexes the spatial indexes.
      */
-    public void setSpatialIndexes(Collection spatialIndexes) {
+    public IndexingPolicy spatialIndexes(Collection spatialIndexes) {
         this.spatialIndexes = spatialIndexes;
         super.set(Constants.Properties.SPATIAL_INDEXES, this.spatialIndexes);
+        return this;
     }
 
     @Override
     void populatePropertyBag() {
         // If indexing mode is not 'none' and not paths are set, set them to the defaults
-        if (this.getIndexingMode() != IndexingMode.None && this.getIncludedPaths().size() == 0 &&
-                this.getExcludedPaths().size() == 0) {
+        if (this.indexingMode() != IndexingMode.NONE && this.includedPaths().size() == 0 &&
+                this.excludedPaths().size() == 0) {
             IncludedPath includedPath = new IncludedPath();
-            includedPath.setPath(IndexingPolicy.DEFAULT_PATH);
-            this.getIncludedPaths().add(includedPath);
+            includedPath.path(IndexingPolicy.DEFAULT_PATH);
+            this.includedPaths().add(includedPath);
         }
 
         if (this.includedPaths != null) {
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/JsonSerializable.java b/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java
similarity index 97%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/JsonSerializable.java
rename to commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java
index 64b8a40f48fe7..3fedeb3f80c9d 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/JsonSerializable.java
+++ b/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java
@@ -21,7 +21,7 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 import java.io.IOException;
 import java.lang.reflect.InvocationTargetException;
@@ -32,7 +32,7 @@
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.node.ArrayNode;
 import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.microsoft.azure.cosmosdb.internal.Utils;
+import com.azure.data.cosmos.internal.Utils;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -185,8 +185,8 @@ private  void internalSetCollection(String propertyName, Collection collec
                 castedValue.populatePropertyBag();
                 targetArray.add(castedValue.propertyBag != null ? castedValue.propertyBag : this.getMapper().createObjectNode());
             } else {
-                // POJO, JSONObject, Number (includes Int, Float, Double etc),
-                // Boolean, and String.
+                // POJO, JSONObject, NUMBER (includes Int, Float, Double etc),
+                // Boolean, and STRING.
                 targetArray.add(this.getMapper().valueToTree(childValue));
             }
         }
@@ -290,7 +290,7 @@ public  T getObject(String propertyName, Class c) {
             JsonNode jsonObj = propertyBag.get(propertyName);
             if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c)
                     || Boolean.class.isAssignableFrom(c) || Object.class == c) {
-                // Number, String, Boolean
+                // NUMBER, STRING, Boolean
                 return c.cast(getValue(jsonObj));
             } else if (Enum.class.isAssignableFrom(c)) {
                 try {
@@ -352,7 +352,7 @@ public  List getList(String propertyName, Class c) {
 
             for (JsonNode n : jsonArray) {
                 if (isBaseClass) {
-                    // Number, String, Boolean
+                    // NUMBER, STRING, Boolean
                     result.add(c.cast(getValue(n)));
                 } else if (isEnumClass) {
                     try {
@@ -497,7 +497,7 @@ private String toJson(Object object){
         try {
             return getMapper().writeValueAsString(object);
         } catch (JsonProcessingException e) {
-            throw new IllegalStateException("Unable to convert JSON to String", e);
+            throw new IllegalStateException("Unable to convert JSON to STRING", e);
         }
     }
 
@@ -505,7 +505,7 @@ private String toPrettyJson(Object object){
         try {
             return getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(object);
         } catch (JsonProcessingException e) {
-            throw new IllegalStateException("Unable to convert JSON to String", e);
+            throw new IllegalStateException("Unable to convert JSON to STRING", e);
         }
     }
 
@@ -545,7 +545,7 @@ public  T toObject(Class c) {
      * @return the JSON string.
      */
     public String toJson() {
-        return this.toJson(SerializationFormattingPolicy.None);
+        return this.toJson(SerializationFormattingPolicy.NONE);
     }
     
     /**
@@ -556,7 +556,7 @@ public String toJson() {
      */
     public String toJson(SerializationFormattingPolicy formattingPolicy) {
         this.populatePropertyBag();
-        if (SerializationFormattingPolicy.Indented.equals(formattingPolicy) ) {
+        if (SerializationFormattingPolicy.INDENTED.equals(formattingPolicy) ) {
             return toPrettyJson(propertyBag);
         } else {
             return toJson(propertyBag);
@@ -564,7 +564,7 @@ public String toJson(SerializationFormattingPolicy formattingPolicy) {
     }
 
     /**
-     * Gets Simple String representation of property bag.
+     * Gets Simple STRING representation of property bag.
      * 
      * For proper conversion to json and inclusion of the default values 
      * use {@link #toJson()}.
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/MediaOptions.java b/commons/src/main/java/com/azure/data/cosmos/MediaOptions.java
similarity index 98%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/MediaOptions.java
rename to commons/src/main/java/com/azure/data/cosmos/MediaOptions.java
index 43d38ee187d2f..1a627fd2c7fb3 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/MediaOptions.java
+++ b/commons/src/main/java/com/azure/data/cosmos/MediaOptions.java
@@ -21,7 +21,7 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 /**
  * Options used with attachment content (aka media) creation in the Azure Cosmos DB database service.
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/MediaReadMode.java b/commons/src/main/java/com/azure/data/cosmos/MediaReadMode.java
similarity index 97%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/MediaReadMode.java
rename to commons/src/main/java/com/azure/data/cosmos/MediaReadMode.java
index 00b318ea7f586..ab6aa698e5f5e 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/MediaReadMode.java
+++ b/commons/src/main/java/com/azure/data/cosmos/MediaReadMode.java
@@ -21,7 +21,7 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 /**
  * Represents the mode for use with downloading attachment content (aka media) from the Azure Cosmos DB database service.
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/MediaResponse.java b/commons/src/main/java/com/azure/data/cosmos/MediaResponse.java
similarity index 95%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/MediaResponse.java
rename to commons/src/main/java/com/azure/data/cosmos/MediaResponse.java
index cc4e1dcf30753..4d4aa5c0731c0 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/MediaResponse.java
+++ b/commons/src/main/java/com/azure/data/cosmos/MediaResponse.java
@@ -21,13 +21,13 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 import java.io.BufferedInputStream;
 import java.io.InputStream;
 import java.util.Map;
 
-import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse;
+import com.azure.data.cosmos.internal.RxDocumentServiceResponse;
 
 /**
  * Response associated with retrieving attachment content in the Azure Cosmos DB database service.
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Offer.java b/commons/src/main/java/com/azure/data/cosmos/Offer.java
similarity index 97%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Offer.java
rename to commons/src/main/java/com/azure/data/cosmos/Offer.java
index 0e450510340e6..3b6cf550e497a 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Offer.java
+++ b/commons/src/main/java/com/azure/data/cosmos/Offer.java
@@ -21,12 +21,12 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 import com.fasterxml.jackson.databind.node.ObjectNode;
 
-import com.microsoft.azure.cosmosdb.internal.Constants;
-import com.microsoft.azure.cosmosdb.internal.Utils;
+import com.azure.data.cosmos.internal.Constants;
+import com.azure.data.cosmos.internal.Utils;
 
 /**
  * Represents an offer in the Azure Cosmos DB database service.
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKey.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java
similarity index 85%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKey.java
rename to commons/src/main/java/com/azure/data/cosmos/PartitionKey.java
index 2f25785475d25..bcdce13fd18f9 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKey.java
+++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java
@@ -21,14 +21,14 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
-import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal;
-import com.microsoft.azure.cosmosdb.rx.internal.Utils;
+import com.azure.data.cosmos.internal.routing.PartitionKeyInternal;
+import com.azure.data.cosmos.internal.Utils;
 
 /**
- * Represents a partition key value in the Azure Cosmos DB database service. A partition key identifies the partition
- * where the document is stored in.
+ * Represents a partition key value in the Azure Cosmos DB database service. A
+ * partition key identifies the partition where the document is stored in.
  */
 public class PartitionKey {
 
@@ -39,17 +39,18 @@ public class PartitionKey {
     }
 
     /**
-     * Constructor. Create a new instance of the PartitionKey object.
+     * Constructor. CREATE a new instance of the PartitionKey object.
      *
      * @param key the value of the partition key.
      */
     @SuppressWarnings("serial")
     public PartitionKey(final Object key) {
-        this.internalPartitionKey = PartitionKeyInternal.fromObjectArray(new Object[] {key}, true);
+        this.internalPartitionKey = PartitionKeyInternal.fromObjectArray(new Object[] { key }, true);
     }
 
     /**
-     * Create a new instance of the PartitionKey object from a serialized JSON partition key.
+     * CREATE a new instance of the PartitionKey object from a serialized JSON
+     * partition key.
      *
      * @param jsonString the JSON string representation of this PartitionKey object.
      * @return the PartitionKey instance.
@@ -69,12 +70,15 @@ public String toString() {
         return this.internalPartitionKey.toJson();
     }
 
+    // TODO: make private
     public PartitionKeyInternal getInternalPartitionKey() {
         return internalPartitionKey;
     }
 
     /**
-     * Overrides the Equal operator for object comparisons between two instances of {@link PartitionKey}
+     * Overrides the Equal operator for object comparisons between two instances of
+     * {@link PartitionKey}
+     * 
      * @param other The object to compare with.
      * @return True if two object instance are considered equal.
      */
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java
similarity index 88%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java
rename to commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java
index bc6fda9090410..27530f1a1172a 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinition.java
+++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java
@@ -21,11 +21,11 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
-import com.microsoft.azure.cosmosdb.internal.Constants;
-import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal;
-import com.microsoft.azure.cosmosdb.rx.internal.Strings;
+import com.azure.data.cosmos.internal.Constants;
+import com.azure.data.cosmos.internal.routing.PartitionKeyInternal;
+import com.azure.data.cosmos.internal.Strings;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -47,7 +47,7 @@ public final class PartitionKeyDefinition extends JsonSerializable {
      * Constructor. Creates a new instance of the PartitionKeyDefinition object.
      */
     public PartitionKeyDefinition() {
-        this.setKind(PartitionKind.Hash);
+        this.kind(PartitionKind.HASH);
     }
 
     /**
@@ -65,7 +65,7 @@ public PartitionKeyDefinition(String jsonString) {
      *
      * @return the partition algorithm.
      */
-    public PartitionKind getKind() {
+    public PartitionKind kind() {
         if (this.kind == null) {
             this.kind = super.getObject(Constants.Properties.PARTITION_KIND, PartitionKind.class);
         }
@@ -78,11 +78,12 @@ public PartitionKind getKind() {
      *
      * @param kind the partition algorithm.
      */
-    public void setKind(PartitionKind kind) {
+    public PartitionKeyDefinition kind(PartitionKind kind) {
         this.kind = kind;
+        return this;
     }
 
-    public PartitionKeyDefinitionVersion getVersion() {
+    public PartitionKeyDefinitionVersion version() {
         if (this.version == null) {
             Object versionObject = super.getObject(Constants.Properties.PARTITION_KEY_DEFINITION_VERSION, Object.class);
             if (versionObject == null) {
@@ -93,7 +94,7 @@ public PartitionKeyDefinitionVersion getVersion() {
                     this.version = PartitionKeyDefinitionVersion.valueOf(String.format("V%d", Integer.parseInt(versionStr)));
                 } else {
                     this.version = !Strings.isNullOrEmpty(versionStr)
-                            ? PartitionKeyDefinitionVersion.valueOf(WordUtils.capitalize(versionStr))
+                            ? PartitionKeyDefinitionVersion.valueOf(StringUtils.upperCase(versionStr))
                             : null;
                 }
             }
@@ -102,8 +103,9 @@ public PartitionKeyDefinitionVersion getVersion() {
         return this.version;
     }
 
-    public void setVersion(PartitionKeyDefinitionVersion version) {
+    public PartitionKeyDefinition version(PartitionKeyDefinitionVersion version) {
         this.version = version;
+        return this;
     }
 
     /**
@@ -111,7 +113,7 @@ public void setVersion(PartitionKeyDefinitionVersion version) {
      *
      * @return the paths to the document properties that form the partition key.
      */
-    public List getPaths() {
+    public List paths() {
         if (this.paths == null) {
             if (super.has(Constants.Properties.PARTITION_KEY_PATHS)) {
                 paths = super.getList(Constants.Properties.PARTITION_KEY_PATHS, String.class);
@@ -128,12 +130,13 @@ public List getPaths() {
      *
      * @param paths the paths to document properties that form the partition key.
      */
-    public void setPaths(List paths) {
+    public PartitionKeyDefinition paths(List paths) {
         if (paths == null || paths.size() == 0) {
             throw new IllegalArgumentException("paths must not be null or empty.");
         }
 
         this.paths = paths;
+        return this;
     }
 
     /**
@@ -154,7 +157,7 @@ Boolean isSystemKey() {
     }
 
     PartitionKeyInternal getNonePartitionKeyValue() {
-        if (this.getPaths().size() == 0 || this.isSystemKey()) {
+        if (this.paths().size() == 0 || this.isSystemKey()) {
             return PartitionKeyInternal.Empty;
         } else {
             return PartitionKeyInternal.UndefinedPartitionKey;
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinitionVersion.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java
similarity index 94%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinitionVersion.java
rename to commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java
index 096f2dc054f9f..296ac803b2f92 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyDefinitionVersion.java
+++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java
@@ -21,7 +21,7 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 /**
  * Partitioning version.
@@ -42,7 +42,7 @@ public enum PartitionKeyDefinitionVersion {
 
     int val;
 
-    private PartitionKeyDefinitionVersion(int val) {
+    PartitionKeyDefinitionVersion(int val) {
         this.val = val;
     }
 
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyRange.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java
similarity index 92%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyRange.java
rename to commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java
index f74e3146a8bfa..44479d7acfe60 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKeyRange.java
+++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java
@@ -21,12 +21,12 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 import java.util.List;
 
-import com.microsoft.azure.cosmosdb.internal.Constants;
-import com.microsoft.azure.cosmosdb.internal.routing.Range;
+import com.azure.data.cosmos.internal.Constants;
+import com.azure.data.cosmos.internal.routing.Range;
 
 /**
  * Represent a partition key range in the Azure Cosmos DB database service.
@@ -56,14 +56,14 @@ public PartitionKeyRange(String jsonString) {
 
     public PartitionKeyRange(String id, String minInclusive, String maxExclusive) {
         super();
-        this.setId(id);
+        this.id(id);
         this.setMinInclusive(minInclusive);
         this.setMaxExclusive(maxExclusive);
     }
 
     public PartitionKeyRange(String id, String minInclusive, String maxExclusive, List parents) {
         super();
-        this.setId(id);
+        this.id(id);
         this.setMinInclusive(minInclusive);
         this.setMaxExclusive(maxExclusive);
         this.setParents(parents);
@@ -97,7 +97,7 @@ public boolean equals(Object obj) {
 
         PartitionKeyRange otherRange = (PartitionKeyRange) obj;
 
-        return this.getId().compareTo(otherRange.getId()) == 0
+        return this.id().compareTo(otherRange.id()) == 0
                 && this.getMinInclusive().compareTo(otherRange.getMinInclusive()) == 0
                 && this.getMaxExclusive().compareTo(otherRange.getMaxExclusive()) == 0;
     }
@@ -105,7 +105,7 @@ public boolean equals(Object obj) {
     @Override
     public int hashCode() {
         int hash = 0;
-        hash = (hash * 397) ^ this.getId().hashCode();
+        hash = (hash * 397) ^ this.id().hashCode();
         hash = (hash * 397) ^ this.getMinInclusive().hashCode();
         hash = (hash * 397) ^ this.getMaxExclusive().hashCode();
         return hash;
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKind.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKind.java
similarity index 96%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKind.java
rename to commons/src/main/java/com/azure/data/cosmos/PartitionKind.java
index 4c5c94c35cd2d..1871e158ec7cd 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/PartitionKind.java
+++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKind.java
@@ -21,7 +21,7 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 /**
  * Specifies the partition scheme for an multiple-partitioned collection in the Azure Cosmos DB database service.
@@ -30,5 +30,5 @@ public enum PartitionKind {
     /**
      * The Partition of a document is calculated based on the hash value of the PartitionKey.
      */
-    Hash
+    HASH
 }
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Permission.java b/commons/src/main/java/com/azure/data/cosmos/Permission.java
similarity index 95%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Permission.java
rename to commons/src/main/java/com/azure/data/cosmos/Permission.java
index a72b653582eca..9b98a0f036894 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Permission.java
+++ b/commons/src/main/java/com/azure/data/cosmos/Permission.java
@@ -21,12 +21,13 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 import com.fasterxml.jackson.databind.node.ArrayNode;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.text.WordUtils;
 
-import com.microsoft.azure.cosmosdb.internal.Constants;
+import com.azure.data.cosmos.internal.Constants;
 
 /**
  * Represents a per-User Permission to access a specific resource e.g. Document or Collection in the Azure Cosmos DB database service.
@@ -73,7 +74,7 @@ public void setResourceLink(String resourceLink) {
      */
     public PermissionMode getPermissionMode() {
         String value = super.getString(Constants.Properties.PERMISSION_MODE);
-        return PermissionMode.valueOf(WordUtils.capitalize(value));
+        return PermissionMode.valueOf(StringUtils.upperCase(value));
     }
 
     /**
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/PermissionMode.java b/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java
similarity index 96%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/PermissionMode.java
rename to commons/src/main/java/com/azure/data/cosmos/PermissionMode.java
index ef514dcf45738..f6369560337dd 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/PermissionMode.java
+++ b/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java
@@ -21,7 +21,7 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 /**
  * Enumeration specifying applicability of permission in the Azure Cosmos DB database service.
@@ -30,12 +30,12 @@ public enum PermissionMode {
     /**
      * Permission applicable for read operations only.
      */
-    Read(0x1),
+    READ(0x1),
 
     /**
      * Permission applicable for all operations.
      */
-    All(0x2);
+    ALL(0x2);
 
     private int value;
 
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/QueryMetrics.java b/commons/src/main/java/com/azure/data/cosmos/QueryMetrics.java
similarity index 97%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/QueryMetrics.java
rename to commons/src/main/java/com/azure/data/cosmos/QueryMetrics.java
index c333c6a757a67..c565ea0af452b 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/QueryMetrics.java
+++ b/commons/src/main/java/com/azure/data/cosmos/QueryMetrics.java
@@ -20,12 +20,12 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
-import com.microsoft.azure.cosmosdb.internal.query.metrics.ClientSideMetrics;
-import com.microsoft.azure.cosmosdb.internal.query.metrics.FetchExecutionRange;
-import com.microsoft.azure.cosmosdb.internal.query.metrics.QueryMetricsTextWriter;
-import com.microsoft.azure.cosmosdb.internal.query.metrics.SchedulingTimeSpan;
+import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics;
+import com.azure.data.cosmos.internal.query.metrics.FetchExecutionRange;
+import com.azure.data.cosmos.internal.query.metrics.QueryMetricsTextWriter;
+import com.azure.data.cosmos.internal.query.metrics.SchedulingTimeSpan;
 import org.apache.commons.lang3.tuple.ImmutablePair;
 
 import java.time.Duration;
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/QueryMetricsConstants.java b/commons/src/main/java/com/azure/data/cosmos/QueryMetricsConstants.java
similarity index 99%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/QueryMetricsConstants.java
rename to commons/src/main/java/com/azure/data/cosmos/QueryMetricsConstants.java
index f14d338e19102..59ea51c28d5d8 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/QueryMetricsConstants.java
+++ b/commons/src/main/java/com/azure/data/cosmos/QueryMetricsConstants.java
@@ -20,7 +20,7 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 public final class QueryMetricsConstants {
     // QueryMetrics
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/QueryMetricsUtils.java b/commons/src/main/java/com/azure/data/cosmos/QueryMetricsUtils.java
similarity index 99%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/QueryMetricsUtils.java
rename to commons/src/main/java/com/azure/data/cosmos/QueryMetricsUtils.java
index 320e68e673467..b913289df3e19 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/QueryMetricsUtils.java
+++ b/commons/src/main/java/com/azure/data/cosmos/QueryMetricsUtils.java
@@ -20,7 +20,7 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 import org.apache.commons.lang3.StringUtils;
 
@@ -49,7 +49,7 @@ static HashMap parseDelimitedString(String delimitedString) {
             String[] attributeKeyValue = StringUtils.split(attribute, "=");
 
             if (attributeKeyValue.length != 2) {
-                throw new NullPointerException("recieved a malformed delimited String");
+                throw new NullPointerException("recieved a malformed delimited STRING");
             }
 
             String attributeKey = attributeKeyValue[key];
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/QueryPreparationTimes.java b/commons/src/main/java/com/azure/data/cosmos/QueryPreparationTimes.java
similarity index 99%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/QueryPreparationTimes.java
rename to commons/src/main/java/com/azure/data/cosmos/QueryPreparationTimes.java
index 1ab1ae83bf75e..e3e2b2cf94875 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/QueryPreparationTimes.java
+++ b/commons/src/main/java/com/azure/data/cosmos/QueryPreparationTimes.java
@@ -20,7 +20,7 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
 import java.time.Duration;
 import java.util.Collection;
diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/RangeIndex.java b/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java
similarity index 78%
rename from commons/src/main/java/com/microsoft/azure/cosmosdb/RangeIndex.java
rename to commons/src/main/java/com/azure/data/cosmos/RangeIndex.java
index 27ef781fe73af..742ed958e735a 100644
--- a/commons/src/main/java/com/microsoft/azure/cosmosdb/RangeIndex.java
+++ b/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java
@@ -21,11 +21,12 @@
  * SOFTWARE.
  */
 
-package com.microsoft.azure.cosmosdb;
+package com.azure.data.cosmos;
 
+import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.text.WordUtils;
 
-import com.microsoft.azure.cosmosdb.internal.Constants;
+import com.azure.data.cosmos.internal.Constants;
 
 /**
  * Represents a range index in the Azure Cosmos DB database service.
@@ -39,7 +40,7 @@ public final class RangeIndex extends Index {
      * 
      * {@code
      *
-     * RangeIndex rangeIndex = new RangeIndex(DataType.Number);
+     * RangeIndex rangeIndex = new RangeIndex(DataType.NUMBER);
      *
      * }
      * 
@@ -47,8 +48,8 @@ public final class RangeIndex extends Index { * @param dataType the data type. */ public RangeIndex(DataType dataType) { - super(IndexKind.Range); - this.setDataType(dataType); + super(IndexKind.RANGE); + this.dataType(dataType); } /** @@ -56,7 +57,7 @@ public RangeIndex(DataType dataType) { *
      * {@code
      *
-     * RangeIndex rangeIndex = new RangeIndex(DataType.Number, -1);
+     * RangeIndex rangeIndex = new RangeIndex(DataType.NUMBER, -1);
      *
      * }
      * 
@@ -64,9 +65,9 @@ public RangeIndex(DataType dataType) { * @param precision the precision of the RangeIndex */ public RangeIndex(DataType dataType, int precision) { - super(IndexKind.Range); - this.setDataType(dataType); - this.setPrecision(precision); + super(IndexKind.RANGE); + this.dataType(dataType); + this.precision(precision); } /** @@ -75,8 +76,8 @@ public RangeIndex(DataType dataType, int precision) { * @param jsonString the json string that represents the index. */ public RangeIndex(String jsonString) { - super(jsonString, IndexKind.Range); - if (this.getDataType() == null) { + super(jsonString, IndexKind.RANGE); + if (this.dataType() == null) { throw new IllegalArgumentException("The jsonString doesn't contain a valid 'dataType'."); } } @@ -86,12 +87,12 @@ public RangeIndex(String jsonString) { * * @return the data type. */ - public DataType getDataType() { + public DataType dataType() { DataType result = null; try { - result = DataType.valueOf(WordUtils.capitalize(super.getString(Constants.Properties.DATA_TYPE))); + result = DataType.valueOf(StringUtils.upperCase(super.getString(Constants.Properties.DATA_TYPE))); } catch (IllegalArgumentException e) { - this.getLogger().warn("Invalid index dataType value {}.", super.getString(Constants.Properties.DATA_TYPE)); + this.getLogger().warn("INVALID index dataType value {}.", super.getString(Constants.Properties.DATA_TYPE)); } return result; } @@ -101,8 +102,9 @@ public DataType getDataType() { * * @param dataType the data type. */ - public void setDataType(DataType dataType) { + public RangeIndex dataType(DataType dataType) { super.set(Constants.Properties.DATA_TYPE, dataType.name()); + return this; } /** @@ -110,7 +112,7 @@ public void setDataType(DataType dataType) { * * @return the precision. */ - public int getPrecision() { + public int precision() { return super.getInt(Constants.Properties.PRECISION); } @@ -119,8 +121,9 @@ public int getPrecision() { * * @param precision the precision. */ - public void setPrecision(int precision) { + public RangeIndex precision(int precision) { super.set(Constants.Properties.PRECISION, precision); + return this; } boolean hasPrecision() { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ReplicationPolicy.java b/commons/src/main/java/com/azure/data/cosmos/ReplicationPolicy.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ReplicationPolicy.java rename to commons/src/main/java/com/azure/data/cosmos/ReplicationPolicy.java index 727fcd588b63a..30767a13db259 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ReplicationPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/ReplicationPolicy.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Encapsulates the replication policy in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/RequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/RequestOptions.java similarity index 99% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/RequestOptions.java rename to commons/src/main/java/com/azure/data/cosmos/RequestOptions.java index 9a9e77a3503e0..5515ea15a8aee 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/RequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/RequestOptions.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.HashMap; import java.util.List; @@ -291,7 +291,7 @@ public void setPopulateQuotaInfo(boolean populateQuotaInfo) { * Sets the custom request option value by key * * @param name a string representing the custom option's name - * @param value a String representing the custom option's value + * @param value a STRING representing the custom option's value */ public void setHeader(String name, String value) { if (this.customOptions == null) { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java b/commons/src/main/java/com/azure/data/cosmos/Resource.java similarity index 79% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java rename to commons/src/main/java/com/azure/data/cosmos/Resource.java index da3d723b3e0b5..1f90025ffef98 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Resource.java +++ b/commons/src/main/java/com/azure/data/cosmos/Resource.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.time.Instant; import java.time.OffsetDateTime; @@ -29,7 +29,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents the base resource in the Azure Cosmos DB database service. @@ -39,15 +39,16 @@ public class Resource extends JsonSerializable { /** * Copy constructor. + * * @param resource resource to by copied. */ protected Resource(Resource resource) { - this.setId(resource.getId()); - this.setResourceId(resource.getResourceId()); - this.setSelfLink(resource.getSelfLink()); - this.setAltLink(resource.getAltLink()); - this.setTimestamp(resource.getTimestamp()); - this.setETag(resource.getETag()); + this.id(resource.id()); + this.resourceId(resource.resourceId()); + this.selfLink(resource.selfLink()); + this.altLink(resource.altLink()); + this.timestamp(resource.timestamp()); + this.etag(resource.etag()); } /** @@ -60,7 +61,8 @@ protected Resource() { /** * Constructor. * - * @param objectNode the {@link ObjectNode} that represent the {@link JsonSerializable} + * @param objectNode the {@link ObjectNode} that represent the + * {@link JsonSerializable} */ Resource(ObjectNode objectNode) { super(objectNode); @@ -69,14 +71,14 @@ protected Resource() { /** * Constructor. * - * @param jsonString the json string that represents the resource. + * @param jsonString the json string that represents the resource. * @param objectMapper the custom object mapper */ Resource(String jsonString, ObjectMapper objectMapper) { // TODO: Made package private due to #153. #171 adding custom serialization options back. super(jsonString, objectMapper); } - + /** * Constructor. * @@ -91,7 +93,7 @@ protected Resource(String jsonString) { * * @return the name of the resource. */ - public String getId() { + public String id() { return super.getString(Constants.Properties.ID); } @@ -100,8 +102,9 @@ public String getId() { * * @param id the name of the resource. */ - public void setId(String id) { + public Resource id(String id) { super.set(Constants.Properties.ID, id); + return this; } /** @@ -109,17 +112,19 @@ public void setId(String id) { * * @return the ID associated with the resource. */ - public String getResourceId() { + public String resourceId() { return super.getString(Constants.Properties.R_ID); } + // TODO: make private /** * Set the ID associated with the resource. * * @param resourceId the ID associated with the resource. */ - public void setResourceId(String resourceId) { + public Resource resourceId(String resourceId) { super.set(Constants.Properties.R_ID, resourceId); + return this; } /** @@ -127,7 +132,7 @@ public void setResourceId(String resourceId) { * * @return the self link. */ - public String getSelfLink() { + public String selfLink() { return super.getString(Constants.Properties.SELF_LINK); } @@ -136,8 +141,9 @@ public String getSelfLink() { * * @param selfLink the self link. */ - void setSelfLink(String selfLink) { + Resource selfLink(String selfLink) { super.set(Constants.Properties.SELF_LINK, selfLink); + return this; } /** @@ -145,9 +151,10 @@ void setSelfLink(String selfLink) { * * @return the timestamp. */ - public OffsetDateTime getTimestamp() { + public OffsetDateTime timestamp() { Long seconds = super.getLong(Constants.Properties.LAST_MODIFIED); - if (seconds == null) return null; + if (seconds == null) + return null; return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds.longValue()), ZoneOffset.UTC); } @@ -156,9 +163,10 @@ public OffsetDateTime getTimestamp() { * * @param timestamp the timestamp. */ - void setTimestamp(OffsetDateTime timestamp) { + Resource timestamp(OffsetDateTime timestamp) { long seconds = timestamp.toEpochSecond(); super.set(Constants.Properties.LAST_MODIFIED, seconds); + return this; } /** @@ -166,7 +174,7 @@ void setTimestamp(OffsetDateTime timestamp) { * * @return the e tag. */ - public String getETag() { + public String etag() { return super.getString(Constants.Properties.E_TAG); } @@ -175,22 +183,27 @@ public String getETag() { * * @param eTag the e tag. */ - void setETag(String eTag) { + Resource etag(String eTag) { super.set(Constants.Properties.E_TAG, eTag); + return this; } /** - * Sets the alt-link associated with the resource from the Azure Cosmos DB service. + * Sets the alt-link associated with the resource from the Azure Cosmos DB + * service. + * * @param altLink */ - void setAltLink(String altLink) { + Resource altLink(String altLink) { this.altLink = altLink; + return this; } /** - * Gets the alt-link associated with the resource from the Azure Cosmos DB service. + * Gets the alt-link associated with the resource from the Azure Cosmos DB + * service. */ - String getAltLink() { + String altLink() { return this.altLink; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/ResourceResponse.java b/commons/src/main/java/com/azure/data/cosmos/ResourceResponse.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/ResourceResponse.java rename to commons/src/main/java/com/azure/data/cosmos/ResourceResponse.java index d92db72637004..c4769a675ef20 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/ResourceResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/ResourceResponse.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.time.Duration; import java.util.HashMap; @@ -29,9 +29,9 @@ import org.apache.commons.lang3.StringUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; /** * Represents the service response to a request made from DocumentClient in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/RetryOptions.java b/commons/src/main/java/com/azure/data/cosmos/RetryOptions.java similarity index 92% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/RetryOptions.java rename to commons/src/main/java/com/azure/data/cosmos/RetryOptions.java index 2fb19427228cd..bb9ec32572d33 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/RetryOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/RetryOptions.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Encapsulates retry options in the Azure Cosmos DB database service. @@ -45,7 +45,7 @@ public RetryOptions() { * * @return the maximum number of retries. */ - public int getMaxRetryAttemptsOnThrottledRequests() { + public int maxRetryAttemptsOnThrottledRequests() { return this.maxRetryAttemptsOnThrottledRequests; } @@ -66,12 +66,13 @@ public int getMaxRetryAttemptsOnThrottledRequests() { * @param maxRetryAttemptsOnThrottledRequests the max number of retry attempts on failed requests due to a * throttle error. */ - public void setMaxRetryAttemptsOnThrottledRequests(int maxRetryAttemptsOnThrottledRequests) { + public RetryOptions maxRetryAttemptsOnThrottledRequests(int maxRetryAttemptsOnThrottledRequests) { if (maxRetryAttemptsOnThrottledRequests < 0) { throw new IllegalArgumentException("maxRetryAttemptsOnThrottledRequests value must be a positive integer."); } this.maxRetryAttemptsOnThrottledRequests = maxRetryAttemptsOnThrottledRequests; + return this; } /** @@ -79,7 +80,7 @@ public void setMaxRetryAttemptsOnThrottledRequests(int maxRetryAttemptsOnThrottl * * @return the maximum retry time in seconds. */ - public int getMaxRetryWaitTimeInSeconds() { + public int maxRetryWaitTimeInSeconds() { return this.maxRetryWaitTimeInSeconds; } @@ -97,13 +98,14 @@ public int getMaxRetryWaitTimeInSeconds() { * * @param maxRetryWaitTimeInSeconds the maximum number of seconds a request will be retried. */ - public void setMaxRetryWaitTimeInSeconds(int maxRetryWaitTimeInSeconds) { + public RetryOptions maxRetryWaitTimeInSeconds(int maxRetryWaitTimeInSeconds) { if (maxRetryWaitTimeInSeconds < 0 || maxRetryWaitTimeInSeconds > Integer.MAX_VALUE / 1000) { throw new IllegalArgumentException( "value must be a positive integer between the range of 0 to " + Integer.MAX_VALUE / 1000); } this.maxRetryWaitTimeInSeconds = maxRetryWaitTimeInSeconds; + return this; } @Override diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/RuntimeExecutionTimes.java b/commons/src/main/java/com/azure/data/cosmos/RuntimeExecutionTimes.java similarity index 99% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/RuntimeExecutionTimes.java rename to commons/src/main/java/com/azure/data/cosmos/RuntimeExecutionTimes.java index 0beb503a80ab0..de7eb4754a384 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/RuntimeExecutionTimes.java +++ b/commons/src/main/java/com/azure/data/cosmos/RuntimeExecutionTimes.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.time.Duration; import java.util.Collection; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/SerializationFormattingPolicy.java b/commons/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/SerializationFormattingPolicy.java rename to commons/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java index bd753f5e394c5..fde6c6334ee6d 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/SerializationFormattingPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * The formatting policy associated with JSON serialization in the Azure Cosmos DB database service. @@ -31,10 +31,10 @@ public enum SerializationFormattingPolicy { /** * No additional formatting required. */ - None, + NONE, /** * Indent the fields appropriately. */ - Indented + INDENTED } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/SpatialIndex.java b/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java similarity index 79% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/SpatialIndex.java rename to commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java index a263640bcb3db..f710156705554 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/SpatialIndex.java +++ b/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java @@ -21,11 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents a spatial index in the Azure Cosmos DB database service. @@ -39,7 +40,7 @@ public final class SpatialIndex extends Index { *
      * {@code
      *
-     * SpatialIndex spatialIndex = new SpatialIndex(DataType.Point);
+     * SpatialIndex spatialIndex = new SpatialIndex(DataType.POINT);
      *
      * }
      * 
@@ -47,8 +48,8 @@ public final class SpatialIndex extends Index { * @param dataType specifies the target data type for the index path specification. */ public SpatialIndex(DataType dataType) { - super(IndexKind.Spatial); - this.setDataType(dataType); + super(IndexKind.SPATIAL); + this.dataType(dataType); } /** @@ -57,8 +58,8 @@ public SpatialIndex(DataType dataType) { * @param jsonString the json string that represents the index. */ public SpatialIndex(String jsonString) { - super(jsonString, IndexKind.Spatial); - if (this.getDataType() == null) { + super(jsonString, IndexKind.SPATIAL); + if (this.dataType() == null) { throw new IllegalArgumentException("The jsonString doesn't contain a valid 'dataType'."); } } @@ -68,12 +69,12 @@ public SpatialIndex(String jsonString) { * * @return the data type. */ - public DataType getDataType() { + public DataType dataType() { DataType result = null; try { - result = DataType.valueOf(WordUtils.capitalize(super.getString(Constants.Properties.DATA_TYPE))); + result = DataType.valueOf(StringUtils.upperCase(super.getString(Constants.Properties.DATA_TYPE))); } catch (IllegalArgumentException e) { - this.getLogger().warn("Invalid index dataType value {}.", super.getString(Constants.Properties.DATA_TYPE)); + this.getLogger().warn("INVALID index dataType value {}.", super.getString(Constants.Properties.DATA_TYPE)); } return result; } @@ -83,7 +84,8 @@ public DataType getDataType() { * * @param dataType the data type. */ - public void setDataType(DataType dataType) { + public SpatialIndex dataType(DataType dataType) { super.set(Constants.Properties.DATA_TYPE, dataType.name()); + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/SpatialSpec.java b/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java similarity index 89% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/SpatialSpec.java rename to commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java index 828bd08956995..abbc9de262b52 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/SpatialSpec.java +++ b/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.ArrayList; import java.util.Collection; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; public class SpatialSpec extends JsonSerializable { @@ -54,7 +54,7 @@ public SpatialSpec(String jsonString) { * * @return the path. */ - public String getPath() { + public String path() { return super.getString(Constants.Properties.PATH); } @@ -63,8 +63,9 @@ public String getPath() { * * @param path the path. */ - public void setPath(String path) { + public SpatialSpec path(String path) { super.set(Constants.Properties.PATH, path); + return this; } /** @@ -72,7 +73,7 @@ public void setPath(String path) { * * @return the collection of spatial types. */ - public Collection getSpatialTypes() { + public Collection spatialTypes() { if (this.spatialTypes == null) { this.spatialTypes = super.getCollection(Constants.Properties.TYPES, SpatialType.class); @@ -89,12 +90,13 @@ public Collection getSpatialTypes() { * * @param spatialTypes the collection of spatial types. */ - public void setSpatialTypes(Collection spatialTypes) { + public SpatialSpec spatialTypes(Collection spatialTypes) { this.spatialTypes = spatialTypes; Collection spatialTypeNames = new ArrayList(); for (SpatialType spatialType : this.spatialTypes) { spatialTypeNames.add(spatialType.name()); } super.set(Constants.Properties.TYPES, spatialTypeNames); + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/SpatialType.java b/commons/src/main/java/com/azure/data/cosmos/SpatialType.java similarity index 94% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/SpatialType.java rename to commons/src/main/java/com/azure/data/cosmos/SpatialType.java index 23ddd664f872b..06e49d72e2649 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/SpatialType.java +++ b/commons/src/main/java/com/azure/data/cosmos/SpatialType.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Defines the target data type of an index path specification in the Azure Cosmos DB service. @@ -31,21 +31,21 @@ public enum SpatialType { /** * Represent a point data type. */ - Point, + POINT, /** * Represent a line string data type. */ - LineString, + LINE_STRING, /** * Represent a polygon data type. */ - Polygon, + POLYGON, /** * Represent a multi-polygon data type. */ - MultiPolygon + MULTI_POLYGON } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/SqlParameter.java b/commons/src/main/java/com/azure/data/cosmos/SqlParameter.java similarity index 89% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/SqlParameter.java rename to commons/src/main/java/com/azure/data/cosmos/SqlParameter.java index 6d6018f04e330..e8aa7bb73a27e 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/SqlParameter.java +++ b/commons/src/main/java/com/azure/data/cosmos/SqlParameter.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Represents a SQL parameter in the SqlQuerySpec used for queries in the Azure Cosmos DB database service. @@ -44,8 +44,8 @@ public SqlParameter() { */ public SqlParameter(String name, Object value) { super(); - this.setName(name); - this.setValue(value); + this.name(name); + this.value(value); } /** @@ -53,7 +53,7 @@ public SqlParameter(String name, Object value) { * * @return the name of the parameter. */ - public String getName() { + public String name() { return super.getString("name"); } @@ -62,8 +62,9 @@ public String getName() { * * @param name the name of the parameter. */ - public void setName(String name) { + public SqlParameter name(String name) { super.set("name", name); + return this; } /** @@ -73,7 +74,7 @@ public void setName(String name) { * @param the type of the parameter * @return the value of the parameter. */ - public Object getValue(Class c) { + public Object value(Class c) { return super.getObject("value", c); } @@ -82,7 +83,8 @@ public Object getValue(Class c) { * * @param value the value of the parameter. */ - public void setValue(Object value) { + public SqlParameter value(Object value) { super.set("value", value); + return this; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/SqlParameterCollection.java b/commons/src/main/java/com/azure/data/cosmos/SqlParameterCollection.java similarity index 99% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/SqlParameterCollection.java rename to commons/src/main/java/com/azure/data/cosmos/SqlParameterCollection.java index 8d7a5bcbe8ac9..6e59d37c4c5ce 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/SqlParameterCollection.java +++ b/commons/src/main/java/com/azure/data/cosmos/SqlParameterCollection.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.ArrayList; import java.util.Arrays; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/SqlQuerySpec.java b/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java similarity index 90% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/SqlQuerySpec.java rename to commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java index a73f3112c83ac..556e85df77935 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/SqlQuerySpec.java +++ b/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.ArrayList; import java.util.Collection; @@ -49,7 +49,7 @@ public SqlQuerySpec() { */ public SqlQuerySpec(String queryText) { super(); - this.setQueryText(queryText); + this.queryText(queryText); } /** @@ -61,7 +61,7 @@ public SqlQuerySpec(String queryText) { */ public SqlQuerySpec(String queryText, SqlParameterCollection parameters) { super(); - this.setQueryText(queryText); + this.queryText(queryText); this.parameters = parameters; } @@ -70,7 +70,7 @@ public SqlQuerySpec(String queryText, SqlParameterCollection parameters) { * * @return the query text. */ - public String getQueryText() { + public String queryText() { return super.getString("query"); } @@ -80,8 +80,9 @@ public String getQueryText() { * @param queryText * the query text. */ - public void setQueryText(String queryText) { + public SqlQuerySpec queryText(String queryText) { super.set("query", queryText); + return this; } /** @@ -89,7 +90,7 @@ public void setQueryText(String queryText) { * * @return the query parameters. */ - public SqlParameterCollection getParameters() { + public SqlParameterCollection parameters() { if (this.parameters == null) { Collection sqlParameters = super.getCollection("parameters", SqlParameter.class); if (sqlParameters == null) { @@ -108,8 +109,9 @@ public SqlParameterCollection getParameters() { * @param parameters * the query parameters. */ - public void setParameters(SqlParameterCollection parameters) { + public SqlQuerySpec parameters(SqlParameterCollection parameters) { this.parameters = parameters; + return this; } @Override diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/StoredProcedure.java b/commons/src/main/java/com/azure/data/cosmos/StoredProcedure.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/StoredProcedure.java rename to commons/src/main/java/com/azure/data/cosmos/StoredProcedure.java index 0972ca2f57a71..51fde631af21a 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/StoredProcedure.java +++ b/commons/src/main/java/com/azure/data/cosmos/StoredProcedure.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents a stored procedure in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/StoredProcedureResponse.java b/commons/src/main/java/com/azure/data/cosmos/StoredProcedureResponse.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/StoredProcedureResponse.java rename to commons/src/main/java/com/azure/data/cosmos/StoredProcedureResponse.java index ea358de0d579c..01c3e4ff225b7 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/StoredProcedureResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/StoredProcedureResponse.java @@ -21,15 +21,15 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; /** * Represents the response returned from a stored procedure in the Azure Cosmos DB database service. @@ -104,7 +104,7 @@ public double getRequestCharge() { try { return Double.valueOf(value); } catch (NumberFormatException e) { - logger.warn("Invalid x-ms-request-charge value {}.", value); + logger.warn("INVALID x-ms-request-charge value {}.", value); return 0; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/TokenResolver.java b/commons/src/main/java/com/azure/data/cosmos/TokenResolver.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/TokenResolver.java rename to commons/src/main/java/com/azure/data/cosmos/TokenResolver.java index 363626a557ff5..67fc295d87861 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/TokenResolver.java +++ b/commons/src/main/java/com/azure/data/cosmos/TokenResolver.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.Map; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Trigger.java b/commons/src/main/java/com/azure/data/cosmos/Trigger.java similarity index 86% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Trigger.java rename to commons/src/main/java/com/azure/data/cosmos/Trigger.java index 2b71da26710f0..4a92e07454f38 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Trigger.java +++ b/commons/src/main/java/com/azure/data/cosmos/Trigger.java @@ -21,10 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents a trigger in the Azure Cosmos DB database service. @@ -74,13 +75,13 @@ public void setBody(String body) { * @return the trigger type. */ public TriggerType getTriggerType() { - TriggerType result = TriggerType.Pre; + TriggerType result = TriggerType.PRE; try { result = TriggerType.valueOf( - WordUtils.capitalize(super.getString(Constants.Properties.TRIGGER_TYPE))); + StringUtils.upperCase(super.getString(Constants.Properties.TRIGGER_TYPE))); } catch (IllegalArgumentException e) { // ignore the exception and return the default - this.getLogger().warn("Invalid triggerType value {}.", super.getString(Constants.Properties.TRIGGER_TYPE)); + this.getLogger().warn("INVALID triggerType value {}.", super.getString(Constants.Properties.TRIGGER_TYPE)); } return result; } @@ -100,13 +101,13 @@ public void setTriggerType(TriggerType triggerType) { * @return the trigger operation. */ public TriggerOperation getTriggerOperation() { - TriggerOperation result = TriggerOperation.Create; + TriggerOperation result = TriggerOperation.CREATE; try { result = TriggerOperation.valueOf( - WordUtils.capitalize(super.getString(Constants.Properties.TRIGGER_OPERATION))); + StringUtils.upperCase(super.getString(Constants.Properties.TRIGGER_OPERATION))); } catch (IllegalArgumentException e) { // ignore the exception and return the default - this.getLogger().warn("Invalid triggerOperation value {}.", super.getString(Constants.Properties.TRIGGER_OPERATION)); + this.getLogger().warn("INVALID triggerOperation value {}.", super.getString(Constants.Properties.TRIGGER_OPERATION)); } return result; } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/TriggerOperation.java b/commons/src/main/java/com/azure/data/cosmos/TriggerOperation.java similarity index 86% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/TriggerOperation.java rename to commons/src/main/java/com/azure/data/cosmos/TriggerOperation.java index 084250371a945..ea2dd535d5593 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/TriggerOperation.java +++ b/commons/src/main/java/com/azure/data/cosmos/TriggerOperation.java @@ -21,36 +21,36 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Specifies the operations on which a trigger should be executed in the Azure Cosmos DB database service. */ public enum TriggerOperation { /** - * All operations. + * ALL operations. */ - All(0x0), + ALL(0x0), /** - * Create operations only. + * CREATE operations only. */ - Create(0x1), + CREATE(0x1), /** - * Update operations only. + * UPDATE operations only. */ - Update(0x2), + UPDATE(0x2), /** - * Delete operations only. + * DELETE operations only. */ - Delete(0x3), + DELETE(0x3), /** - * Replace operations only. + * REPLACE operations only. */ - Replace(0x4); + REPLACE(0x4); private int value; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/TriggerType.java b/commons/src/main/java/com/azure/data/cosmos/TriggerType.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/TriggerType.java rename to commons/src/main/java/com/azure/data/cosmos/TriggerType.java index 9f46d79cd916a..60ad25f4ccc5f 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/TriggerType.java +++ b/commons/src/main/java/com/azure/data/cosmos/TriggerType.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * The trigger type in the Azure Cosmos DB database service. @@ -30,12 +30,12 @@ public enum TriggerType { /** * Trigger should be executed before the associated operation(s). */ - Pre(0x0), + PRE(0x0), /** * Trigger should be executed after the associated operation(s). */ - Post(0x1); + POST(0x1); private int value; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/Undefined.java b/commons/src/main/java/com/azure/data/cosmos/Undefined.java similarity index 94% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/Undefined.java rename to commons/src/main/java/com/azure/data/cosmos/Undefined.java index ceb3fc06bb040..e0951a340278a 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/Undefined.java +++ b/commons/src/main/java/com/azure/data/cosmos/Undefined.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; /** * Represents the 'Undefined' partition key in the Azure Cosmos DB database service. @@ -31,7 +31,7 @@ public class Undefined extends JsonSerializable { private final static Undefined value = new Undefined(); /** - * Constructor. Create a new instance of the Undefined object. + * Constructor. CREATE a new instance of the Undefined object. */ private Undefined() { } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/UniqueKey.java b/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java similarity index 93% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/UniqueKey.java rename to commons/src/main/java/com/azure/data/cosmos/UniqueKey.java index 7a60410c8fbef..658fd4f701cbf 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/UniqueKey.java +++ b/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java @@ -20,12 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.ArrayList; import java.util.Collection; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents a unique key on that enforces uniqueness constraint on documents in the collection in the Azure Cosmos DB service. @@ -54,7 +54,7 @@ public UniqueKey(String jsonString) { * * @return the unique paths. */ - public Collection getPaths() { + public Collection paths() { if (this.paths == null) { this.paths = super.getCollection(Constants.Properties.PATHS, String.class); @@ -75,8 +75,9 @@ public Collection getPaths() { * * @param paths the unique paths. */ - public void setPaths(Collection paths) { + public UniqueKey paths(Collection paths) { this.paths = paths; + return this; } @Override diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/UniqueKeyPolicy.java b/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java similarity index 92% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/UniqueKeyPolicy.java rename to commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java index 26e5983eaf778..8c5ae6d803d3f 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/UniqueKeyPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java @@ -20,12 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.ArrayList; import java.util.Collection; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents the unique key policy configuration for specifying uniqueness constraints on documents in the @@ -53,7 +53,7 @@ public UniqueKeyPolicy(String jsonString) { * * @return the unique keys. */ - public Collection getUniqueKeys() { + public Collection uniqueKeys() { if (this.uniqueKeys == null) { this.uniqueKeys = super.getCollection(Constants.Properties.UNIQUE_KEYS, UniqueKey.class); if (this.uniqueKeys == null) { @@ -63,11 +63,12 @@ public Collection getUniqueKeys() { return this.uniqueKeys; } - public void setUniqueKeys(Collection uniqueKeys) { + public UniqueKeyPolicy uniqueKeys(Collection uniqueKeys) { if (uniqueKeys == null) { throw new IllegalArgumentException("uniqueKeys cannot be null."); } this.uniqueKeys = uniqueKeys; + return this; } @Override diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/User.java b/commons/src/main/java/com/azure/data/cosmos/User.java similarity index 93% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/User.java rename to commons/src/main/java/com/azure/data/cosmos/User.java index f3a0137051e04..a841aaeaedd76 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/User.java +++ b/commons/src/main/java/com/azure/data/cosmos/User.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents a database user in the Azure Cosmos DB database service. @@ -52,7 +52,7 @@ public User(String jsonString) { * @return the permissions link. */ public String getPermissionsLink() { - String selfLink = this.getSelfLink(); + String selfLink = this.selfLink(); if (selfLink.endsWith("/")) { return selfLink + super.getString(Constants.Properties.PERMISSIONS_LINK); } else { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/UserDefinedFunction.java b/commons/src/main/java/com/azure/data/cosmos/UserDefinedFunction.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/UserDefinedFunction.java rename to commons/src/main/java/com/azure/data/cosmos/UserDefinedFunction.java index 7cfb585ead3e9..060c249d6c42d 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/UserDefinedFunction.java +++ b/commons/src/main/java/com/azure/data/cosmos/UserDefinedFunction.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; /** * Represents a user defined function in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Address.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Address.java similarity index 94% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Address.java rename to commons/src/main/java/com/azure/data/cosmos/directconnectivity/Address.java index ac09a6669e5d8..718685fec5241 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Address.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Address.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.Constants; /** * Used internally to represent a physical address in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressInformation.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/AddressInformation.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressInformation.java rename to commons/src/main/java/com/azure/data/cosmos/directconnectivity/AddressInformation.java index 10ecf29854c25..642bdfe24186c 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressInformation.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/AddressInformation.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import java.util.Objects; @@ -86,9 +86,9 @@ private static Protocol scheme2protocol(String scheme) { switch (scheme.toLowerCase()) { case "https": - return Protocol.Https; + return Protocol.HTTPS; case "rntbd": - return Protocol.Tcp; + return Protocol.TCP; default: throw new IllegalArgumentException(String.format("scheme: %s", scheme)); } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GoneException.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java similarity index 89% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GoneException.java rename to commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java index 04aaaf9cb138a..f22da6227ea2c 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GoneException.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java @@ -21,21 +21,21 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.Strings; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; import java.util.HashMap; import java.util.Map; -public class GoneException extends DocumentClientException { +public class GoneException extends CosmosClientException { public GoneException(String msg) { this(msg, null); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpUtils.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/HttpUtils.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpUtils.java rename to commons/src/main/java/com/azure/data/cosmos/directconnectivity/HttpUtils.java index 13bbb27aee3fe..08464546286d4 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpUtils.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/HttpUtils.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.internal.Constants.UrlEncodingInfo; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.internal.Constants.UrlEncodingInfo; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Strings; import io.reactivex.netty.protocol.http.client.HttpRequestHeaders; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import org.apache.commons.lang3.StringUtils; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Protocol.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Protocol.java similarity index 91% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Protocol.java rename to commons/src/main/java/com/azure/data/cosmos/directconnectivity/Protocol.java index 5f5c1d7ef6a28..b49ad34a907e8 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Protocol.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Protocol.java @@ -21,16 +21,16 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; public enum Protocol { - Https, Tcp; + HTTPS, TCP; String scheme() { switch (this) { - case Https: + case HTTPS: return "https"; - case Tcp: + case TCP: return "rntbd"; default: throw new IllegalStateException(); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestTimeoutException.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java similarity index 88% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestTimeoutException.java rename to commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java index 836d4b3935dc0..d1a1c3f56102a 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestTimeoutException.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java @@ -21,20 +21,20 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.Strings; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; import java.util.Map; -public class RequestTimeoutException extends DocumentClientException { +public class RequestTimeoutException extends CosmosClientException { public RequestTimeoutException() { this(RMResources.RequestTimeout, null); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponse.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponse.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponse.java rename to commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponse.java index 816918cc7512f..94d1d7dfb95e0 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponse.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.ClientSideRequestStatistics; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.internal.HttpConstants; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResult.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java similarity index 81% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResult.java rename to commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java index 9dbb0d4160522..7154fc3a6f831 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResult.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java @@ -21,17 +21,17 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.ISessionToken; -import com.microsoft.azure.cosmosdb.internal.InternalServerErrorException; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.rx.internal.Exceptions; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ISessionToken; +import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.Exceptions; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,7 +41,7 @@ public class StoreResult { private final static Logger logger = LoggerFactory.getLogger(StoreResult.class); private final StoreResponse storeResponse; - private final DocumentClientException exception; + private final CosmosClientException exception; final public long lsn; final public String partitionKeyRangeId; @@ -61,7 +61,7 @@ public class StoreResult { public StoreResult( StoreResponse storeResponse, - DocumentClientException exception, + CosmosClientException exception, String partitionKeyRangeId, long lsn, long quorumAckedLsn, @@ -83,8 +83,8 @@ public StoreResult( this.currentReplicaSetSize = currentReplicaSetSize; this.currentWriteQuorum = currentWriteQuorum; this.isValid = isValid; - this.isGoneException = this.exception != null && this.exception.getStatusCode() == HttpConstants.StatusCodes.GONE; - this.isNotFoundException = this.exception != null && this.exception.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND; + this.isGoneException = this.exception != null && this.exception.statusCode() == HttpConstants.StatusCodes.GONE; + this.isNotFoundException = this.exception != null && this.exception.statusCode() == HttpConstants.StatusCodes.NOTFOUND; this.isInvalidPartitionException = this.exception != null && Exceptions.isNameCacheStale(this.exception); this.storePhysicalAddress = storePhysicalAddress; @@ -94,7 +94,7 @@ public StoreResult( this.sessionToken = sessionToken; } - public DocumentClientException getException() throws InternalServerErrorException { + public CosmosClientException getException() throws InternalServerErrorException { if (this.exception == null) { String message = "Exception should be available but found none"; assert false : message; @@ -105,11 +105,11 @@ public DocumentClientException getException() throws InternalServerErrorExceptio return exception; } - public StoreResponse toResponse() throws DocumentClientException { + public StoreResponse toResponse() throws CosmosClientException { return toResponse(null); } - public StoreResponse toResponse(RequestChargeTracker requestChargeTracker) throws DocumentClientException { + public StoreResponse toResponse(RequestChargeTracker requestChargeTracker) throws CosmosClientException { if (!this.isValid) { if (this.exception == null) { logger.error("Exception not set for invalid response"); @@ -130,9 +130,9 @@ public StoreResponse toResponse(RequestChargeTracker requestChargeTracker) throw return this.storeResponse; } - private static void setRequestCharge(StoreResponse response, DocumentClientException documentClientException, double totalRequestCharge) { - if (documentClientException != null) { - documentClientException.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_CHARGE, + private static void setRequestCharge(StoreResponse response, CosmosClientException cosmosClientException, double totalRequestCharge) { + if (cosmosClientException != null) { + cosmosClientException.responseHeaders().put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(totalRequestCharge)); } // Set total charge as final charge for the response. @@ -157,8 +157,8 @@ public String toString() { statusCode = this.storeResponse.getStatus(); subStatusCode = this.storeResponse.getSubStatusCode(); } else if (this.exception != null) { - statusCode = this.exception.getStatusCode(); - subStatusCode = this.exception.getSubStatusCode(); + statusCode = this.exception.statusCode(); + subStatusCode = this.exception.subStatusCode(); } return "storePhysicalAddress: " + this.storePhysicalAddress + diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TimeoutHelper.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/TimeoutHelper.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TimeoutHelper.java rename to commons/src/main/java/com/azure/data/cosmos/directconnectivity/TimeoutHelper.java index c870d8cf6ed99..87820baba28d8 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TimeoutHelper.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/TimeoutHelper.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import java.time.Duration; import java.time.Instant; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/WFConstants.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/WFConstants.java similarity index 99% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/WFConstants.java rename to commons/src/main/java/com/azure/data/cosmos/directconnectivity/WFConstants.java index 9d177fbffae87..f8cce3d41b647 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/WFConstants.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/WFConstants.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; public class WFConstants { public static class BackendHeaders { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/AuthorizationTokenType.java b/commons/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/AuthorizationTokenType.java rename to commons/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java index dc0e37c3dcc54..ec36d4d000981 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/AuthorizationTokenType.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; public enum AuthorizationTokenType { Invalid, diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/BadRequestException.java b/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java similarity index 88% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/BadRequestException.java rename to commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java index f9dc2cf708606..5a2304aeacd81 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/BadRequestException.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java @@ -20,13 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.HttpUtils; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; @@ -37,7 +36,7 @@ * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ -public class BadRequestException extends DocumentClientException { +public class BadRequestException extends CosmosClientException { private static final long serialVersionUID = 1L; public BadRequestException(String message, Exception innerException) { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Bytes.java b/commons/src/main/java/com/azure/data/cosmos/internal/Bytes.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Bytes.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Bytes.java index 9220f79f73a55..0c8fc14fe6ad0 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Bytes.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Bytes.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; public class Bytes { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Configs.java b/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Configs.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Configs.java index 7bd80d3fbdacd..7a338279f2634 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Configs.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.directconnectivity.Protocol; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; @@ -38,7 +38,7 @@ public class Configs { private final SslContext sslContext; private static final String PROTOCOL = "COSMOS.PROTOCOL"; - private static final Protocol DEFAULT_PROTOCOL = Protocol.Https; + private static final Protocol DEFAULT_PROTOCOL = Protocol.HTTPS; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; @@ -89,7 +89,7 @@ public SslContext getSslContext() { public Protocol getProtocol() { String protocol = getJVMConfigAsString(PROTOCOL, DEFAULT_PROTOCOL.name()); try { - return Protocol.valueOf(WordUtils.capitalize(protocol.toLowerCase())); + return Protocol.valueOf(StringUtils.upperCase(protocol.toLowerCase())); } catch (Exception e) { logger.error("Parsing protocol {} failed. Using the default {}.", protocol, DEFAULT_PROTOCOL, e); return DEFAULT_PROTOCOL; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Constants.java b/commons/src/main/java/com/azure/data/cosmos/internal/Constants.java similarity index 99% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Constants.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Constants.java index c3d11aa753d36..adc9f98681a44 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Constants.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Constants.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * Used internally. Constants in the Azure Cosmos DB database service Java SDK. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentServiceRequestContext.java b/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java similarity index 88% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentServiceRequestContext.java rename to commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java index 11adef562364d..31db81195b595 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentServiceRequestContext.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java @@ -22,20 +22,18 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.net.URL; import java.util.List; -import com.microsoft.azure.cosmosdb.ClientSideRequestStatistics; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.ISessionToken; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreResult; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreResponse; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.TimeoutHelper; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.directconnectivity.StoreResult; +import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.azure.data.cosmos.directconnectivity.TimeoutHelper; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; public class DocumentServiceRequestContext implements Cloneable{ public volatile boolean forceAddressRefresh; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Exceptions.java b/commons/src/main/java/com/azure/data/cosmos/internal/Exceptions.java similarity index 74% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Exceptions.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Exceptions.java index 08bea22645dac..c45993030547e 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Exceptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Exceptions.java @@ -20,10 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.azure.data.cosmos.CosmosClientException; /** * While this class is public, but it is not part of our published public APIs. @@ -31,20 +30,20 @@ */ public class Exceptions { - public static boolean isStatusCode(DocumentClientException e, int status) { - return status == e.getStatusCode(); + public static boolean isStatusCode(CosmosClientException e, int status) { + return status == e.statusCode(); } - public static boolean isSubStatusCode(DocumentClientException e, int subStatus) { - return subStatus == e.getSubStatusCode(); + public static boolean isSubStatusCode(CosmosClientException e, int subStatus) { + return subStatus == e.subStatusCode(); } - public static boolean isPartitionSplit(DocumentClientException e) { + public static boolean isPartitionSplit(CosmosClientException e) { return isStatusCode(e, HttpConstants.StatusCodes.GONE) && isSubStatusCode(e, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE); } - public static boolean isNameCacheStale(DocumentClientException e) { + public static boolean isNameCacheStale(CosmosClientException e) { return isStatusCode(e, HttpConstants.StatusCodes.GONE) && isSubStatusCode(e, HttpConstants.SubStatusCodes.NAME_CACHE_IS_STALE); } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/HttpClientFactory.java b/commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java similarity index 85% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/HttpClientFactory.java rename to commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java index 99967bb8b4047..dbdb4bf42ed3a 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/HttpClientFactory.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; @@ -30,9 +30,7 @@ import io.netty.handler.logging.LoggingHandler; import io.netty.handler.proxy.HttpProxyHandler; import io.netty.handler.ssl.SslContext; -import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; -import io.netty.handler.ssl.SslProvider; import io.reactivex.netty.pipeline.PipelineConfigurator; import io.reactivex.netty.pipeline.PipelineConfiguratorComposite; import io.reactivex.netty.pipeline.ssl.SSLEngineFactory; @@ -41,13 +39,9 @@ import io.reactivex.netty.protocol.http.client.CompositeHttpClientBuilder; import io.reactivex.netty.protocol.http.client.HttpClient.HttpClientConfig; import io.reactivex.netty.protocol.http.client.HttpClientPipelineConfigurator; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLException; -import com.microsoft.azure.cosmosdb.internal.Constants; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; @@ -57,7 +51,7 @@ * Helper class internally used for instantiating rx http client. */ public class HttpClientFactory { - private final static String NETWORK_LOG_CATEGORY = "com.microsoft.azure.cosmosdb.netty-network"; + private final static String NETWORK_LOG_CATEGORY = "com.azure.data.cosmos.netty-network"; private final Configs configs; private Integer maxPoolSize; @@ -101,6 +95,7 @@ public SSLEngine createSSLEngine(ByteBufAllocator allocator) { return sslContext.newEngine(allocator); } } + class SslPipelineConfiguratorUsedWithProxy implements PipelineConfigurator { private final SSLEngineFactory sslEngineFactory; @@ -112,13 +107,14 @@ private SslPipelineConfiguratorUsedWithProxy(SSLEngineFactory sslEngineFactory) @Override public void configureNewPipeline(ChannelPipeline pipeline) { final SslHandler sslHandler = new SslHandler(sslEngineFactory.createSSLEngine(pipeline.channel().alloc())); - if(proxy != null) { - pipeline.addAfter(Constants.Properties.HTTP_PROXY_HANDLER_NAME,Constants.Properties.SSL_HANDLER_NAME, sslHandler); + if (proxy != null) { + pipeline.addAfter(Constants.Properties.HTTP_PROXY_HANDLER_NAME, Constants.Properties.SSL_HANDLER_NAME, + sslHandler); } else { pipeline.addFirst(Constants.Properties.SSL_HANDLER_NAME, sslHandler); } pipeline.addAfter(Constants.Properties.SSL_HANDLER_NAME, Constants.Properties.SSL_COMPLETION_HANDLER_NAME, - new SslCompletionHandler(sslHandler.handshakeFuture())); + new SslCompletionHandler(sslHandler.handshakeFuture())); } } @@ -145,12 +141,11 @@ public CompositeHttpClientBuilder toHttpClientBuilder() { pipeline.addFirst(Constants.Properties.LOGGING_HANDLER_NAME, loggingHandler); } - if(proxy != null) { + if (proxy != null) { pipeline.addFirst(Constants.Properties.HTTP_PROXY_HANDLER_NAME, new HttpProxyHandler(proxy)); } - }) - .appendPipelineConfigurator(new SslPipelineConfiguratorUsedWithProxy<>(defaultSSLEngineFactory)) - .appendPipelineConfigurator(createClientPipelineConfigurator(configs)); + }).appendPipelineConfigurator(new SslPipelineConfiguratorUsedWithProxy<>(defaultSSLEngineFactory)) + .appendPipelineConfigurator(createClientPipelineConfigurator(configs)); if (requestTimeoutInMillis != null) { HttpClientConfig.Builder clientConfigBuilder = new HttpClientConfig.Builder(); @@ -163,11 +158,8 @@ public CompositeHttpClientBuilder toHttpClientBuilder() { private static PipelineConfigurator createClientPipelineConfigurator(Configs config) { PipelineConfigurator clientPipelineConfigurator = new PipelineConfiguratorComposite( - new HttpClientPipelineConfigurator( - config.getMaxHttpInitialLineLength(), - config.getMaxHttpHeaderSize(), - config.getMaxHttpChunkSize(), - true), + new HttpClientPipelineConfigurator(config.getMaxHttpInitialLineLength(), + config.getMaxHttpHeaderSize(), config.getMaxHttpChunkSize(), true), new HttpObjectAggregationConfigurator(config.getMaxHttpBodyLength())); return clientPipelineConfigurator; } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java b/commons/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java rename to commons/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java index 9775dad3dfc79..9d4b63288f369 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/HttpConstants.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * Used internally. HTTP constants in the Azure Cosmos DB database service Java @@ -56,7 +56,7 @@ public static class HttpHeaders { public static final String USER_AGENT = "User-Agent"; public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; public static final String IF_MATCH = "If-Match"; - public static final String IF_NONE_MATCH = "If-None-Match"; + public static final String IF_NONE_MATCH = "If-NONE-Match"; public static final String CONTENT_LENGTH = "Content-Length"; public static final String ACCEPT_ENCODING = "Accept-Encoding"; public static final String KEEP_ALIVE = "Keep-Alive"; @@ -66,11 +66,11 @@ public static class HttpHeaders { public static final String CONTENT_LANGUAGE = "Content-Language"; public static final String CONTENT_LOCATION = "Content-Location"; public static final String CONTENT_MD5 = "Content-Md5"; - public static final String CONTENT_RANGE = "Content-Range"; + public static final String CONTENT_RANGE = "Content-RANGE"; public static final String ACCEPT = "Accept"; public static final String ACCEPT_CHARSET = "Accept-Charset"; public static final String ACCEPT_LANGUAGE = "Accept-Language"; - public static final String IF_RANGE = "If-Range"; + public static final String IF_RANGE = "If-RANGE"; public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; public static final String MAX_FORWARDS = "Max-Forwards"; public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; @@ -208,7 +208,7 @@ public static class HttpHeaders { public static final String LSN = "lsn"; - // Custom DocDB JavaScript logging headers + // CUSTOM DocDB JavaScript logging headers public static final String SCRIPT_ENABLE_LOGGING = "x-ms-documentdb-script-enable-logging"; public static final String SCRIPT_LOG_RESULTS = "x-ms-documentdb-script-log-results"; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ISessionToken.java b/commons/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java similarity index 88% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ISessionToken.java rename to commons/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java index 08ce7f9c1f7e7..49c6b383e98da 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ISessionToken.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.azure.data.cosmos.CosmosClientException; /** * Models session token. @@ -40,11 +40,11 @@ public interface ISessionToken { * This is used to decide if the client can accept server's response (based on comparison between client's * and server's session token) * - * @param other Session token to validate + * @param other SESSION token to validate * @return true if this instance of session token is valid with respect to other session token; * false otherwise */ - boolean isValid(ISessionToken other) throws DocumentClientException; + boolean isValid(ISessionToken other) throws CosmosClientException; /** * Returns a new instance of session token obtained by merging this session token with @@ -55,7 +55,7 @@ public interface ISessionToken { * @param other Other session token to merge * @return Instance of merged session token */ - ISessionToken merge(ISessionToken other) throws DocumentClientException; + ISessionToken merge(ISessionToken other) throws CosmosClientException; long getLSN(); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Integers.java b/commons/src/main/java/com/azure/data/cosmos/internal/Integers.java similarity index 94% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Integers.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Integers.java index 3d9c3cb6fdcb0..2369c1c815118 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Integers.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Integers.java @@ -21,9 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; - -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +package com.azure.data.cosmos.internal; public class Integers { public static int tryParse(String value, int defaultValue) { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/InternalConstants.java b/commons/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/InternalConstants.java rename to commons/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java index 991b807d28b68..5f56ba4fbed15 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/InternalConstants.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; class InternalConstants { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/InternalServerErrorException.java b/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java similarity index 90% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/InternalServerErrorException.java rename to commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java index b6a12f08b3c62..72af9654a7f71 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/InternalServerErrorException.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java @@ -21,13 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.HttpUtils; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; @@ -41,7 +40,7 @@ * No retries should be made in this case, as either split or merge might have happened and query/readfeed * must take appropriate actions. */ -public class InternalServerErrorException extends DocumentClientException { +public class InternalServerErrorException extends CosmosClientException { public InternalServerErrorException() { this(RMResources.InternalServerError); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/JavaStreamUtils.java b/commons/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java similarity index 91% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/JavaStreamUtils.java rename to commons/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java index bc0c512236037..5e07f0b845ff3 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/JavaStreamUtils.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java @@ -21,14 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; - -import org.apache.commons.lang3.StringUtils; +package com.azure.data.cosmos.internal; import java.util.Collection; -import java.util.Iterator; import java.util.stream.Collectors; -import java.util.stream.Stream; public class JavaStreamUtils { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/LifeCycleUtils.java b/commons/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/LifeCycleUtils.java rename to commons/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java index a5bc168b5db87..5209b9a1d64f0 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/LifeCycleUtils.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Lists.java b/commons/src/main/java/com/azure/data/cosmos/internal/Lists.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Lists.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Lists.java index d3007dab83126..4287412c33b62 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Lists.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Lists.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import java.util.List; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Longs.java b/commons/src/main/java/com/azure/data/cosmos/internal/Longs.java similarity index 93% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Longs.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Longs.java index 5a8c9398385fc..757782057e061 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Longs.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Longs.java @@ -21,9 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; - -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +package com.azure.data.cosmos.internal; public class Longs { public static long tryParse(String value, long defaultValue) { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/MutableVolatile.java b/commons/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/MutableVolatile.java rename to commons/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java index 4b4c9b2338e4a..921476855f13d 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/MutableVolatile.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; public class MutableVolatile { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/OperationType.java b/commons/src/main/java/com/azure/data/cosmos/internal/OperationType.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/OperationType.java rename to commons/src/main/java/com/azure/data/cosmos/internal/OperationType.java index 05b1a484509d7..6256a7756ef85 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/OperationType.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/OperationType.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * Operation types in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/PathInfo.java b/commons/src/main/java/com/azure/data/cosmos/internal/PathInfo.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/PathInfo.java rename to commons/src/main/java/com/azure/data/cosmos/internal/PathInfo.java index b1884975d5f53..c03d3bac6d036 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/PathInfo.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/PathInfo.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * Represents a resource path's information in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/PathParser.java b/commons/src/main/java/com/azure/data/cosmos/internal/PathParser.java similarity index 94% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/PathParser.java rename to commons/src/main/java/com/azure/data/cosmos/internal/PathParser.java index c1f54819e4536..9855d6f2fe8c2 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/PathParser.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/PathParser.java @@ -21,10 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import java.util.ArrayList; -import java.util.Collection; import java.util.List; /** @@ -40,7 +39,7 @@ public static List getPathParts(String path) { while (currentIndex < path.length()) { if (path.charAt(currentIndex) != segmentSeparator) { - throw new IllegalArgumentException(String.format("Invalid path, failed at index %d.", currentIndex)); + throw new IllegalArgumentException(String.format("INVALID path, failed at index %d.", currentIndex)); } if (++currentIndex == path.length()) @@ -52,7 +51,7 @@ public static List getPathParts(String path) { while (true) { newIndex = path.indexOf(quote, newIndex); if (newIndex == -1) { - throw new IllegalArgumentException(String.format("Invalid path, failed at index %d.", currentIndex)); + throw new IllegalArgumentException(String.format("INVALID path, failed at index %d.", currentIndex)); } if (path.charAt(newIndex - 1) != '\\') { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Paths.java b/commons/src/main/java/com/azure/data/cosmos/internal/Paths.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Paths.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Paths.java index 25b0af49db4c1..de499bdc2afea 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Paths.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Paths.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * Used internally. Contains string constants to work with the paths in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/PathsHelper.java b/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/PathsHelper.java rename to commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java index f65d3f5c0e6f6..9894764217a13 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/PathsHelper.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java @@ -21,34 +21,29 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.Attachment; -import com.microsoft.azure.cosmosdb.Conflict; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.Trigger; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.Attachment; +import com.azure.data.cosmos.Conflict; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.StoredProcedure; +import com.azure.data.cosmos.Trigger; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.UserDefinedFunction; import org.apache.commons.text.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; -import com.microsoft.azure.cosmosdb.rx.internal.BadRequestException; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; - /** * Used internally to provide utility methods to work with the resource's path in the Azure Cosmos DB database service. */ @@ -153,7 +148,7 @@ public static String generatePath(ResourceType resourceType, String ownerOrResou resourceType != ResourceType.ServerPartition && resourceType != ResourceType.DatabaseAccount && resourceType != ResourceType.Topology) { - throw new IllegalStateException("Invalid resource type"); + throw new IllegalStateException("INVALID resource type"); } if(ownerOrResourceId == null) { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Quadruple.java b/commons/src/main/java/com/azure/data/cosmos/internal/Quadruple.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Quadruple.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Quadruple.java index 624c12b5148ec..612ab51ca2172 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Quadruple.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Quadruple.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * Represents class with four different generic objects. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/QueryCompatibilityMode.java b/commons/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/QueryCompatibilityMode.java rename to commons/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java index 77dba9f5c531c..191f205bbec30 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/QueryCompatibilityMode.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * A client query compatibility mode when making query request in the Azure Cosmos DB database service. Can be used diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RMResources.java b/commons/src/main/java/com/azure/data/cosmos/internal/RMResources.java similarity index 91% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RMResources.java rename to commons/src/main/java/com/azure/data/cosmos/internal/RMResources.java index 38a08c2476d58..d8c58e928e9e2 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RMResources.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RMResources.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; public class RMResources { public static final String UnknownResourceType = "Resource type %s is unknown"; public static final String InvalidDocumentCollection = "The specified document collection is invalid."; - public static final String StringArgumentNullOrEmpty = "String agument %s is null or empty"; + public static final String StringArgumentNullOrEmpty = "STRING agument %s is null or empty"; public static final String PartitionKeyAndParitionKeyRangeIdBothSpecified = "Both Partition Key and Partition Key range are Specified in %s"; public static final String PartitionKeyRangeIdOrPartitionKeyMustBeSpecified = "One of the partition key range id or partition key must be specified"; public static final String TooFewPartitionKeyComponents = "PartitionKey has fewer components than defined the collection resource."; @@ -43,7 +43,7 @@ public class RMResources { public static final String InvalidPartitionKey = "Partition key %s is invalid."; public static final String PartitionKeyMismatch = "Partition key provided either doesn't correspond to definition in the collection or doesn't match partition key field values specified in the document."; public static final String MissingPartitionKeyValue = "PartitionKey value must be supplied for this operation."; - public static final String InvalidConflictResolutionMode = "Invalid mode '%s' for setting '%s'. MODE expected is '%s'."; + public static final String InvalidConflictResolutionMode = "INVALID mode '%s' for setting '%s'. MODE expected is '%s'."; public static final String InvalidRegionsInSessionToken = "Compared session tokens '%s' and '%s' has unexpected regions."; public static final String InvalidSessionToken = "The session token provided '%s' is invalid."; public static final String ResourceTokenNotFound = "Resource token not found."; @@ -61,10 +61,10 @@ public class RMResources { public static final String UnexpectedResourceType = "ResourceType %s is unexpected."; public static final String InvalidHeaderValue = "Value '%s' specified for the header '%s' is invalid."; public static final String RequestTimeout = "Request timed out."; - public static final String GlobalStrongWriteBarrierNotMet = "Global Strong write barrier has not been met for the request."; - public static final String InvalidRequestHeaderValue = "Invalid value for request header %s: %s"; - public static final String InvalidResourceAddress = "Invalid address for resource %s: %s"; - public static final String ReadQuorumNotMet = "Read Quorum size of %d is not met for the request."; + public static final String GlobalStrongWriteBarrierNotMet = "Global STRONG write barrier has not been met for the request."; + public static final String InvalidRequestHeaderValue = "INVALID value for request header %s: %s"; + public static final String InvalidResourceAddress = "INVALID address for resource %s: %s"; + public static final String ReadQuorumNotMet = "READ Quorum size of %d is not met for the request."; public static final String ReadSessionNotAvailable = "The read session is not available for the input session token."; public static final String InvalidUrl = "InvalidUrl"; public static final String InvalidResourceUrlQuery = "The value %s specified for query %s is invalid."; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/RequestChargeTracker.java b/commons/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/RequestChargeTracker.java rename to commons/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java index 0cb8d34688358..3621fca0ff29b 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/RequestChargeTracker.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import java.util.concurrent.atomic.AtomicLong; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ResourceId.java b/commons/src/main/java/com/azure/data/cosmos/internal/ResourceId.java similarity index 99% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ResourceId.java rename to commons/src/main/java/com/azure/data/cosmos/internal/ResourceId.java index 78bd93de89465..deeba0aec6352 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ResourceId.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/ResourceId.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; @@ -72,7 +72,7 @@ public static ResourceId parse(String id) throws IllegalArgumentException { if (!pair.getKey()) { throw new IllegalArgumentException(String.format( - "Invalid resource id %s", id)); + "INVALID resource id %s", id)); } return pair.getValue(); } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ResourceTokenAuthorizationHelper.java b/commons/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ResourceTokenAuthorizationHelper.java rename to commons/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java index 9e0577917258b..f5f1f1ae83756 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ResourceTokenAuthorizationHelper.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import java.util.List; import java.util.Map; @@ -29,9 +29,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyAndResourceTokenPair; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.internal.routing.PartitionKeyAndResourceTokenPair; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; /** * This class is used internally and act as a helper in authorization of diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ResourceType.java b/commons/src/main/java/com/azure/data/cosmos/internal/ResourceType.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ResourceType.java rename to commons/src/main/java/com/azure/data/cosmos/internal/ResourceType.java index cf6a2f6094874..fb0a92940e91d 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/ResourceType.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/ResourceType.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * Resource types in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/RuntimeConstants.java b/commons/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/RuntimeConstants.java rename to commons/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java index fe1907cca044a..8d68ec3abec07 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/RuntimeConstants.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * Used internally. Runtime constants in the Azure Cosmos DB database service Java SDK. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentServiceRequest.java b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentServiceRequest.java rename to commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java index d1346deb44c0b..d373e3a2af83c 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentServiceRequest.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.io.InputStream; import java.net.URI; @@ -29,24 +29,14 @@ import java.util.HashMap; import java.util.Map; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.WFConstants; +import com.azure.data.cosmos.directconnectivity.WFConstants; import org.apache.commons.lang3.StringUtils; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedOptionsBase; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.PathInfo; -import com.microsoft.azure.cosmosdb.internal.PathsHelper; -import com.microsoft.azure.cosmosdb.internal.QueryCompatibilityMode; -import com.microsoft.azure.cosmosdb.internal.ResourceId; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.FeedOptionsBase; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import rx.Observable; import rx.observables.StringObservable; @@ -475,14 +465,14 @@ public static RxDocumentServiceRequest create(ResourceType resourceType, String queryText; switch (queryCompatibilityMode) { case SqlQuery: - if (querySpec.getParameters() != null && querySpec.getParameters().size() > 0) { + if (querySpec.parameters() != null && querySpec.parameters().size() > 0) { throw new IllegalArgumentException( String.format("Unsupported argument in query compatibility mode '{%s}'", queryCompatibilityMode.name())); } operation = OperationType.SqlQuery; - queryText = querySpec.getQueryText(); + queryText = querySpec.queryText(); break; case Default: @@ -1052,7 +1042,7 @@ private static Map getProperties(Object options) { } else if (options instanceof RequestOptions) { return ((RequestOptions) options).getProperties(); } else if (options instanceof FeedOptionsBase) { - return ((FeedOptionsBase) options).getProperties(); + return ((FeedOptionsBase) options).properties(); } else { return null; } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentServiceResponse.java b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java similarity index 87% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentServiceResponse.java rename to commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java index 0cc618257ab57..f195ca31b88cf 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentServiceResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java @@ -21,32 +21,28 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; -import com.microsoft.azure.cosmosdb.Attachment; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ClientSideRequestStatistics; -import com.microsoft.azure.cosmosdb.Conflict; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.Trigger; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.PathsHelper; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Address; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreResponse; +import com.azure.data.cosmos.Attachment; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.Conflict; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.StoredProcedure; +import com.azure.data.cosmos.Trigger; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.UserDefinedFunction; +import com.azure.data.cosmos.directconnectivity.Address; +import com.azure.data.cosmos.directconnectivity.StoreResponse; import org.apache.commons.lang3.StringUtils; import java.io.IOException; @@ -139,7 +135,7 @@ public T getResource(Class c) { throw new IllegalStateException("Failed to instantiate class object.", e); } if(PathsHelper.isPublicResource(resource)) { - BridgeInternal.setAltLink(resource, PathsHelper.generatePathForNameBased(resource, this.getOwnerFullName(),resource.getId())); + BridgeInternal.setAltLink(resource, PathsHelper.generatePathForNameBased(resource, this.getOwnerFullName(),resource.id())); } return resource; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Strings.java b/commons/src/main/java/com/azure/data/cosmos/internal/Strings.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Strings.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Strings.java index 468872ac43197..41f0b87a41937 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Strings.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Strings.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import org.apache.commons.lang3.StringUtils; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Utils.java b/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java similarity index 64% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Utils.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Utils.java index 821e25392566c..f9a78fd63bf0a 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/Utils.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java @@ -1,17 +1,17 @@ /* * The MIT License (MIT) * Copyright (c) 2018 Microsoft Corporation - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,46 +20,37 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ +package com.azure.data.cosmos.internal; -package com.microsoft.azure.cosmosdb.internal; - -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLEncoder; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Base64; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.lang3.StringUtils; - +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.DocumentCollection; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.uuid.EthernetAddress; import com.fasterxml.uuid.Generators; import com.fasterxml.uuid.impl.TimeBasedGenerator; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentCollection; +import org.apache.commons.lang3.StringUtils; + +import java.io.UnsupportedEncodingException; +import java.net.*; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; /** - * Used internally to provides utility functions for the Azure Cosmos DB database service Java SDK. + * While this class is public, but it is not part of our published public APIs. + * This is meant to be internally used only by our sdk. */ -public final class Utils { +public class Utils { private static final ZoneId GMT_ZONE_ID = ZoneId.of("GMT"); public static final Base64.Encoder Base64Encoder = Base64.getEncoder(); public static final Base64.Decoder Base64Decoder = Base64.getDecoder(); private static final ObjectMapper simpleObjectMapper = new ObjectMapper(); - private static final TimeBasedGenerator TimeUUIDGegerator = + private static final TimeBasedGenerator TimeUUIDGegerator = Generators.timeBasedGenerator(EthernetAddress.constructMulticastAddress()); // NOTE DateTimeFormatter.RFC_1123_DATE_TIME cannot be used. @@ -187,21 +178,21 @@ public static boolean IsResourceType(String resourcePathSegment) { } switch (resourcePathSegment.toLowerCase()) { - case Paths.ATTACHMENTS_PATH_SEGMENT: - case Paths.COLLECTIONS_PATH_SEGMENT: - case Paths.DATABASES_PATH_SEGMENT: - case Paths.PERMISSIONS_PATH_SEGMENT: - case Paths.USERS_PATH_SEGMENT: - case Paths.DOCUMENTS_PATH_SEGMENT: - case Paths.STORED_PROCEDURES_PATH_SEGMENT: - case Paths.TRIGGERS_PATH_SEGMENT: - case Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT: - case Paths.CONFLICTS_PATH_SEGMENT: - case Paths.PARTITION_KEY_RANGES_PATH_SEGMENT: - return true; - - default: - return false; + case Paths.ATTACHMENTS_PATH_SEGMENT: + case Paths.COLLECTIONS_PATH_SEGMENT: + case Paths.DATABASES_PATH_SEGMENT: + case Paths.PERMISSIONS_PATH_SEGMENT: + case Paths.USERS_PATH_SEGMENT: + case Paths.DOCUMENTS_PATH_SEGMENT: + case Paths.STORED_PROCEDURES_PATH_SEGMENT: + case Paths.TRIGGERS_PATH_SEGMENT: + case Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT: + case Paths.CONFLICTS_PATH_SEGMENT: + case Paths.PARTITION_KEY_RANGES_PATH_SEGMENT: + return true; + + default: + return false; } } @@ -328,8 +319,8 @@ public static Boolean isCollectionPartitioned(DocumentCollection collection) { } return collection.getPartitionKey() != null - && collection.getPartitionKey().getPaths() != null - && collection.getPartitionKey().getPaths().size() > 0; + && collection.getPartitionKey().paths() != null + && collection.getPartitionKey().paths().size() > 0; } public static boolean isCollectionChild(ResourceType type) { @@ -371,30 +362,30 @@ private static String removeLeadingQuestionMark(String path) { } public static boolean isValidConsistency(ConsistencyLevel backendConsistency, - ConsistencyLevel desiredConsistency) { + ConsistencyLevel desiredConsistency) { switch (backendConsistency) { - case Strong: - return desiredConsistency == ConsistencyLevel.Strong || - desiredConsistency == ConsistencyLevel.BoundedStaleness || - desiredConsistency == ConsistencyLevel.Session || - desiredConsistency == ConsistencyLevel.Eventual || - desiredConsistency == ConsistencyLevel.ConsistentPrefix; - - case BoundedStaleness: - return desiredConsistency == ConsistencyLevel.BoundedStaleness || - desiredConsistency == ConsistencyLevel.Session || - desiredConsistency == ConsistencyLevel.Eventual || - desiredConsistency == ConsistencyLevel.ConsistentPrefix; - - case Session: - case Eventual: - case ConsistentPrefix: - return desiredConsistency == ConsistencyLevel.Session || - desiredConsistency == ConsistencyLevel.Eventual || - desiredConsistency == ConsistencyLevel.ConsistentPrefix; - - default: - throw new IllegalArgumentException("backendConsistency"); + case STRONG: + return desiredConsistency == ConsistencyLevel.STRONG || + desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || + desiredConsistency == ConsistencyLevel.SESSION || + desiredConsistency == ConsistencyLevel.EVENTUAL || + desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; + + case BOUNDED_STALENESS: + return desiredConsistency == ConsistencyLevel.BOUNDED_STALENESS || + desiredConsistency == ConsistencyLevel.SESSION || + desiredConsistency == ConsistencyLevel.EVENTUAL || + desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; + + case SESSION: + case EVENTUAL: + case CONSISTENT_PREFIX: + return desiredConsistency == ConsistencyLevel.SESSION || + desiredConsistency == ConsistencyLevel.EVENTUAL || + desiredConsistency == ConsistencyLevel.CONSISTENT_PREFIX; + + default: + throw new IllegalArgumentException("backendConsistency"); } } @@ -418,10 +409,10 @@ public static ObjectMapper getSimpleObjectMapper() { } /** - * Returns Current Time in RFC 1123 format, e.g, + * Returns Current Time in RFC 1123 format, e.g, * Fri, 01 Dec 2017 19:22:30 GMT. - * - * @return an instance of String + * + * @return an instance of STRING */ public static String nowAsRFC1123() { ZonedDateTime now = ZonedDateTime.now(GMT_ZONE_ID); @@ -432,7 +423,142 @@ public static UUID randomUUID() { return TimeUUIDGegerator.generate(); } - public static String zonedDateTimeAsUTCRFC1123(ZonedDateTime zonedDateTime){ - return Utils.RFC_1123_DATE_TIME.format(zonedDateTime.withZoneSameInstant(GMT_ZONE_ID)); + public static String zonedDateTimeAsUTCRFC1123(OffsetDateTime offsetDateTime){ + return Utils.RFC_1123_DATE_TIME.format(offsetDateTime.atZoneSameInstant(GMT_ZONE_ID)); + } + + public static int getValueOrDefault(Integer val, int defaultValue) { + return val != null ? val.intValue() : defaultValue; + } + + public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { + + IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); + if (t != null) { + throw t; + } + } + + public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { + + NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); + if (t != null) { + throw t; + } + } + + public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { + IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); + if (t != null) { + throw t; + } + } + + public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { + + if (value) { + return null; + } + + return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); + } + + public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { + if (value) { + return null; + } + + return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); + } + + private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { + if (val != null) { + return null; + } + + return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); + } + + public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String message) { + + if (value) { + return null; + } + + return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, message)); + } + + public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { + if (value) { + return null; + } + + return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); + } + + @SuppressWarnings("unchecked") + public static O as(I i, Class klass) { + if (i == null) { + return null; + } + + if (klass.isInstance(i)) { + return (O) i; + } else { + return null; + } + } + + @SuppressWarnings("unchecked") + public static List immutableListOf() { + return Collections.EMPTY_LIST; + } + + public static List immutableListOf(V v1) { + List list = new ArrayList<>(); + list.add(v1); + return Collections.unmodifiableList(list); + } + + public static MapimmutableMapOf() { + return Collections.emptyMap(); + } + + public static MapimmutableMapOf(K k1, V v1) { + Map map = new HashMap(); + map.put(k1, v1); + map = Collections.unmodifiableMap(map); + return map; + } + + public static V firstOrDefault(List list) { + return list.size() > 0? list.get(0) : null ; + } + + public static class ValueHolder { + + public ValueHolder() { + } + + public ValueHolder(V v) { + this.v = v; + } + public V v; + + public static ValueHolder initialize(T v) { + return new ValueHolder(v); + } + } + + public static boolean tryGetValue(Map dictionary, K key, ValueHolder holder) { + // doesn't work for dictionary with null value + holder.v = dictionary.get(key); + return holder.v != null; + } + + public static boolean tryRemove(Map dictionary, K key, ValueHolder holder) { + // doesn't work for dictionary with null value + holder.v = dictionary.remove(key); + return holder.v != null; } } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/ClientSideMetrics.java b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/ClientSideMetrics.java rename to commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java index 8a93a3a16e526..f29d1c001a0ba 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/ClientSideMetrics.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.metrics; +package com.azure.data.cosmos.internal.query.metrics; import org.apache.commons.lang3.tuple.ImmutablePair; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/FetchExecutionRange.java b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/FetchExecutionRange.java rename to commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java index 30e1e341c26d6..b0cfc0a2d1bac 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/FetchExecutionRange.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.metrics; +package com.azure.data.cosmos.internal.query.metrics; import java.time.Instant; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/FetchExecutionRangeAccumulator.java b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/FetchExecutionRangeAccumulator.java rename to commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java index cb67879c01aa0..3f86b0d01aef4 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/FetchExecutionRangeAccumulator.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.metrics; +package com.azure.data.cosmos.internal.query.metrics; import org.apache.commons.lang3.time.StopWatch; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/QueryMetricsTextWriter.java b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java similarity index 99% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/QueryMetricsTextWriter.java rename to commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java index 72c6383b00544..171edf56b41d9 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/QueryMetricsTextWriter.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java @@ -1,4 +1,4 @@ -package com.microsoft.azure.cosmosdb.internal.query.metrics; +package com.azure.data.cosmos.internal.query.metrics; import org.apache.commons.lang3.StringUtils; @@ -56,7 +56,7 @@ public class QueryMetricsTextWriter extends QueryMetricsWriter { private static final String EndTimeHeader = "End Time (UTC)"; private static final String DurationHeader = "Duration (ms)"; private static final String PartitionKeyRangeIdHeader = "Partition Id"; - private static final String NumberOfDocumentsHeader = "Number of Documents"; + private static final String NumberOfDocumentsHeader = "NUMBER of Documents"; private static final String RetryCountHeader = "Retry Count"; private static final String ActivityIdHeader = "Activity Id"; @@ -66,7 +66,7 @@ public class QueryMetricsTextWriter extends QueryMetricsWriter { private static final String RunTimeHeader = "Run Time (ms)"; private static final String WaitTimeHeader = "Wait Time (ms)"; private static final String TurnaroundTimeHeader = "Turnaround Time (ms)"; - private static final String NumberOfPreemptionHeader = "Number of Preemptions"; + private static final String NumberOfPreemptionHeader = "NUMBER of Preemptions"; // Static for Partition Execution Timeline Table // private static int MaxDateTimeStringLength = LocalDateTime.MAX.toString().length(); @@ -446,7 +446,7 @@ static HashMap parseDelimitedString(String delimitedString) { String[] attributeKeyValue = StringUtils.split(attribute, "="); if (attributeKeyValue.length != 2) { - throw new NullPointerException("recieved a malformed delimited String"); + throw new NullPointerException("recieved a malformed delimited STRING"); } String attributeKey = attributeKeyValue[key]; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/QueryMetricsWriter.java b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/QueryMetricsWriter.java rename to commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java index 575760ec7b50d..62d3b660affa9 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/QueryMetricsWriter.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java @@ -1,9 +1,9 @@ -package com.microsoft.azure.cosmosdb.internal.query.metrics; +package com.azure.data.cosmos.internal.query.metrics; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.QueryMetrics; -import com.microsoft.azure.cosmosdb.QueryPreparationTimes; -import com.microsoft.azure.cosmosdb.RuntimeExecutionTimes; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.QueryPreparationTimes; +import com.azure.data.cosmos.RuntimeExecutionTimes; import org.apache.commons.lang3.tuple.ImmutablePair; import java.time.Duration; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/SchedulingStopwatch.java b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/SchedulingStopwatch.java rename to commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java index eac7270f90be1..64fbf2c103c99 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/SchedulingStopwatch.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.metrics; +package com.azure.data.cosmos.internal.query.metrics; import org.apache.commons.lang3.time.StopWatch; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/SchedulingTimeSpan.java b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/SchedulingTimeSpan.java rename to commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java index 02bd4cbd80dc6..0600e78daf637 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/SchedulingTimeSpan.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.metrics; +package com.azure.data.cosmos.internal.query.metrics; public class SchedulingTimeSpan { @@ -45,7 +45,7 @@ public class SchedulingTimeSpan { private final long waitTime; /** - * Number of times the process was preempted. + * NUMBER of times the process was preempted. */ private final long numPreemptions; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/TextTable.java b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/TextTable.java rename to commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java index ca7c711ee4f13..367384ad62bb8 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/query/metrics/TextTable.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.metrics; +package com.azure.data.cosmos.internal.query.metrics; import org.apache.commons.lang3.StringUtils; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/BoolPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/BoolPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java index eda8dd7a94224..512ad440cbebf 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/BoolPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.IOException; import java.io.OutputStream; import com.fasterxml.jackson.core.JsonGenerator; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; class BoolPartitionKeyComponent implements IPartitionKeyComponent { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/IPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/IPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java index ff21ae1d307c7..f9c8030c5c0a8 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/IPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.OutputStream; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/InfinityPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/InfinityPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java index fb5ed45050d2a..e4fca693c693e 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/InfinityPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.IOException; import java.io.OutputStream; import com.fasterxml.jackson.core.JsonGenerator; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; class InfinityPartitionKeyComponent implements IPartitionKeyComponent { @Override diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MaxNumberPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MaxNumberPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java index c88fa8889be43..555623858136f 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MaxNumberPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.IOException; import java.io.OutputStream; import com.fasterxml.jackson.core.JsonGenerator; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; class MaxNumberPartitionKeyComponent implements IPartitionKeyComponent { public static final MaxNumberPartitionKeyComponent VALUE = new MaxNumberPartitionKeyComponent(); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MaxStringPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MaxStringPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java index 0b45955919dad..22520651b6048 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MaxStringPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.IOException; import java.io.OutputStream; import com.fasterxml.jackson.core.JsonGenerator; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; class MaxStringPartitionKeyComponent implements IPartitionKeyComponent { public static final MaxStringPartitionKeyComponent VALUE = new MaxStringPartitionKeyComponent(); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MinNumberPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MinNumberPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java index 7d10d31262568..a87d99fb8ca5b 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MinNumberPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.IOException; import java.io.OutputStream; import com.fasterxml.jackson.core.JsonGenerator; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; class MinNumberPartitionKeyComponent implements IPartitionKeyComponent { public static final MinNumberPartitionKeyComponent VALUE = new MinNumberPartitionKeyComponent(); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MinStringPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MinStringPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java index 8b765dab91d3f..e60c0c547df78 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MinStringPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.IOException; import java.io.OutputStream; import com.fasterxml.jackson.core.JsonGenerator; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; class MinStringPartitionKeyComponent implements IPartitionKeyComponent { public static final MinStringPartitionKeyComponent VALUE = new MinStringPartitionKeyComponent(); diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/NullPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/NullPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java index a82585474370f..1b781c4694751 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/NullPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.IOException; import java.io.OutputStream; import com.fasterxml.jackson.core.JsonGenerator; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; class NullPartitionKeyComponent implements IPartitionKeyComponent { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/NumberPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/NumberPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java index 18eed71c03d91..ef5b56b5a324d 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/NumberPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java @@ -21,14 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.IOException; import java.io.OutputStream; -import java.math.BigInteger; import com.fasterxml.jackson.core.JsonGenerator; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; /** * Used internally to represent a number component in the partition key of the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyAndResourceTokenPair.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyAndResourceTokenPair.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java index f1c3c5241c795..66183124b6a95 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyAndResourceTokenPair.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; /** * This is the pair for Partition key and its corresponding Resource Token , diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyComponentType.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyComponentType.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java index ee1180f0a2aa5..24d8af6948aaf 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyComponentType.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; enum PartitionKeyComponentType { UNDEFINED(0x0), diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternal.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternal.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java index 35bcc575ec2bb..a91b468fcd68a 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; @@ -35,10 +35,10 @@ import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.Strings; import java.io.IOException; import java.util.ArrayList; @@ -46,7 +46,7 @@ import java.util.Iterator; import java.util.List; -import static com.microsoft.azure.cosmosdb.rx.internal.Utils.as; +import static com.azure.data.cosmos.internal.Utils.as; /** * Used internally to encapsulate internal information of a partition key in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyRangeIdentity.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java similarity index 98% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyRangeIdentity.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java index 41360c5e20b91..148c4401c58d9 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyRangeIdentity.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import org.apache.commons.lang3.StringUtils; diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/Range.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/Range.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java index e4a4d7ff8b396..1c765f7bde130 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/Range.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java @@ -21,14 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.util.Comparator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.microsoft.azure.cosmosdb.JsonSerializable; +import com.azure.data.cosmos.JsonSerializable; @JsonIgnoreProperties({ "empty", "singleValue", "hashMap" }) public final class Range> extends JsonSerializable { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/StringPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java similarity index 95% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/StringPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java index 5f373417d1cbf..104bb9ce2d421 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/StringPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java @@ -21,14 +21,14 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import com.fasterxml.jackson.core.JsonGenerator; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; class StringPartitionKeyComponent implements IPartitionKeyComponent { @@ -44,7 +44,7 @@ public StringPartitionKeyComponent(String value) { this.value = value; try { - this.utf8Value = com.microsoft.azure.cosmosdb.internal.Utils.getUTF8Bytes(value); + this.utf8Value = com.azure.data.cosmos.internal.Utils.getUTF8Bytes(value); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/UndefinedPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java similarity index 96% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/UndefinedPartitionKeyComponent.java rename to commons/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java index 8bbad5c40153c..59dc6e13655a0 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/UndefinedPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.io.IOException; import java.io.OutputStream; import com.fasterxml.jackson.core.JsonGenerator; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; class UndefinedPartitionKeyComponent implements IPartitionKeyComponent { diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/package-info.java b/commons/src/main/java/com/azure/data/cosmos/package-info.java similarity index 97% rename from commons/src/main/java/com/microsoft/azure/cosmosdb/package-info.java rename to commons/src/main/java/com/azure/data/cosmos/package-info.java index 351bf1499dc69..e7385efdf3309 100644 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/package-info.java +++ b/commons/src/main/java/com/azure/data/cosmos/package-info.java @@ -25,4 +25,4 @@ /** * This package provides Java SDK Common Resources for Azure Cosmos DB. */ -package com.microsoft.azure.cosmosdb; \ No newline at end of file +package com.azure.data.cosmos; \ No newline at end of file diff --git a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java b/commons/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java deleted file mode 100644 index 139668ae1ef50..0000000000000 --- a/commons/src/main/java/com/microsoft/azure/cosmos/CosmosTriggerSettings.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.Trigger; - -import java.util.List; -import java.util.stream.Collectors; - -public class CosmosTriggerSettings extends Trigger { - - /** - * Constructor - */ - public CosmosTriggerSettings(){ - super(); - } - - /** - * Constructor. - * - * @param jsonString the json string that represents the trigger settings. - */ - public CosmosTriggerSettings(String jsonString){ - super(jsonString); - } - - CosmosTriggerSettings(ResourceResponse response) { - super(response.getResource().toJson()); - } - - static List getFromV2Results(List results) { - return results.stream().map(trigger -> new CosmosTriggerSettings(trigger.toJson())).collect(Collectors.toList()); - } -} diff --git a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Utils.java b/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Utils.java deleted file mode 100644 index 118aa91d3f0b5..0000000000000 --- a/commons/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/Utils.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * While this class is public, but it is not part of our published public APIs. - * This is meant to be internally used only by our sdk. - */ -public class Utils { - - public static int getValueOrDefault(Integer val, int defaultValue) { - return val != null ? val.intValue() : defaultValue; - } - - public static void checkStateOrThrow(boolean value, String argumentName, String message) throws IllegalArgumentException { - - IllegalArgumentException t = checkStateOrReturnException(value, argumentName, message); - if (t != null) { - throw t; - } - } - - public static void checkNotNullOrThrow(Object val, String argumentName, String message) throws NullPointerException { - - NullPointerException t = checkNotNullOrReturnException(val, argumentName, message); - if (t != null) { - throw t; - } - } - - public static void checkStateOrThrow(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) throws IllegalArgumentException { - IllegalArgumentException t = checkStateOrReturnException(value, argumentName, argumentName, messageTemplateParams); - if (t != null) { - throw t; - } - } - - public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String message) { - - if (value) { - return null; - } - - return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, message)); - } - - public static IllegalArgumentException checkStateOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { - if (value) { - return null; - } - - return new IllegalArgumentException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); - } - - private static NullPointerException checkNotNullOrReturnException(Object val, String argumentName, String messageTemplate, Object... messageTemplateParams) { - if (val != null) { - return null; - } - - return new NullPointerException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); - } - - public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String message) { - - if (value) { - return null; - } - - return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, message)); - } - - public static BadRequestException checkRequestOrReturnException(boolean value, String argumentName, String messageTemplate, Object... messageTemplateParams) { - if (value) { - return null; - } - - return new BadRequestException(String.format("argumentName: %s, message: %s", argumentName, String.format(messageTemplate, messageTemplateParams))); - } - - @SuppressWarnings("unchecked") - public static O as(I i, Class klass) { - if (i == null) { - return null; - } - - if (klass.isInstance(i)) { - return (O) i; - } else { - return null; - } - } - - @SuppressWarnings("unchecked") - public static List immutableListOf() { - return Collections.EMPTY_LIST; - } - - public static List immutableListOf(V v1) { - List list = new ArrayList<>(); - list.add(v1); - return Collections.unmodifiableList(list); - } - - public static MapimmutableMapOf() { - return Collections.emptyMap(); - } - - public static MapimmutableMapOf(K k1, V v1) { - Map map = new HashMap(); - map.put(k1, v1); - map = Collections.unmodifiableMap(map); - return map; - } - - public static V firstOrDefault(List list) { - return list.size() > 0? list.get(0) : null ; - } - - public static class ValueHolder { - - public ValueHolder() { - } - - public ValueHolder(V v) { - this.v = v; - } - public V v; - - public static ValueHolder initialize(T v) { - return new ValueHolder(v); - } - } - - public static boolean tryGetValue(Map dictionary, K key, ValueHolder holder) { - // doesn't work for dictionary with null value - holder.v = dictionary.get(key); - return holder.v != null; - } - - public static boolean tryRemove(Map dictionary, K key, ValueHolder holder) { - // doesn't work for dictionary with null value - holder.v = dictionary.remove(key); - return holder.v != null; - } -} diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/ConflictTests.java b/commons/src/test/java/com/azure/data/cosmos/ConflictTests.java similarity index 87% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/ConflictTests.java rename to commons/src/test/java/com/azure/data/cosmos/ConflictTests.java index 9139d319d52ea..fc079c6ffb075 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/ConflictTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/ConflictTests.java @@ -21,8 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; +import com.azure.data.cosmos.Conflict; +import com.azure.data.cosmos.Document; import org.apache.commons.io.IOUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -62,9 +64,9 @@ public void getResourceType() { public void getResource() { Conflict conf = new Conflict(conflictAsString); Document doc = conf.getResource(Document.class); - assertThat(doc.getId()).isEqualTo("0007312a-a1c5-4b54-9e39-35de2367fa33"); + assertThat(doc.id()).isEqualTo("0007312a-a1c5-4b54-9e39-35de2367fa33"); assertThat(doc.getInt("regionId")).isEqualTo(2); - assertThat(doc.getResourceId()).isEqualTo("k6d9ALgBmD+ChB4AAAAAAA=="); - assertThat(doc.getETag()).isEqualTo("\"00000200-0000-0000-0000-5b6e214b0000\""); + assertThat(doc.resourceId()).isEqualTo("k6d9ALgBmD+ChB4AAAAAAA=="); + assertThat(doc.etag()).isEqualTo("\"00000200-0000-0000-0000-5b6e214b0000\""); } } diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/ConnectionPolicyTest.java b/commons/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java similarity index 82% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/ConnectionPolicyTest.java rename to commons/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java index 5b4d34817b6a5..097b4e31e8c99 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/ConnectionPolicyTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.directconnectivity.Protocol; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -34,24 +34,24 @@ public class ConnectionPolicyTest { @DataProvider(name = "connectionModeArgProvider") public Object[][] connectionModeArgProvider() { return new Object[][]{ - { ConnectionMode.Gateway }, - { ConnectionMode.Direct }, + { ConnectionMode.GATEWAY}, + { ConnectionMode.DIRECT}, }; } @Test(groups = { "unit" }, dataProvider = "connectionModeArgProvider") public void connectionMode(ConnectionMode connectionMode) { ConnectionPolicy policy = new ConnectionPolicy(); - policy.setConnectionMode(connectionMode); + policy.connectionMode(connectionMode); - assertThat(policy.getConnectionMode()).isEqualTo(connectionMode); + assertThat(policy.connectionMode()).isEqualTo(connectionMode); } @DataProvider(name = "connectionProtocolModeArgProvider") public Object[][] connectionProtocolModeArgProvider() { return new Object[][]{ - { Protocol.Https }, - { Protocol.Tcp }, + { Protocol.HTTPS}, + { Protocol.TCP}, }; } } diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentClientExceptionTest.java b/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java similarity index 53% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentClientExceptionTest.java rename to commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java index ddf535c3c577b..7b6c1f033422d 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentClientExceptionTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java @@ -21,8 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; import com.google.common.collect.ImmutableMap; import org.testng.annotations.Test; @@ -30,55 +32,55 @@ import static org.assertj.core.api.Assertions.assertThat; -public class DocumentClientExceptionTest { +public class CosmosClientExceptionTest { @Test(groups = { "unit" }) public void headerNotNull1() { - DocumentClientException dce = new DocumentClientException(0); - assertThat(dce.getResponseHeaders()).isNotNull(); - assertThat(dce.getResponseHeaders()).isEmpty(); + CosmosClientException dce = new CosmosClientException(0); + assertThat(dce.responseHeaders()).isNotNull(); + assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull2() { - DocumentClientException dce = new DocumentClientException(0, "dummy"); - assertThat(dce.getResponseHeaders()).isNotNull(); - assertThat(dce.getResponseHeaders()).isEmpty(); + CosmosClientException dce = new CosmosClientException(0, "dummy"); + assertThat(dce.responseHeaders()).isNotNull(); + assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull3() { - DocumentClientException dce = new DocumentClientException(0, new RuntimeException()); - assertThat(dce.getResponseHeaders()).isNotNull(); - assertThat(dce.getResponseHeaders()).isEmpty(); + CosmosClientException dce = new CosmosClientException(0, new RuntimeException()); + assertThat(dce.responseHeaders()).isNotNull(); + assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull4() { - DocumentClientException dce = new DocumentClientException(0, (Error) null, (Map) null); - assertThat(dce.getResponseHeaders()).isNotNull(); - assertThat(dce.getResponseHeaders()).isEmpty(); + CosmosClientException dce = new CosmosClientException(0, (Error) null, (Map) null); + assertThat(dce.responseHeaders()).isNotNull(); + assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull5() { - DocumentClientException dce = new DocumentClientException((String) null, 0, (Error) null, (Map) null); - assertThat(dce.getResponseHeaders()).isNotNull(); - assertThat(dce.getResponseHeaders()).isEmpty(); + CosmosClientException dce = new CosmosClientException((String) null, 0, (Error) null, (Map) null); + assertThat(dce.responseHeaders()).isNotNull(); + assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull6() { - DocumentClientException dce = new DocumentClientException((String) null, (Exception) null, (Map) null, 0, (String) null); - assertThat(dce.getResponseHeaders()).isNotNull(); - assertThat(dce.getResponseHeaders()).isEmpty(); + CosmosClientException dce = new CosmosClientException((String) null, (Exception) null, (Map) null, 0, (String) null); + assertThat(dce.responseHeaders()).isNotNull(); + assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull7() { ImmutableMap respHeaders = ImmutableMap.of("key", "value"); - DocumentClientException dce = new DocumentClientException((String) null, (Exception) null, respHeaders, 0, (String) null); - assertThat(dce.getResponseHeaders()).isNotNull(); - assertThat(dce.getResponseHeaders()).contains(respHeaders.entrySet().iterator().next()); + CosmosClientException dce = new CosmosClientException((String) null, (Exception) null, respHeaders, 0, (String) null); + assertThat(dce.responseHeaders()).isNotNull(); + assertThat(dce.responseHeaders()).contains(respHeaders.entrySet().iterator().next()); } } diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentCollectionTests.java b/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java similarity index 74% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentCollectionTests.java rename to commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java index 2e11ed6134e1c..daa8b7dc333c0 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentCollectionTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java @@ -21,8 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.PartitionKeyDefinitionVersion; import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; @@ -34,7 +37,7 @@ public class DocumentCollectionTests { public void getPartitionKey() { DocumentCollection collection = new DocumentCollection(); PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); - partitionKeyDefinition.setPaths(ImmutableList.of("/mypk")); + partitionKeyDefinition.paths(ImmutableList.of("/mypk")); collection.setPartitionKey(partitionKeyDefinition); assertThat(collection.getPartitionKey()).isEqualTo(partitionKeyDefinition); } @@ -43,13 +46,13 @@ public void getPartitionKey() { public void getPartitionKey_serializeAndDeserialize() { DocumentCollection collection = new DocumentCollection(); PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); - partitionKeyDefinition.setPaths(ImmutableList.of("/mypk")); - partitionKeyDefinition.setVersion(PartitionKeyDefinitionVersion.V2); + partitionKeyDefinition.paths(ImmutableList.of("/mypk")); + partitionKeyDefinition.version(PartitionKeyDefinitionVersion.V2); collection.setPartitionKey(partitionKeyDefinition); DocumentCollection parsedColl = new DocumentCollection(collection.toJson()); - assertThat(parsedColl.getPartitionKey().getKind().toString()).isEqualTo(partitionKeyDefinition.getKind().toString()); - assertThat(parsedColl.getPartitionKey().getPaths()).isEqualTo(partitionKeyDefinition.getPaths()); - assertThat(parsedColl.getPartitionKey().getVersion()).isEqualTo(partitionKeyDefinition.getVersion()); + assertThat(parsedColl.getPartitionKey().kind().toString()).isEqualTo(partitionKeyDefinition.kind().toString()); + assertThat(parsedColl.getPartitionKey().paths()).isEqualTo(partitionKeyDefinition.paths()); + assertThat(parsedColl.getPartitionKey().version()).isEqualTo(partitionKeyDefinition.version()); } } diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentTests.java b/commons/src/test/java/com/azure/data/cosmos/DocumentTests.java similarity index 91% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentTests.java rename to commons/src/test/java/com/azure/data/cosmos/DocumentTests.java index d4ed8f4c87c25..7dfaa1bff5a74 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/DocumentTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/DocumentTests.java @@ -21,11 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import static org.assertj.core.api.Assertions.assertThat; +import com.azure.data.cosmos.Document; import org.testng.annotations.Test; import java.time.OffsetDateTime; @@ -37,7 +38,7 @@ public class DocumentTests { public void timestamp() { Document d = new Document(); OffsetDateTime time = OffsetDateTime.of(2019, 8, 6, 12, 53, 29, 0, ZoneOffset.UTC); - d.setTimestamp(time); - assertThat(d.getTimestamp()).isEqualTo(time); + d.timestamp(time); + assertThat(d.timestamp()).isEqualTo(time); } } diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/IncludedPathTest.java b/commons/src/test/java/com/azure/data/cosmos/IncludedPathTest.java similarity index 80% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/IncludedPathTest.java rename to commons/src/test/java/com/azure/data/cosmos/IncludedPathTest.java index 663c2834c2061..cdbaa7b56c924 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/IncludedPathTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/IncludedPathTest.java @@ -20,12 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; +import com.azure.data.cosmos.DataType; +import com.azure.data.cosmos.IncludedPath; +import com.azure.data.cosmos.Index; import org.testng.annotations.Test; public class IncludedPathTest { @@ -36,21 +39,21 @@ public void deserialize() { " 'path': '\\/*'," + " 'indexes': [" + " {" + - " 'kind': 'Range'," + - " 'dataType': 'String'," + + " 'kind': 'RANGE'," + + " 'dataType': 'STRING'," + " 'precision': -1" + " }," + " {" + - " 'kind': 'Range'," + - " 'dataType': 'Number'," + + " 'kind': 'RANGE'," + + " 'dataType': 'NUMBER'," + " 'precision': -1" + " }" + " ]" + "}"; IncludedPath path = new IncludedPath(json); - Collection indexes = path.getIndexes(); + Collection indexes = path.indexes(); assertThat(indexes).hasSize(2); - assertThat(indexes).usingFieldByFieldElementComparator().contains(Index.Range(DataType.String, -1)); - assertThat(indexes).usingFieldByFieldElementComparator().contains(Index.Range(DataType.Number, -1)); + assertThat(indexes).usingFieldByFieldElementComparator().contains(Index.Range(DataType.STRING, -1)); + assertThat(indexes).usingFieldByFieldElementComparator().contains(Index.Range(DataType.NUMBER, -1)); } } \ No newline at end of file diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/JsonSerializableTests.java b/commons/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java similarity index 91% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/JsonSerializableTests.java rename to commons/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java index ca5c4b4af07ea..d1a04d6e3a819 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/JsonSerializableTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java @@ -1,10 +1,11 @@ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.fail; import java.io.Serializable; +import com.azure.data.cosmos.Document; import org.testng.annotations.Test; import com.fasterxml.jackson.annotation.JsonCreator; @@ -83,15 +84,15 @@ public void getObjectAndCastToClass() { // JsonSerializable Document innerDocument = new Document(); - innerDocument.setId("innerDocument"); + innerDocument.id("innerDocument"); document.set("innerDocument", innerDocument); Document readInnerDocument = document.getObject("innerDocument", Document.class); - assertThat(readInnerDocument.getId()).isEqualTo(innerDocument.getId()); + assertThat(readInnerDocument.id()).isEqualTo(innerDocument.id()); } @Test(groups = { "unit" }) public void objectMapperInvalidJsonNoQuotesForFieldAndValue() { - // Invalid Json - field and value must be quoted + // INVALID Json - field and value must be quoted try { new Document("{ field: value }"); fail("failure expected"); @@ -102,7 +103,7 @@ public void objectMapperInvalidJsonNoQuotesForFieldAndValue() { @Test(groups = { "unit" }) public void objectMapperInvalidJsonNoQuotesForField() { - // Invalid Json - field must be quoted + // INVALID Json - field must be quoted try { new Document("{ field: 'value' }"); fail("failure expected"); @@ -113,7 +114,7 @@ public void objectMapperInvalidJsonNoQuotesForField() { @Test(groups = { "unit" }) public void objectMapperInvalidJsonNoDuplicatesAllowed() { - // Invalid Json - duplicates must not exist in Json string + // INVALID Json - duplicates must not exist in Json string try { new Document("{ 'field': 'value1', 'field': 'value2' }"); fail("failure expected"); diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/PermissionTest.java b/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java similarity index 91% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/PermissionTest.java rename to commons/src/test/java/com/azure/data/cosmos/PermissionTest.java index 3a4f0edd2c6e1..8688f825115c3 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/PermissionTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java @@ -20,10 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import static org.assertj.core.api.Assertions.assertThat; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.PermissionMode; import org.testng.annotations.Test; public class PermissionTest { @@ -38,6 +41,6 @@ public void deserialize() { "}"; Permission p = new Permission(json); assertThat(p.getResourcePartitionKey()).isEqualToComparingFieldByField(new PartitionKey("/id")); - assertThat(p.getPermissionMode()).isEqualTo(PermissionMode.Read); + assertThat(p.getPermissionMode()).isEqualTo(PermissionMode.READ); } } \ No newline at end of file diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/ResourceIdTests.java b/commons/src/test/java/com/azure/data/cosmos/ResourceIdTests.java similarity index 98% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/ResourceIdTests.java rename to commons/src/test/java/com/azure/data/cosmos/ResourceIdTests.java index 62c514ac318c5..43b227fdfc00f 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/ResourceIdTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/ResourceIdTests.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import static org.assertj.core.api.Assertions.assertThat; @@ -32,7 +32,7 @@ import org.apache.commons.lang3.tuple.Pair; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.internal.ResourceId; +import com.azure.data.cosmos.internal.ResourceId; public class ResourceIdTests { diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpUtilsTest.java b/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java similarity index 95% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpUtilsTest.java rename to commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java index de52b4fa83f7c..f9dcb97d995e0 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpUtilsTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java @@ -20,19 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import static org.assertj.core.api.Assertions.assertThat; import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; import java.util.List; import java.util.Map.Entry; import java.util.Set; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.azure.data.cosmos.internal.HttpConstants; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.DefaultHttpResponse; diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponseTest.java b/commons/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseTest.java similarity index 97% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponseTest.java rename to commons/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseTest.java index d91eb8faf0fde..262bdb2fdd0ac 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponseTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import static org.assertj.core.api.Assertions.assertThat; diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/PathsHelperTest.java b/commons/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java similarity index 97% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/internal/PathsHelperTest.java rename to commons/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java index ee22d54ef1908..fd3ed3c53e836 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/PathsHelperTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java @@ -21,11 +21,8 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import org.apache.commons.lang3.StringUtils; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/RxDocumentServiceRequestTest.java b/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java similarity index 99% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/internal/RxDocumentServiceRequestTest.java rename to commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java index 2d157911e347f..7a0decd919a4f 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/RxDocumentServiceRequestTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java @@ -21,22 +21,19 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import static org.assertj.core.api.Assertions.assertThat; import java.nio.charset.StandardCharsets; import java.util.UUID; -import com.microsoft.azure.cosmosdb.Resource; import org.apache.commons.collections4.map.HashedMap; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.rx.internal.AuthorizationTokenType; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.Document; import rx.Observable; diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/TimeTokenTest.java b/commons/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java similarity index 97% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/internal/TimeTokenTest.java rename to commons/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java index 710d740ae9a06..39a4000fd2984 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/TimeTokenTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import java.time.format.DateTimeFormatter; import java.util.Locale; diff --git a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/StringPartitionKeyComponentTest.java b/commons/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java similarity index 93% rename from commons/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/StringPartitionKeyComponentTest.java rename to commons/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java index 02b0bd685d803..ec8a23046128b 100644 --- a/commons/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/StringPartitionKeyComponentTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java @@ -1,4 +1,4 @@ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/commons/src/test/resources/log4j.properties b/commons/src/test/resources/log4j.properties index 00b89ecf16b75..09c5242466d25 100644 --- a/commons/src/test/resources/log4j.properties +++ b/commons/src/test/resources/log4j.properties @@ -7,7 +7,7 @@ log4j.rootLogger=INFO, A1 log4j.category.io.netty=INFO log4j.category.io.reactivex=INFO -log4j.category.com.microsoft.azure.cosmosdb=INFO +log4j.category.com.azure.data.cosmos=INFO # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressResolver.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java similarity index 88% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressResolver.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java index 37527ab7d9ca0..550f744adf51c 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressResolver.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java @@ -21,29 +21,29 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.InternalServerErrorException; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceId; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.routing.CollectionRoutingMap; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternalHelper; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.rx.internal.BadRequestException; -import com.microsoft.azure.cosmosdb.rx.internal.ICollectionRoutingMapCache; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionException; -import com.microsoft.azure.cosmosdb.rx.internal.NotFoundException; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxCollectionCache; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceId; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Single; @@ -108,13 +108,13 @@ private static boolean isSameCollection(PartitionKeyRange initiallyResolved, Par return false; } - if (Strings.areEqual(initiallyResolved.getId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID) && - Strings.areEqual(newlyResolved.getId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { + if (Strings.areEqual(initiallyResolved.id(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID) && + Strings.areEqual(newlyResolved.id(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { return true; } - if (Strings.areEqual(initiallyResolved.getId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID) - || Strings.areEqual(newlyResolved.getId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { + if (Strings.areEqual(initiallyResolved.id(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID) + || Strings.areEqual(newlyResolved.id(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { String message = "Request was resolved to master partition and then to server partition."; assert false : message; @@ -122,13 +122,13 @@ private static boolean isSameCollection(PartitionKeyRange initiallyResolved, Par return false; } - if (ResourceId.parse(initiallyResolved.getResourceId()).getDocumentCollection() - != ResourceId.parse(newlyResolved.getResourceId()).getDocumentCollection()) { + if (ResourceId.parse(initiallyResolved.resourceId()).getDocumentCollection() + != ResourceId.parse(newlyResolved.resourceId()).getDocumentCollection()) { return false; } - if (!Strings.areEqual(initiallyResolved.getId(), newlyResolved.getId()) && - !(newlyResolved.getParents() != null && newlyResolved.getParents().contains(initiallyResolved.getId()))) { + if (!Strings.areEqual(initiallyResolved.id(), newlyResolved.id()) && + !(newlyResolved.getParents() != null && newlyResolved.getParents().contains(initiallyResolved.id()))) { // the above condition should be always false in current codebase. // We don't need to refresh any caches if we resolved to a range which is child of previously resolved range. // Quorum reads should be handled transparently as child partitions share LSNs with parent partitions which are gone. @@ -151,7 +151,7 @@ private static boolean isSameCollection(PartitionKeyRange initiallyResolved, Par * @param request Request in progress * @param targetRange Target partition key range determined by address resolver * @*/ - private void throwIfTargetChanged(RxDocumentServiceRequest request, PartitionKeyRange targetRange) throws DocumentClientException { + private void throwIfTargetChanged(RxDocumentServiceRequest request, PartitionKeyRange targetRange) throws CosmosClientException { // If new range is child of previous range, we don't need to throw any exceptions // as LSNs are continued on child ranges. if (request.requestContext.resolvedPartitionKeyRange != null && @@ -172,7 +172,7 @@ private void throwIfTargetChanged(RxDocumentServiceRequest request, PartitionKey private static void ensureRoutingMapPresent( RxDocumentServiceRequest request, CollectionRoutingMap routingMap, - DocumentCollection collection) throws DocumentClientException { + DocumentCollection collection) throws CosmosClientException { if (routingMap == null && request.getIsNameBased() && request.getPartitionKeyRangeIdentity() != null && request.getPartitionKeyRangeIdentity().getCollectionRid() != null) { // By design, if partitionkeyrangeid header is present and it contains collectionrid for collection @@ -191,7 +191,7 @@ private static void ensureRoutingMapPresent( if (routingMap == null) { logger.debug( "Routing map was not found although collection cache is upto date for collection {}", - collection.getResourceId()); + collection.resourceId()); // Routing map not found although collection was resolved correctly. NotFoundException e = new NotFoundException(); BridgeInternal.setResourceAddress(e, request.getResourceAddress()); @@ -254,7 +254,7 @@ private Single tryResolveServerPartitionAsync( Single addressesObs = this.addressCache.tryGetAddresses( request, - new PartitionKeyRangeIdentity(collection.getResourceId(), range.getId()), + new PartitionKeyRangeIdentity(collection.resourceId(), range.id()), forceRefreshPartitionAddresses); return addressesObs.flatMap(addresses -> { @@ -262,7 +262,7 @@ private Single tryResolveServerPartitionAsync( if (addresses == null) { logger.info( "Could not resolve addresses for identity {}/{}. Potentially collection cache or routing map cache is outdated. Return null - upper logic will refresh and retry. ", - new PartitionKeyRangeIdentity(collection.getResourceId(), range.getId())); + new PartitionKeyRangeIdentity(collection.resourceId(), range.id())); return Single.just(null); } @@ -277,7 +277,7 @@ private Single tryResolveServerPartitionAsync( private PartitionKeyRange tryResolveSinglePartitionCollection( RxDocumentServiceRequest request, CollectionRoutingMap routingMap, - boolean collectionCacheIsUptoDate) throws DocumentClientException { + boolean collectionCacheIsUptoDate) throws CosmosClientException { // Neither partitionkey nor partitionkeyrangeid is specified. // Three options here: // * This is non-partitioned collection and old client SDK which doesn't send partition key. In @@ -325,7 +325,7 @@ private Single resolveMasterResourceAddress(RxDocumentServiceR } PartitionKeyRange partitionKeyRange = new PartitionKeyRange(); - partitionKeyRange.setId(PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID); + partitionKeyRange.id(PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID); return Single.just(new ResolutionResult(partitionKeyRange, addresses)); }); @@ -353,7 +353,7 @@ private Single getOrRefreshRoutingMap(RxDocumentServiceRequest req Single stateObs = collectionObs.flatMap(collection -> { state.collection = collection; Single routingMapObs = - this.collectionRoutingMapCache.tryLookupAsync(collection.getResourceId(), null, request.forceCollectionRoutingMapRefresh, request.properties); + this.collectionRoutingMapCache.tryLookupAsync(collection.resourceId(), null, request.forceCollectionRoutingMapRefresh, request.properties); final DocumentCollection underlyingCollection = collection; return routingMapObs.flatMap(routingMap -> { state.routingMap = routingMap; @@ -362,7 +362,7 @@ private Single getOrRefreshRoutingMap(RxDocumentServiceRequest req state.collectionRoutingMapCacheIsUptoDate = true; request.forcePartitionKeyRangeRefresh = false; if (routingMap != null) { - return this.collectionRoutingMapCache.tryLookupAsync(underlyingCollection.getResourceId(), routingMap, request.properties) + return this.collectionRoutingMapCache.tryLookupAsync(underlyingCollection.resourceId(), routingMap, request.properties) .map(newRoutingMap -> { state.routingMap = newRoutingMap; return state; @@ -389,7 +389,7 @@ private Single getOrRefreshRoutingMap(RxDocumentServiceRequest req return newCollectionObs.flatMap(collection -> { newState.collection = collection; Single newRoutingMapObs = this.collectionRoutingMapCache.tryLookupAsync( - collection.getResourceId(), + collection.resourceId(), null, request.properties); @@ -460,7 +460,7 @@ private Single resolveAddressesAndIdentityAsync( // InvalidPartitionException if we reach wrong collection. // Also this header will be used by backend to inject collection rid into metrics for // throttled requests. - request.getHeaders().put(WFConstants.BackendHeaders.COLLECTION_RID, state.collection.getResourceId()); + request.getHeaders().put(WFConstants.BackendHeaders.COLLECTION_RID, state.collection.resourceId()); } return Single.just(funcResolutionResult); @@ -477,7 +477,7 @@ private Single resolveAddressesAndIdentityAsync( if (!funcState.collectionRoutingMapCacheIsUptoDate) { funcState.collectionRoutingMapCacheIsUptoDate = true; Single newRoutingMapObs = this.collectionRoutingMapCache.tryLookupAsync( - funcState.collection.getResourceId(), + funcState.collection.resourceId(), funcState.routingMap, request.properties); @@ -528,12 +528,12 @@ private Single resolveAddressesAndIdentityAsync( Single newRefreshStateObs = newCollectionObs.flatMap(collection -> { state.collection = collection; - if (collection.getResourceId() != state.routingMap.getCollectionUniqueId()) { + if (collection.resourceId() != state.routingMap.getCollectionUniqueId()) { // Collection cache was stale. We resolved to new Rid. routing map cache is potentially stale // for this new collection rid. Mark it as such. state.collectionRoutingMapCacheIsUptoDate = false; Single newRoutingMap = this.collectionRoutingMapCache.tryLookupAsync( - collection.getResourceId(), + collection.resourceId(), null, request.properties); @@ -561,7 +561,7 @@ private ResolutionResult handleRangeAddressResolutionFailure( RxDocumentServiceRequest request, boolean collectionCacheIsUpToDate, boolean routingMapCacheIsUpToDate, - CollectionRoutingMap routingMap) throws DocumentClientException { + CollectionRoutingMap routingMap) throws CosmosClientException { // Optimization to not refresh routing map unnecessary. As we keep track of parent child relationships, // we can determine that a range is gone just by looking up in the routing map. if (collectionCacheIsUpToDate && routingMapCacheIsUpToDate || @@ -600,7 +600,7 @@ private Single tryResolveServerPartitionByPartitionKeyRangeIdA Single addressesObs = this.addressCache.tryGetAddresses( request, - new PartitionKeyRangeIdentity(collection.getResourceId(), request.getPartitionKeyRangeIdentity().getPartitionKeyRangeId()), + new PartitionKeyRangeIdentity(collection.resourceId(), request.getPartitionKeyRangeIdentity().getPartitionKeyRangeId()), forceRefreshPartitionAddresses); return addressesObs.flatMap(addresses -> { @@ -610,7 +610,7 @@ private Single tryResolveServerPartitionByPartitionKeyRangeIdA try { return Single.just(this.handleRangeAddressResolutionFailure(request, collectionCacheIsUpToDate, routingMapCacheIsUpToDate, routingMap)); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { return Single.error(e); } } @@ -624,7 +624,7 @@ private PartitionKeyRange tryResolveServerPartitionByPartitionKey( String partitionKeyString, boolean collectionCacheUptoDate, DocumentCollection collection, - CollectionRoutingMap routingMap) throws DocumentClientException { + CollectionRoutingMap routingMap) throws CosmosClientException { if (request == null) { throw new NullPointerException("request"); } @@ -655,11 +655,11 @@ private PartitionKeyRange tryResolveServerPartitionByPartitionKey( throw new InternalServerErrorException(String.format("partition key is null '%s'", partitionKeyString)); } - if (partitionKey.equals(PartitionKeyInternal.Empty) || partitionKey.getComponents().size() == collection.getPartitionKey().getPaths().size()) { - // Although we can compute effective partition key here, in general case this Gateway can have outdated - // partition key definition cached - like if collection with same name but with Range partitioning is created. + if (partitionKey.equals(PartitionKeyInternal.Empty) || partitionKey.getComponents().size() == collection.getPartitionKey().paths().size()) { + // Although we can compute effective partition key here, in general case this GATEWAY can have outdated + // partition key definition cached - like if collection with same name but with RANGE partitioning is created. // In this case server will not pass x-ms-documentdb-collection-rid check and will return back InvalidPartitionException. - // Gateway will refresh its cache and retry. + // GATEWAY will refresh its cache and retry. String effectivePartitionKey = PartitionKeyInternalHelper.getEffectivePartitionKeyString(partitionKey, collection.getPartitionKey()); // There should be exactly one range which contains a partition key. Always. @@ -668,7 +668,7 @@ private PartitionKeyRange tryResolveServerPartitionByPartitionKey( if (collectionCacheUptoDate) { BadRequestException badRequestException = BridgeInternal.setResourceAddress(new BadRequestException(RMResources.PartitionKeyMismatch), request.getResourceAddress()); - badRequestException.getResponseHeaders().put(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_MISMATCH)); + badRequestException.responseHeaders().put(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_MISMATCH)); throw badRequestException; } @@ -677,17 +677,17 @@ private PartitionKeyRange tryResolveServerPartitionByPartitionKey( // Three things can happen: // 1. User supplied wrong partition key. // 2. Client SDK has outdated partition key definition cache and extracted wrong value from the document. - // 3. Gateway's cache is outdated. + // 3. GATEWAY's cache is outdated. // // What we will do is append x-ms-documentdb-collection-rid header and forward it to random collection partition. // * If collection rid matches, server will send back 400.1001, because it also will not be able to compute - // effective partition key. Gateway will forward this status code to client - client will handle it. - // * If collection rid doesn't match, server will send back InvalidPartiitonException and Gateway will + // effective partition key. GATEWAY will forward this status code to client - client will handle it. + // * If collection rid doesn't match, server will send back InvalidPartiitonException and GATEWAY will // refresh name routing cache - this will refresh partition key definition as well, and retry. logger.debug( "Cannot compute effective partition key. Definition has '{}' paths, values supplied has '{}' paths. Will refresh cache and retry.", - collection.getPartitionKey().getPaths().size(), + collection.getPartitionKey().paths().size(), partitionKey.getComponents().size()); return null; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressSelector.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressSelector.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java index 24727f7a07a72..bca577ce6a76d 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressSelector.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; import rx.Single; import java.net.URI; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/BarrierRequestHelper.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java similarity index 88% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/BarrierRequestHelper.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java index dabfb9d2c96ea..3e097852f291f 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/BarrierRequestHelper.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java @@ -21,21 +21,20 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.InternalServerErrorException; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.PathsHelper; -import com.microsoft.azure.cosmosdb.internal.ResourceId; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.rx.internal.AuthorizationTokenType; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; -import org.apache.commons.lang3.NotImplementedException; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.ResourceId; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.AuthorizationTokenType; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Single; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConflictException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java similarity index 88% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConflictException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java index 58f7e39d3c72b..e0e54d923e864 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConflictException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.util.Map; @@ -35,7 +35,7 @@ * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ -public class ConflictException extends DocumentClientException { +public class ConflictException extends CosmosClientException { private static final long serialVersionUID = 1L; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java similarity index 87% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyReader.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java index ab132ebbafbdb..ab3ebb10261e5 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java @@ -21,25 +21,25 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import java.util.HashMap; import java.util.List; -import com.microsoft.azure.cosmosdb.ClientSideRequestStatistics; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.ISessionToken; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.NotFoundException; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; - -import static com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ISessionToken; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; + +import static com.azure.data.cosmos.internal.Utils.ValueHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,16 +48,16 @@ /* ConsistencyLevel Replication Mode Desired ReadMode ------------------- -------------------- --------------------------------------------------------------------------- - Strong Synchronous Read from Read Quorum + STRONG Synchronous READ from READ Quorum Asynchronous Not supported - Bounded Staleness Synchronous Read from Read Quorum - Asynchronous Read from Read Quorum. Performing read barrier on Primary is unsupported. + Bounded Staleness Synchronous READ from READ Quorum + Asynchronous READ from READ Quorum. Performing read barrier on Primary is unsupported. - Session Sync/Async Read Any (With LSN Cookie) - Default to Primary as last resort (which should succeed always) + SESSION Sync/Async READ Any (With LSN Cookie) + DEFAULT to Primary as last resort (which should succeed always) - Eventual Sync/Async Read Any + EVENTUAL Sync/Async READ Any Client does validation of unsupported combinations. @@ -66,7 +66,7 @@ Default to Primary as last resort (which should succeed always) ============= 1. We do primary copy/single master replication. 2. We do sync or async replication depending on the value of DefaultConsistencyLevel on a database account. - If the database account is configured with DefaultConsistencyLevel = Strong, we do sync replication. By default, for all other values of DefaultConsistencyLevel, we do asynchronous replication. + If the database account is configured with DefaultConsistencyLevel = STRONG, we do sync replication. By default, for all other values of DefaultConsistencyLevel, we do asynchronous replication. Replica set =========== @@ -90,8 +90,8 @@ Default to Primary as last resort (which should succeed always) Quorums ======= - W = Write Quorum = Number of replicas which acknowledge a write before the primary can ack the client. It is majority set i.e. N/2 + 1 - R = Read Quorum = Set of replicas such that there is non-empty intersection between W and R that constitute N i.e. R = N -W + 1 + W = Write Quorum = NUMBER of replicas which acknowledge a write before the primary can ack the client. It is majority set i.e. N/2 + 1 + R = READ Quorum = Set of replicas such that there is non-empty intersection between W and R that constitute N i.e. R = N -W + 1 For sync replication, W is used as a majority quorum. For async replication, W = 1. We have two LSNs, one is quorum acknowledged LSN (LSN-Q) and another is what is visible to the client (LSN-C). @@ -106,14 +106,14 @@ Default to Primary as last resort (which should succeed always) N from read standpoint means number of address from BE which is returning successful response. Successful reponse: Any BE response containing LSN response header is considered successful reponse. Typically every response other than 410 is treated as succesful response. - Strong Consistency + STRONG Consistency ================== - Strong Read requires following guarantees. - * Read value is the latest that has been written. If a write operation finished. Any subsequent reads should see that value. + STRONG READ requires following guarantees. + * READ value is the latest that has been written. If a write operation finished. Any subsequent reads should see that value. * Monotonic guarantee. Any read that starts after a previous read operation, should see atleast return equal or higher version of the value. - To perform strong read we require that atleast R i.e. Read Quorum number of replicas have the value committed. To acheve that such read : - * Read R replicas. If they have the same LSN, use the read result + To perform strong read we require that atleast R i.e. READ Quorum number of replicas have the value committed. To acheve that such read : + * READ R replicas. If they have the same LSN, use the read result * If they don't have the same LSN, we will either return the result with the highest LSN observed from those R replicas, after ensuring that LSN becomes available with R replicas. * Secondary replicas are always preferred for reading. If R secondaries have returned the result but cannot agree on the resulting LSN, we can include Primary to satisfy read quorum. @@ -122,13 +122,13 @@ Default to Primary as last resort (which should succeed always) Bounded Staleness ================= Sync Replication: - Bounded staleness uses the same logic as Strong for cases where the server is using sync replication. + Bounded staleness uses the same logic as STRONG for cases where the server is using sync replication. Async Replication: For async replication, we make sure that we do not use the Primary as barrier for read quorum. This is because Primary is always going to run ahead (async replication uses W=1 on Primary). Using primary would voilate the monotonic read guarantees when we fall back to reading from secondary in the subsequent reads as they are always running slower as compared to Primary. - Session + SESSION ======= We read from secondaries one by one until we find a match for the client's session token (LSN-C). We go to primary as a last resort which should satisfy LSN-C. @@ -137,7 +137,7 @@ Availability for Bounded Staleness (for NMax = 4 and NMin = 2): When there is a partition, the minority quorum can remain available for read as long as N >= 1 When there is a partition, the minority quorum can remain available for writes as long as N >= 2 - Eventual + EVENTUAL ======== We can read from any replicas. @@ -145,21 +145,21 @@ Availability for Bounded Staleness (for NMax = 4 and NMin = 2): When there is a partition, the minority quorum can remain available for read as long as N >= 1 When there is a partition, the minority quorum can remain available for writes as long as N >= 2 - Read Retry logic + READ Retry logic ----------------- For Any NonQuorum Reads(A.K.A ReadAny); AddressCache is refreshed for following condition. 1) No Secondary Address is found in Address Cache. 2) Chosen Secondary Returned GoneException/EndpointNotFoundException. - For Quorum Read address cache is refreshed on following condition. + For Quorum READ address cache is refreshed on following condition. 1) We found only R secondary where R < RMAX. 2) We got GoneException/EndpointNotFoundException on all the secondary we contacted. */ /** - * ConsistencyReader has a dependency on both StoreReader and QuorumReader. For Bounded Staleness and Strong Consistency, it uses the Quorum Reader + * ConsistencyReader has a dependency on both StoreReader and QuorumReader. For Bounded Staleness and STRONG Consistency, it uses the Quorum Reader * to converge on a read from read quorum number of replicas. - * For Session and Eventual Consistency, it directly uses the store reader. + * For SESSION and EVENTUAL Consistency, it directly uses the store reader. */ public class ConsistencyReader { private final static int MAX_NUMBER_OF_SECONDARY_READ_RETRIES = 3; @@ -219,7 +219,7 @@ public Single readAsync(RxDocumentServiceRequest entity, ReadMode desiredReadMode; try { desiredReadMode = this.deduceReadMode(entity, targetConsistencyLevel, useSessionToken); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { return Single.error(e); } int maxReplicaCount = this.getMaxReplicaSetSize(entity); @@ -249,7 +249,7 @@ public Single readAsync(RxDocumentServiceRequest entity, return this.quorumReader.readStrongAsync(entity, readQuorumValue, desiredReadMode); case Any: - if (targetConsistencyLevel.v == ConsistencyLevel.Session) { + if (targetConsistencyLevel.v == ConsistencyLevel.SESSION) { return this.readSessionAsync(entity, desiredReadMode); } else { return this.readAnyAsync(entity, desiredReadMode); @@ -270,7 +270,7 @@ private Single readPrimaryAsync(RxDocumentServiceRequest entity, return responseObs.flatMap(response -> { try { return Single.just(response.toResponse()); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { // TODO: RxJava1 due to design flaw doesn't allow throwing checked exception // RxJava2 has fixed this design flaw, // once we switched to RxJava2 we can get rid of unnecessary catch block @@ -298,7 +298,7 @@ private Single readAnyAsync(RxDocumentServiceRequest entity, try { return Single.just(responses.get(0).toResponse()); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { // TODO: RxJava1 due to design flaw doesn't allow throwing checked exception // RxJava2 has fixed this design flaw, // once we switched to RxJava2 we can get rid of unnecessary catch block @@ -336,17 +336,17 @@ private Single readSessionAsync(RxDocumentServiceRequest entity, if (entity.requestContext.sessionToken != null && responses.get(0).sessionToken != null && !entity.requestContext.sessionToken.isValid(responses.get(0).sessionToken)) { - logger.warn("Convert to session read exception, request {} Session Lsn {}, responseLSN {}", entity.getResourceAddress(), entity.requestContext.sessionToken.convertToString(), responses.get(0).lsn); - notFoundException.getResponseHeaders().put(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)); + logger.warn("Convert to session read exception, request {} SESSION Lsn {}, responseLSN {}", entity.getResourceAddress(), entity.requestContext.sessionToken.convertToString(), responses.get(0).lsn); + notFoundException.responseHeaders().put(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)); } return Single.error(notFoundException); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { // TODO: RxJava1 due to design flaw doesn't allow throwing checked exception // so we have to catch and return // once we move to RxJava2 we can fix this. return Single.error(e); } - } catch (DocumentClientException dce) { + } catch (CosmosClientException dce) { // TODO: RxJava1 due to design flaw doesn't allow throwing checked exception // so we have to catch and return // once we move to RxJava2 we can fix this. @@ -366,9 +366,9 @@ private Single readSessionAsync(RxDocumentServiceRequest entity, ReadMode deduceReadMode(RxDocumentServiceRequest request, ValueHolder targetConsistencyLevel, - ValueHolder useSessionToken) throws DocumentClientException { + ValueHolder useSessionToken) throws CosmosClientException { targetConsistencyLevel.v = RequestHelper.GetConsistencyLevelToUse(this.serviceConfigReader, request); - useSessionToken.v = (targetConsistencyLevel.v == ConsistencyLevel.Session); + useSessionToken.v = (targetConsistencyLevel.v == ConsistencyLevel.SESSION); if (request.getDefaultReplicaIndex() != null) { // Don't use session token - this is used by internal scenarios which technically don't intend session read when they target @@ -378,23 +378,23 @@ ReadMode deduceReadMode(RxDocumentServiceRequest request, } switch (targetConsistencyLevel.v) { - case Eventual: + case EVENTUAL: return ReadMode.Any; - case ConsistentPrefix: + case CONSISTENT_PREFIX: return ReadMode.Any; - case Session: + case SESSION: return ReadMode.Any; - case BoundedStaleness: + case BOUNDED_STALENESS: return ReadMode.BoundedStaleness; - case Strong: + case STRONG: return ReadMode.Strong; default: - throw new IllegalStateException("Invalid Consistency Level " + targetConsistencyLevel.v); + throw new IllegalStateException("INVALID Consistency Level " + targetConsistencyLevel.v); } } diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyWriter.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java similarity index 92% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyWriter.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java index 2710724723c04..6c19be06c1eee 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyWriter.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java @@ -21,21 +21,21 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.ClientSideRequestStatistics; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.Integers; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.internal.SessionTokenHelper; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Integers; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.SessionTokenHelper; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.Utils; import org.apache.commons.collections4.ComparatorUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -57,8 +57,8 @@ * * The determination of whether a request is a local quorum-acked write or a globally strong write is through several factors: * 1. Request.RequestContext.OriginalRequestConsistencyLevel - ensure that original request's consistency level, if set, is strong. - * 2. Default consistency level of the accoutn should be strong. - * 3. Number of read regions returned by write response > 0. + * 2. DEFAULT consistency level of the accoutn should be strong. + * 3. NUMBER of read regions returned by write response > 0. * * For quorum-acked write: * We send single request to primary of a single partition, which will take care of replicating to its secondaries. Once write quorum number of replicas commits the write, the write request returns to the user with success. There is no additional handling for this case. @@ -164,7 +164,7 @@ Single writePrivateAsync( try { primaryURI.set(primaryUri); if (this.useMultipleWriteLocations && - RequestHelper.GetConsistencyLevelToUse(this.serviceConfigReader, request) == ConsistencyLevel.Session) { + RequestHelper.GetConsistencyLevelToUse(this.serviceConfigReader, request) == ConsistencyLevel.SESSION) { // Set session token to ensure session consistency for write requests // when writes can be issued to multiple locations SessionTokenHelper.setPartitionLocalSessionToken(request, this.sessionContainer); @@ -183,14 +183,14 @@ Single writePrivateAsync( .doOnError( t -> { try { - DocumentClientException ex = Utils.as(t, DocumentClientException.class); + CosmosClientException ex = Utils.as(t, CosmosClientException.class); try { request.requestContext.clientSideRequestStatistics.recordResponse(request, storeReader.createStoreResult(null, ex, false, false, primaryUri)); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { logger.error("Error occurred while recording response", e); } - String value = ex.getResponseHeaders().get(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH); + String value = ex.responseHeaders().get(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH); if (!Strings.isNullOrWhiteSpace(value)) { Integer result = Integers.tryParse(value); if (result != null && result == 1) { @@ -208,7 +208,7 @@ Single writePrivateAsync( try { request.requestContext.clientSideRequestStatistics.recordResponse(request, storeReader.createStoreResult(response, null, false, false, primaryURI.get())); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { logger.error("Error occurred while recording response", e); } return barrierForGlobalStrong(request, response); @@ -232,14 +232,14 @@ Single writePrivateAsync( } boolean isGlobalStrongRequest(RxDocumentServiceRequest request, StoreResponse response) { - if (this.serviceConfigReader.getDefaultConsistencyLevel() == ConsistencyLevel.Strong) { + if (this.serviceConfigReader.getDefaultConsistencyLevel() == ConsistencyLevel.STRONG) { int numberOfReadRegions = -1; String headerValue = null; if ((headerValue = response.getHeaderValue(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS)) != null) { numberOfReadRegions = Integer.parseInt(headerValue); } - if (numberOfReadRegions > 0 && this.serviceConfigReader.getDefaultConsistencyLevel() == ConsistencyLevel.Strong) { + if (numberOfReadRegions > 0 && this.serviceConfigReader.getDefaultConsistencyLevel() == ConsistencyLevel.STRONG) { return true; } } @@ -298,7 +298,7 @@ Single barrierForGlobalStrong(RxDocumentServiceRequest request, S return Single.just(response); } - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { // RxJava1 doesn't allow throwing checked exception from Observable operators return Single.error(e); } diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/CustomHeaders.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/CustomHeaders.java similarity index 95% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/CustomHeaders.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/CustomHeaders.java index 8f3f3f8e7d6ba..5842c88da2a56 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/CustomHeaders.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/CustomHeaders.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; public final class CustomHeaders { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ErrorUtils.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ErrorUtils.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ErrorUtils.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ErrorUtils.java index 5fdca7819b13f..0d1abc33dc076 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ErrorUtils.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ErrorUtils.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientResponse; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ForbiddenException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java similarity index 87% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ForbiddenException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java index d74feb5b911af..413e54f96b973 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ForbiddenException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java @@ -21,19 +21,19 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; import java.util.Map; -public class ForbiddenException extends DocumentClientException { +public class ForbiddenException extends CosmosClientException { public ForbiddenException() { this(RMResources.Forbidden); } diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayAddressCache.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java similarity index 92% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayAddressCache.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java index 3e3053fa78415..bae340f944431 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayAddressCache.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java @@ -21,28 +21,28 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.Paths; -import com.microsoft.azure.cosmosdb.internal.PathsHelper; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.rx.internal.AuthorizationTokenType; -import com.microsoft.azure.cosmosdb.rx.internal.Exceptions; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; -import com.microsoft.azure.cosmosdb.rx.internal.caches.AsyncCache; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.AuthorizationTokenType; +import com.azure.data.cosmos.internal.Exceptions; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.caches.AsyncCache; import io.netty.buffer.ByteBuf; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; @@ -57,7 +57,6 @@ import rx.Single; import java.net.MalformedURLException; -import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.time.Duration; @@ -158,8 +157,8 @@ public Single tryGetAddresses(RxDocumentServiceRequest req PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses) { - com.microsoft.azure.cosmosdb.rx.internal.Utils.checkNotNullOrThrow(request, "request", ""); - com.microsoft.azure.cosmosdb.rx.internal.Utils.checkNotNullOrThrow(partitionKeyRangeIdentity, "partitionKeyRangeIdentity", ""); + com.azure.data.cosmos.internal.Utils.checkNotNullOrThrow(request, "request", ""); + com.azure.data.cosmos.internal.Utils.checkNotNullOrThrow(partitionKeyRangeIdentity, "partitionKeyRangeIdentity", ""); if (StringUtils.equals(partitionKeyRangeIdentity.getPartitionKeyRangeId(), PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { @@ -224,7 +223,7 @@ public Single tryGetAddresses(RxDocumentServiceRequest req return addresses; }).onErrorResumeNext(ex -> { - DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(ex, DocumentClientException.class); + CosmosClientException dce = com.azure.data.cosmos.internal.Utils.as(ex, CosmosClientException.class); if (dce == null) { if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); @@ -478,7 +477,7 @@ public Completable openAsync( RxDocumentServiceRequest request = RxDocumentServiceRequest.create( OperationType.Read, // collection.AltLink, - collection.getResourceId(), + collection.resourceId(), ResourceType.DocumentCollection, // AuthorizationTokenType.PrimaryMasterKey Collections.EMPTY_MAP); @@ -490,7 +489,7 @@ public Completable openAsync( tasks.add(this.getServerAddressesViaGatewayAsync( request, - collection.getResourceId(), + collection.resourceId(), partitionKeyRangeIdentities.subList(i, endIndex). stream().map(range -> range.getPartitionKeyRangeId()).collect(Collectors.toList()), @@ -502,12 +501,12 @@ public Completable openAsync( List> addressInfos = list.stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy(address -> address.getParitionKeyRangeId())) - .entrySet().stream().map(group -> toPartitionAddressAndRange(collection.getResourceId(), group.getValue())) + .entrySet().stream().map(group -> toPartitionAddressAndRange(collection.resourceId(), group.getValue())) .collect(Collectors.toList()); for (Pair addressInfo : addressInfos) { this.serverPartitionAddressCache.set( - new PartitionKeyRangeIdentity(collection.getResourceId(), addressInfo.getLeft().getPartitionKeyRangeId()), + new PartitionKeyRangeIdentity(collection.resourceId(), addressInfo.getLeft().getPartitionKeyRangeId()), addressInfo.getRight()); } }).toCompletable(); diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfigurationReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java similarity index 90% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfigurationReader.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java index 8ce4417065d66..a7a8b4d569b35 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfigurationReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import java.net.MalformedURLException; import java.net.URI; @@ -32,17 +32,17 @@ import org.apache.commons.lang3.StringUtils; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DatabaseAccount; -import com.microsoft.azure.cosmosdb.ReplicationPolicy; -import com.microsoft.azure.cosmosdb.internal.BaseAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.rx.internal.GlobalEndpointManager; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.DatabaseAccount; +import com.azure.data.cosmos.ReplicationPolicy; +import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.GlobalEndpointManager; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; @@ -128,7 +128,7 @@ private Single getDatabaseAccountAsync(URI serviceEndpoint) { httpRequest.withHeader(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); UserAgentContainer userAgentContainer = new UserAgentContainer(); - String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); + String userAgentSuffix = this.connectionPolicy.userAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } @@ -160,7 +160,7 @@ public Single initializeReaderAsync() { try { return GlobalEndpointManager.getDatabaseAccountFromAnyLocationsAsync(this.serviceEndpoint.toURL(), - new ArrayList<>(this.connectionPolicy.getPreferredLocations()), url -> { + new ArrayList<>(this.connectionPolicy.preferredLocations()), url -> { try { return getDatabaseAccountAsync(url.toURI()); } catch (URISyntaxException e) { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java similarity index 88% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java index 3f519231d16f8..530d6c6986b90 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java @@ -21,23 +21,22 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import java.time.Duration; +import com.azure.data.cosmos.CosmosClientException; import org.apache.commons.lang3.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.Quadruple; -import com.microsoft.azure.cosmosdb.rx.internal.IDocumentClientRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.IRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionIsMigratingException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionKeyRangeIsSplittingException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Quadruple; +import com.azure.data.cosmos.internal.IRetryPolicy; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.PartitionIsMigratingException; +import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import rx.Single; @@ -72,7 +71,7 @@ public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer wai @Override public Single shouldRetry(Exception exception) { - DocumentClientException exceptionToThrow = null; + CosmosClientException exceptionToThrow = null; Duration backoffTime = Duration.ofSeconds(0); Duration timeout = Duration.ofSeconds(0); boolean forceRefreshAddressCache = false; @@ -104,7 +103,7 @@ public Single shouldRetry(Exception exception) { } else { logger.warn("Received gone exception after backoff/retry. Will fail the request. {}", exception.toString()); - exceptionToThrow = new DocumentClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, + exceptionToThrow = new CosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception); } @@ -119,7 +118,7 @@ public Single shouldRetry(Exception exception) { logger.warn( "Received partition key range gone exception after backoff/retry. Will fail the request. {}", exception.toString()); - exceptionToThrow = new DocumentClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, + exceptionToThrow = new CosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception); } } else if (exception instanceof InvalidPartitionException) { @@ -132,7 +131,7 @@ public Single shouldRetry(Exception exception) { logger.warn( "Received invalid collection partition exception after backoff/retry. Will fail the request. {}", exception.toString()); - exceptionToThrow = new DocumentClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, + exceptionToThrow = new CosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception); } } else { @@ -170,7 +169,7 @@ public Single shouldRetry(Exception exception) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Single.just(ShouldRetryResult - .error(new DocumentClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception))); + .error(new CosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception))); } if (this.request != null) { @@ -180,7 +179,7 @@ public Single shouldRetry(Exception exception) { logger.error("Received unexpected invalid collection exception, request should be non-null.", exception); return Single.just(ShouldRetryResult - .error(new DocumentClientException(HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, exception))); + .error(new CosmosClientException(HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, exception))); } forceRefreshAddressCache = false; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpClientUtils.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java similarity index 82% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpClientUtils.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java index 29e329d17cbd8..b638839cb797e 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpClientUtils.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import rx.Single; @@ -48,7 +48,7 @@ public static Single parseResponseAsync(HttpClientRes } } - private static Single createDocumentClientException(HttpClientResponse responseMessage) { + private static Single createDocumentClientException(HttpClientResponse responseMessage) { Single readStream = ResponseUtils.toString(responseMessage.getContent()).toSingle(); return readStream.map(body -> { @@ -56,7 +56,7 @@ private static Single createDocumentClientException(Htt // TODO: we should set resource address in the Document Client Exception - return new DocumentClientException(responseMessage.getStatus().code(), error, + return new CosmosClientException(responseMessage.getStatus().code(), error, HttpUtils.asMap(responseMessage.getHeaders())); }); } diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpTransportClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java similarity index 95% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpTransportClient.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java index 5e7a354480c58..4667c0c7be9ba 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpTransportClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java @@ -21,32 +21,32 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.Integers; -import com.microsoft.azure.cosmosdb.internal.InternalServerErrorException; -import com.microsoft.azure.cosmosdb.internal.Lists; -import com.microsoft.azure.cosmosdb.internal.Longs; -import com.microsoft.azure.cosmosdb.internal.MutableVolatile; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.PathsHelper; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.RuntimeConstants; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.rx.internal.BadRequestException; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.HttpClientFactory; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionException; -import com.microsoft.azure.cosmosdb.rx.internal.NotFoundException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionIsMigratingException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionKeyRangeIsSplittingException; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Integers; +import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.Lists; +import com.azure.data.cosmos.internal.Longs; +import com.azure.data.cosmos.internal.MutableVolatile; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RuntimeConstants; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.HttpClientFactory; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.PartitionIsMigratingException; +import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.Utils; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; @@ -68,7 +68,7 @@ import java.util.Map; import java.util.UUID; -import static com.microsoft.azure.cosmosdb.internal.Utils.trimBeginningAndEndingSlashes; +import static com.azure.data.cosmos.internal.Utils.trimBeginningAndEndingSlashes; /* * The following code only support Document Write without any error handling support. */ @@ -201,8 +201,8 @@ public Single invokeStoreAsync( exception, null, physicalAddress.toString()); - serviceUnavailableException.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); - serviceUnavailableException.getResponseHeaders().put(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH, "1"); + serviceUnavailableException.responseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); + serviceUnavailableException.responseHeaders().put(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH, "1"); return Single.error(serviceUnavailableException); } }).doOnSuccess(httpClientResponse -> { @@ -683,9 +683,9 @@ private Single processHttpResponse(String resourceAddress, HttpCl RMResources.InvalidBackendResponse), null, physicalAddress); - exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, + exception.responseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); - exception.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); + exception.responseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); return Single.error(exception); } @@ -722,7 +722,7 @@ private Single createErrorResponseFromHttpResponse(String resourc responsePartitionKeyRangeId = Lists.firstOrDefault(partitionKeyRangeIdValues, null); } - DocumentClientException exception; + CosmosClientException exception; switch (statusCode.code()) { case HttpConstants.StatusCodes.UNAUTHORIZED: @@ -760,7 +760,7 @@ private Single createErrorResponseFromHttpResponse(String resourc RMResources.ExceptionMessage, RMResources.Gone), request.getUri()); - exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, + exception.responseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); break; @@ -856,7 +856,7 @@ private Single createErrorResponseFromHttpResponse(String resourc response.getHeaders(), request.getUri()); - exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, + exception.responseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); break; } @@ -941,7 +941,7 @@ private Single createErrorResponseFromHttpResponse(String resourc if (values == null || values.isEmpty()) { logger.warn("RequestRateTooLargeException being thrown without RetryAfter."); } else { - exception.getResponseHeaders().put(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS, values.get(0)); + exception.responseHeaders().put(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS, values.get(0)); } break; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/IAddressCache.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressCache.java similarity index 90% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/IAddressCache.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressCache.java index 3e53730b86bc0..98af574519688 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/IAddressCache.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressCache.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import rx.Single; public interface IAddressCache { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/IAddressResolver.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressResolver.java similarity index 90% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/IAddressResolver.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressResolver.java index d2c5dce2dc49e..aa375a33c1cda 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/IAddressResolver.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressResolver.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import rx.Single; public interface IAddressResolver { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/IStoreClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IStoreClient.java similarity index 88% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/IStoreClient.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IStoreClient.java index a9a1c1fffdae5..fcaa8f0d94b85 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/IStoreClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IStoreClient.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.rx.internal.IRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.IRetryPolicy; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import rx.Single; import rx.functions.Func1; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/LockedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java similarity index 87% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/LockedException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java index 1b996af941a3b..dd58608203a36 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/LockedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.util.Map; @@ -35,7 +35,7 @@ * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ -public class LockedException extends DocumentClientException { +public class LockedException extends CosmosClientException { private static final long serialVersionUID = 1L; public LockedException() { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/MethodNotAllowedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java similarity index 87% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/MethodNotAllowedException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java index 082789ba3eda6..7c74e1357378c 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/MethodNotAllowedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java @@ -21,19 +21,19 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; import java.util.Map; -public class MethodNotAllowedException extends DocumentClientException { +public class MethodNotAllowedException extends CosmosClientException { public MethodNotAllowedException() { this(RMResources.MethodNotAllowed); } diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionKeyRangeGoneException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java similarity index 81% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionKeyRangeGoneException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java index 3a8531316e036..b76ca82264d3d 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionKeyRangeGoneException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java @@ -21,18 +21,15 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; -import org.apache.commons.collections4.CollectionUtils; -import java.net.URL; -import java.util.HashMap; import java.util.Map; /** @@ -42,7 +39,7 @@ * No retries should be made in this case, as either split or merge might have happened and query/readfeed * must take appropriate actions. */ -public class PartitionKeyRangeGoneException extends DocumentClientException { +public class PartitionKeyRangeGoneException extends CosmosClientException { public PartitionKeyRangeGoneException() { this(RMResources.Gone); @@ -79,6 +76,6 @@ public PartitionKeyRangeGoneException(String message, Exception innerException, } private void setSubstatus() { - this.getResponseHeaders().put(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)); + this.responseHeaders().put(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)); } } diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PreconditionFailedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java similarity index 87% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PreconditionFailedException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java index 400609c86685e..e26450aa4eb89 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PreconditionFailedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.util.Map; @@ -35,7 +35,7 @@ * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ -public class PreconditionFailedException extends DocumentClientException { +public class PreconditionFailedException extends CosmosClientException { private static final long serialVersionUID = 1L; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/QueryRequestPerformanceActivity.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QueryRequestPerformanceActivity.java similarity index 95% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/QueryRequestPerformanceActivity.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QueryRequestPerformanceActivity.java index 1673bbc60d76d..06ac246bd0df4 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/QueryRequestPerformanceActivity.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QueryRequestPerformanceActivity.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; // TODO troubleshooting info // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/258624 diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/QuorumReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/QuorumReader.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java index 6028328a6875d..5654cde3382e7 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/QuorumReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java @@ -21,20 +21,20 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - - -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.InternalServerErrorException; -import com.microsoft.azure.cosmosdb.internal.JavaStreamUtils; -import com.microsoft.azure.cosmosdb.internal.MutableVolatile; -import com.microsoft.azure.cosmosdb.internal.Quadruple; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +package com.azure.data.cosmos.directconnectivity; + + +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.JavaStreamUtils; +import com.azure.data.cosmos.internal.MutableVolatile; +import com.azure.data.cosmos.internal.Quadruple; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,11 +48,11 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; -import static com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import static com.azure.data.cosmos.internal.Utils.ValueHolder; // //================================================================================================================= -// Strong read logic: +// STRONG read logic: //================================================================================================================= // // ------------------- PerformPrimaryRead------------------------------------------------------------- @@ -68,7 +68,7 @@ // PrimaryReadBarrier------------------------------------------------------------- // //================================================================================================================= -// BoundedStaleness quorum read logic: +// BOUNDED_STALENESS quorum read logic: //================================================================================================================= // // ------------------- PerformPrimaryRead------------------------------------------------------------- @@ -160,7 +160,7 @@ public Single readStrongAsync( case QuorumMet: try { return Observable.just(secondaryQuorumReadResult.getResponse()); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { return Observable.error(e); } @@ -228,7 +228,7 @@ public Single readStrongAsync( logger.debug("QuorumNotSelected: ReadPrimary successful"); try { return Observable.just(response.getResponse()); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { return Observable.error(e); } } else if (response.shouldRetryOnSecondary) { @@ -336,8 +336,8 @@ private Single readLsn = new ValueHolder(-1); ValueHolder globalCommittedLSN = new ValueHolder(-1); @@ -381,7 +381,7 @@ private Single readPrimaryAsync( if (storeResult.currentReplicaSetSize <= 0 || storeResult.lsn < 0 || storeResult.quorumAckedLSN < 0) { String message = String.format( - "Invalid value received from response header. CurrentReplicaSetSize %d, StoreLSN %d, QuorumAckedLSN %d", + "INVALID value received from response header. CurrentReplicaSetSize %d, StoreLSN %d, QuorumAckedLSN %d", storeResult.currentReplicaSetSize, storeResult.lsn, storeResult.quorumAckedLSN); // might not be returned if primary is still building the secondary replicas (during churn) @@ -738,7 +738,7 @@ protected ReadResult(RequestChargeTracker requestChargeTracker, StoreResult resp this.response = response; } - public StoreResponse getResponse() throws DocumentClientException { + public StoreResponse getResponse() throws CosmosClientException { if (!this.isValidResult()) { logger.error("getResponse called for invalid result"); throw new InternalServerErrorException(RMResources.InternalServerError); @@ -775,7 +775,7 @@ public ReadQuorumResult( public final StoreResult selectedResponse; /** - * All store responses from Quorum Read. + * ALL store responses from Quorum READ. */ public final List storeResponses; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReadMode.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReadMode.java similarity index 94% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReadMode.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReadMode.java index ebefc977a38b4..dcd2fa6ea4287 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReadMode.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReadMode.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; public enum ReadMode { Primary, // Test hook diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicatedResourceClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java similarity index 90% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicatedResourceClient.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java index b8d116ef74085..6ddc736bcc0f7 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicatedResourceClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java @@ -21,25 +21,25 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import java.time.Duration; -import com.microsoft.azure.cosmosdb.ClientSideRequestStatistics; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.ReplicatedResourceClientUtils; +import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.ReplicatedResourceClientUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.Quadruple; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.internal.BackoffRetryUtility; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.Quadruple; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.BackoffRetryUtility; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import rx.Single; import rx.functions.Func1; @@ -76,7 +76,7 @@ public ReplicatedResourceClient( this.configs = configs; this.protocol = configs.getProtocol(); this.addressSelector = addressSelector; - if (protocol != Protocol.Https && protocol != Protocol.Tcp) { + if (protocol != Protocol.HTTPS && protocol != Protocol.TCP) { throw new IllegalArgumentException("protocol"); } @@ -171,7 +171,7 @@ public Single invokeAsync(RxDocumentServiceRequest request, }; } - int retryTimeout = this.serviceConfigReader.getDefaultConsistencyLevel() == ConsistencyLevel.Strong ? + int retryTimeout = this.serviceConfigReader.getDefaultConsistencyLevel() == ConsistencyLevel.STRONG ? ReplicatedResourceClient.STRONG_GONE_AND_RETRY_WITH_RETRY_TIMEOUT_SECONDS : ReplicatedResourceClient.GONE_AND_RETRY_WITH_TIMEOUT_IN_SECONDS; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestEntityTooLargeException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java similarity index 87% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestEntityTooLargeException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java index 1c8a33835e5e6..0d78f4e368375 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestEntityTooLargeException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.util.Map; @@ -35,7 +35,7 @@ * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ -public class RequestEntityTooLargeException extends DocumentClientException { +public class RequestEntityTooLargeException extends CosmosClientException { private static final long serialVersionUID = 1L; public RequestEntityTooLargeException() { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestHelper.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java similarity index 80% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestHelper.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java index 5eb93d0acd8ab..095073d14acea 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestHelper.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java @@ -21,20 +21,20 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.BadRequestException; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; import org.apache.commons.lang3.EnumUtils; public class RequestHelper { public static ConsistencyLevel GetConsistencyLevelToUse(GatewayServiceConfigurationReader serviceConfigReader, - RxDocumentServiceRequest request) throws DocumentClientException { + RxDocumentServiceRequest request) throws CosmosClientException { ConsistencyLevel consistencyLevelToUse = serviceConfigReader.getDefaultConsistencyLevel(); String requestConsistencyLevelHeaderValue = request.getHeaders().get(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL); diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestRateTooLargeException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java similarity index 87% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestRateTooLargeException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java index 1d5c315bade16..d769b45ce9801 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RequestRateTooLargeException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java @@ -21,20 +21,19 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; import java.util.Map; -public class RequestRateTooLargeException extends DocumentClientException { +public class RequestRateTooLargeException extends CosmosClientException { public RequestRateTooLargeException() { this(RMResources.TooManyRequests, null); diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ResourceOperation.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResourceOperation.java similarity index 88% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ResourceOperation.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResourceOperation.java index e51367dea91dc..5bf87fb41b639 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ResourceOperation.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResourceOperation.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; public class ResourceOperation { public final OperationType operationType; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ResponseUtils.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResponseUtils.java similarity index 92% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ResponseUtils.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResponseUtils.java index c37c7bef907a4..e2a30a0dbec1c 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ResponseUtils.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResponseUtils.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.netty.protocol.http.client.HttpClientResponse; @@ -93,7 +93,7 @@ public static Single toStoreResponse(HttpClientResponse } private static void validateOrThrow(RxDocumentServiceRequest request, HttpResponseStatus status, HttpResponseHeaders headers, String body, - InputStream inputStream) throws DocumentClientException { + InputStream inputStream) throws CosmosClientException { int statusCode = status.code(); @@ -118,7 +118,7 @@ private static void validateOrThrow(RxDocumentServiceRequest request, HttpRespon String.format("%s, StatusCode: %s", error.getMessage(), statusCodeString), error.getPartitionedQueryExecutionInfo()); - throw new DocumentClientException(statusCode, error, HttpUtils.asMap(headers)); + throw new CosmosClientException(statusCode, error, HttpUtils.asMap(headers)); } } } diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RetryWithException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java similarity index 85% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RetryWithException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java index df32963da686d..1d116fab21aa9 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RetryWithException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java @@ -21,20 +21,18 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; import java.util.Map; -public class RetryWithException extends DocumentClientException { +public class RetryWithException extends CosmosClientException { public RetryWithException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { super(HttpConstants.StatusCodes.RETRY_WITH, error, responseHeaders); diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RntbdTransportClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RntbdTransportClient.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java index 91762f2058806..b00e20b28e1df 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RntbdTransportClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java @@ -22,15 +22,15 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.collect.ImmutableMap; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdClientChannelInitializer; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdRequestArgs; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdRequestManager; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdClientChannelInitializer; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestArgs; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestManager; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; @@ -55,7 +55,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.HttpHeaders; +import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; final public class RntbdTransportClient extends TransportClient implements AutoCloseable { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServerProperties.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerProperties.java similarity index 95% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServerProperties.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerProperties.java index d8a84ba78d614..71379b780c5f6 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServerProperties.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerProperties.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; final public class ServerProperties { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServerStoreModel.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java similarity index 81% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServerStoreModel.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java index c21ad28d13e01..28761ba122af9 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServerStoreModel.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java @@ -21,17 +21,17 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.BadRequestException; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; -import com.microsoft.azure.cosmosdb.rx.internal.RxStoreModel; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.RxStoreModel; +import com.azure.data.cosmos.internal.Strings; import org.apache.commons.lang3.EnumUtils; import rx.Observable; import rx.Single; @@ -63,7 +63,7 @@ public Observable processMessage(RxDocumentServiceReq } if (ReplicatedResourceClient.isMasterResource(request.getResourceType())) { - request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Strong.toString()); + request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.STRONG.toString()); } Single response = this.storeClient.processMessageAsync(request); diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServiceConfig.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceConfig.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServiceConfig.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceConfig.java index 25ae57544ce59..efd483ad8f8c4 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServiceConfig.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceConfig.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; class ServiceConfig { final static ServiceConfig instance = new ServiceConfig(); diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServiceUnavailableException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java similarity index 87% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServiceUnavailableException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java index e028912a90680..d6253cd27e46a 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ServiceUnavailableException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java @@ -21,19 +21,19 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; import java.util.Map; -public class ServiceUnavailableException extends DocumentClientException { +public class ServiceUnavailableException extends CosmosClientException { public ServiceUnavailableException() { this(RMResources.ServiceUnavailable); } diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java similarity index 83% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreClient.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java index f51634e9a31c3..d2d3b0f26f073 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java @@ -21,27 +21,27 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.ISessionToken; -import com.microsoft.azure.cosmosdb.internal.InternalServerErrorException; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.SessionContainer; -import com.microsoft.azure.cosmosdb.internal.SessionTokenHelper; -import com.microsoft.azure.cosmosdb.rx.internal.BackoffRetryUtility; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.Exceptions; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.IRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ISessionToken; +import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.SessionContainer; +import com.azure.data.cosmos.internal.SessionTokenHelper; +import com.azure.data.cosmos.internal.BackoffRetryUtility; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.Exceptions; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.IRetryPolicy; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.Utils; import org.apache.commons.lang3.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,7 +54,7 @@ /** * Instantiated to issue direct connectivity requests to the backend on: - * - Gateway (for gateway mode clients) + * - GATEWAY (for gateway mode clients) * - Client (for direct mode clients) * StoreClient uses the ReplicatedResourceClient to make requests to the backend. */ @@ -102,13 +102,13 @@ public Single processMessageAsync(RxDocumentServiceRe storeResponse = storeResponse.doOnError(e -> { try { - DocumentClientException exception = Utils.as(e, DocumentClientException.class); + CosmosClientException exception = Utils.as(e, CosmosClientException.class); if (exception == null) { return; } - exception.setClientSideRequestStatistics(request.requestContext.clientSideRequestStatistics); + exception.clientSideRequestStatistics(request.requestContext.clientSideRequestStatistics); handleUnsuccessfulStoreResponse(request, exception); } catch (Throwable throwable) { @@ -127,13 +127,13 @@ public Single processMessageAsync(RxDocumentServiceRe }); } - private void handleUnsuccessfulStoreResponse(RxDocumentServiceRequest request, DocumentClientException exception) { - this.updateResponseHeader(request, exception.getResponseHeaders()); + private void handleUnsuccessfulStoreResponse(RxDocumentServiceRequest request, CosmosClientException exception) { + this.updateResponseHeader(request, exception.responseHeaders()); if ((!ReplicatedResourceClient.isMasterResource(request.getResourceType())) && (Exceptions.isStatusCode(exception, HttpConstants.StatusCodes.PRECONDITION_FAILED) || Exceptions.isStatusCode(exception, HttpConstants.StatusCodes.CONFLICT) || (Exceptions.isStatusCode(exception, HttpConstants.StatusCodes.NOTFOUND) && !Exceptions.isSubStatusCode(exception, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)))) { - this.captureSessionToken(request, exception.getResponseHeaders()); + this.captureSessionToken(request, exception.responseHeaders()); } } @@ -174,9 +174,9 @@ private void updateResponseHeader(RxDocumentServiceRequest request, Map> readMultipleReplicaAsync( * @param replicaCountToRead number of replicas to read from * @param requiresValidLsn flag to indicate whether a valid lsn is required to consider a response as valid * @param useSessionToken flag to indicate whether to use session token - * @param readMode Read mode + * @param readMode READ mode * @param checkMinLSN set minimum required session lsn * @param forceReadAll reads from all available replicas to gather result from readsToRead number of replicas * @return ReadReplicaResult which indicates the LSN and whether Quorum was Met / Not Met etc @@ -310,7 +310,7 @@ private ReadReplicaResult createReadReplicaResult(List responseResu int replicaCountToRead, int resolvedAddressCount, boolean hasGoneException, - RxDocumentServiceRequest entity) throws DocumentClientException { + RxDocumentServiceRequest entity) throws CosmosClientException { if (responseResult.size() < replicaCountToRead) { logger.debug("Could not get quorum number of responses. " + "ValidResponsesReceived: {} ResponsesExpected: {}, ResolvedAddressCount: {}, ResponsesString: {}", @@ -341,7 +341,7 @@ private ReadReplicaResult createReadReplicaResult(List responseResu * @param replicaCountToRead number of replicas to read from * @param requiresValidLsn flag to indicate whether a valid lsn is required to consider a response as valid * @param useSessionToken flag to indicate whether to use session token - * @param readMode Read mode + * @param readMode READ mode * @param checkMinLSN set minimum required session lsn * @param forceReadAll will read from all available replicas to put together result from readsToRead number of replicas * @return ReadReplicaResult which indicates the LSN and whether Quorum was Met / Not Met etc @@ -544,21 +544,21 @@ private Single readPrimaryInternalAsync( true, storeResponse != null ? storeResponseObsAndUri.getRight() : null); return Single.just(storeResult); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { return Single.error(e); } } ); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { // RxJava1 doesn't allow throwing checked exception from Observable:map return Single.error(e); } } ).onErrorResumeNext(t -> { - logger.debug("Exception {} is thrown while doing Read Primary", t); + logger.debug("Exception {} is thrown while doing READ Primary", t); Exception storeTaskException = Utils.as(t, Exception.class); if (storeTaskException == null) { @@ -572,7 +572,7 @@ private Single readPrimaryInternalAsync( true, null); return Single.just(storeResult); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { // RxJava1 doesn't allow throwing checked exception from Observable operators return Single.error(e); } @@ -592,7 +592,7 @@ private Single readPrimaryInternalAsync( private Pair, URI> readFromStoreAsync( URI physicalAddress, - RxDocumentServiceRequest request) throws DocumentClientException { + RxDocumentServiceRequest request) throws CosmosClientException { if (request.requestContext.timeoutHelper.isElapsed()) { throw new GoneException(); @@ -671,7 +671,7 @@ StoreResult createStoreResult(StoreResponse storeResponse, Exception responseException, boolean requiresValidLsn, boolean useLocalLSNBasedHeaders, - URI storePhysicalAddress) throws DocumentClientException { + URI storePhysicalAddress) throws CosmosClientException { if (responseException == null) { String headerValue = null; @@ -722,7 +722,7 @@ StoreResult createStoreResult(StoreResponse storeResponse, } ISessionToken sessionToken = null; - // Session token response header is introduced from version HttpConstants.Versions.v2018_06_18 onwards. + // SESSION token response header is introduced from version HttpConstants.Versions.v2018_06_18 onwards. // Previously it was only a request header if ((headerValue = storeResponse.getHeaderValue(HttpConstants.HttpHeaders.SESSION_TOKEN)) != null) { sessionToken = SessionTokenHelper.parse(headerValue); @@ -744,78 +744,78 @@ StoreResult createStoreResult(StoreResponse storeResponse, /* itemLSN: */ itemLSN, /* sessionToken: */ sessionToken); } else { - DocumentClientException documentClientException = Utils.as(responseException, DocumentClientException.class); - if (documentClientException != null) { - StoreReader.verifyCanContinueOnException(documentClientException); + CosmosClientException cosmosClientException = Utils.as(responseException, CosmosClientException.class); + if (cosmosClientException != null) { + StoreReader.verifyCanContinueOnException(cosmosClientException); long quorumAckedLSN = -1; int currentReplicaSetSize = -1; int currentWriteQuorum = -1; long globalCommittedLSN = -1; int numberOfReadRegions = -1; - String headerValue = documentClientException.getResponseHeaders().get(useLocalLSNBasedHeaders ? WFConstants.BackendHeaders.QUORUM_ACKED_LOCAL_LSN : WFConstants.BackendHeaders.QUORUM_ACKED_LSN); + String headerValue = cosmosClientException.responseHeaders().get(useLocalLSNBasedHeaders ? WFConstants.BackendHeaders.QUORUM_ACKED_LOCAL_LSN : WFConstants.BackendHeaders.QUORUM_ACKED_LSN); if (!Strings.isNullOrEmpty(headerValue)) { quorumAckedLSN = Long.parseLong(headerValue); } - headerValue = documentClientException.getResponseHeaders().get(WFConstants.BackendHeaders.CURRENT_REPLICA_SET_SIZE); + headerValue = cosmosClientException.responseHeaders().get(WFConstants.BackendHeaders.CURRENT_REPLICA_SET_SIZE); if (!Strings.isNullOrEmpty(headerValue)) { currentReplicaSetSize = Integer.parseInt(headerValue); } - headerValue = documentClientException.getResponseHeaders().get(WFConstants.BackendHeaders.CURRENT_WRITE_QUORUM); + headerValue = cosmosClientException.responseHeaders().get(WFConstants.BackendHeaders.CURRENT_WRITE_QUORUM); if (!Strings.isNullOrEmpty(headerValue)) { currentReplicaSetSize = Integer.parseInt(headerValue); } double requestCharge = 0; - headerValue = documentClientException.getResponseHeaders().get(HttpConstants.HttpHeaders.REQUEST_CHARGE); + headerValue = cosmosClientException.responseHeaders().get(HttpConstants.HttpHeaders.REQUEST_CHARGE); if (!Strings.isNullOrEmpty(headerValue)) { requestCharge = Double.parseDouble(headerValue); } - headerValue = documentClientException.getResponseHeaders().get(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS); + headerValue = cosmosClientException.responseHeaders().get(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS); if (!Strings.isNullOrEmpty(headerValue)) { numberOfReadRegions = Integer.parseInt(headerValue); } - headerValue = documentClientException.getResponseHeaders().get(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN); + headerValue = cosmosClientException.responseHeaders().get(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN); if (!Strings.isNullOrEmpty(headerValue)) { globalCommittedLSN = Integer.parseInt(headerValue); } long lsn = -1; if (useLocalLSNBasedHeaders) { - headerValue = documentClientException.getResponseHeaders().get(WFConstants.BackendHeaders.LOCAL_LSN); + headerValue = cosmosClientException.responseHeaders().get(WFConstants.BackendHeaders.LOCAL_LSN); if (!Strings.isNullOrEmpty(headerValue)) { lsn = Long.parseLong(headerValue); } } else { - lsn = BridgeInternal.getLSN(documentClientException); + lsn = BridgeInternal.getLSN(cosmosClientException); } ISessionToken sessionToken = null; - // Session token response header is introduced from version HttpConstants.Versions.v2018_06_18 onwards. + // SESSION token response header is introduced from version HttpConstants.Versions.v2018_06_18 onwards. // Previously it was only a request header - headerValue = documentClientException.getResponseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); + headerValue = cosmosClientException.responseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(headerValue)) { sessionToken = SessionTokenHelper.parse(headerValue); } return new StoreResult( /* storeResponse: */ (StoreResponse) null, - /* exception: */ documentClientException, - /* partitionKeyRangeId: */BridgeInternal.getPartitionKeyRangeId(documentClientException), + /* exception: */ cosmosClientException, + /* partitionKeyRangeId: */BridgeInternal.getPartitionKeyRangeId(cosmosClientException), /* lsn: */ lsn, /* quorumAckedLsn: */ quorumAckedLSN, /* requestCharge: */ requestCharge, /* currentReplicaSetSize: */ currentReplicaSetSize, /* currentWriteQuorum: */ currentWriteQuorum, /* isValid: */!requiresValidLsn - || ((documentClientException.getStatusCode() != HttpConstants.StatusCodes.GONE || isSubStatusCode(documentClientException, HttpConstants.SubStatusCodes.NAME_CACHE_IS_STALE)) + || ((cosmosClientException.statusCode() != HttpConstants.StatusCodes.GONE || isSubStatusCode(cosmosClientException, HttpConstants.SubStatusCodes.NAME_CACHE_IS_STALE)) && lsn >= 0), // TODO: verify where exception.RequestURI is supposed to be set in .Net - /* storePhysicalAddress: */ storePhysicalAddress == null ? BridgeInternal.getRequestUri(documentClientException) : storePhysicalAddress, + /* storePhysicalAddress: */ storePhysicalAddress == null ? BridgeInternal.getRequestUri(cosmosClientException) : storePhysicalAddress, /* globalCommittedLSN: */ globalCommittedLSN, /* numberOfReadRegions: */ numberOfReadRegions, /* itemLSN: */ -1, @@ -858,7 +858,7 @@ private static int generateNextRandom(int maxValue) { return ThreadLocalRandom.current().nextInt(maxValue); } - static void verifyCanContinueOnException(DocumentClientException ex) throws DocumentClientException { + static void verifyCanContinueOnException(CosmosClientException ex) throws CosmosClientException { if (ex instanceof PartitionKeyRangeGoneException) { throw ex; } @@ -871,7 +871,7 @@ static void verifyCanContinueOnException(DocumentClientException ex) throws Docu throw ex; } - String value = ex.getResponseHeaders().get(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE); + String value = ex.responseHeaders().get(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE); if (Strings.isNullOrWhiteSpace(value)) { return; } diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TransportClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportClient.java similarity index 92% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TransportClient.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportClient.java index b25cbe351722d..6123d6d7bf196 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TransportClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportClient.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import rx.Single; import java.net.URI; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TransportException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportException.java similarity index 92% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TransportException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportException.java index c1e3a499a0188..abc5f848b5283 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TransportException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportException.java @@ -22,11 +22,11 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.Error; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.Error; import io.netty.handler.codec.http.HttpResponseStatus; import java.util.Map; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/UnauthorizedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java similarity index 87% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/UnauthorizedException.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java index 5caf0c8b59169..7607d3a467d3c 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/UnauthorizedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java @@ -21,19 +21,19 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; import java.util.Map; -public class UnauthorizedException extends DocumentClientException { +public class UnauthorizedException extends CosmosClientException { public UnauthorizedException() { this(RMResources.Unauthorized); diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdClientChannelInitializer.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelInitializer.java similarity index 92% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdClientChannelInitializer.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelInitializer.java index 693b570b279e1..01c1df430c9da 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdClientChannelInitializer.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelInitializer.java @@ -22,10 +22,10 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.RntbdTransportClient.Options; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.directconnectivity.RntbdTransportClient.Options; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.nio.NioSocketChannel; @@ -88,7 +88,7 @@ protected void initChannel(NioSocketChannel channel) { final SSLEngine sslEngine = this.sslContext.newEngine(channel.alloc()); pipeline.addFirst( - // TODO: DANOBLE: Utilize Read/WriteTimeoutHandler for receive/send hang detection + // TODO: DANOBLE: Utilize READ/WriteTimeoutHandler for receive/send hang detection // Links: // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/331552 // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/331593 diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdConstants.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdConstants.java similarity index 99% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdConstants.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdConstants.java index 500c41313bc6c..ecec351e39d14 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdConstants.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdConstants.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContext.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContext.java similarity index 94% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContext.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContext.java index d3185b26de9b3..3c51ce1bddd8f 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContext.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContext.java @@ -22,14 +22,14 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.ServerProperties; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.TransportException; +import com.azure.data.cosmos.directconnectivity.ServerProperties; +import com.azure.data.cosmos.directconnectivity.TransportException; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.CorruptedFrameException; import io.netty.handler.codec.http.HttpResponseStatus; @@ -38,8 +38,8 @@ import java.util.HashMap; import java.util.UUID; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.CurrentProtocolVersion; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdContextHeader; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.CurrentProtocolVersion; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdContextHeader; final public class RntbdContext { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextDecoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextDecoder.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextDecoder.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextDecoder.java index c55693b1321af..52c5c48e6f5a4 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextDecoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextDecoder.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextNegotiator.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextNegotiator.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextNegotiator.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextNegotiator.java index bc4cb6c369a77..f1e4ae6fc33cf 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextNegotiator.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextNegotiator.java @@ -22,9 +22,9 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.UserAgentContainer; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextRequest.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequest.java similarity index 88% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextRequest.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequest.java index 777906dce2ed6..160a4c7f71ca9 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextRequest.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequest.java @@ -22,23 +22,23 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectWriter; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.UserAgentContainer; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.CorruptedFrameException; import java.nio.charset.StandardCharsets; import java.util.UUID; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.Versions; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.CurrentProtocolVersion; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdContextRequestHeader; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdResourceType; +import static com.azure.data.cosmos.internal.HttpConstants.Versions; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.CurrentProtocolVersion; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdContextRequestHeader; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResourceType; final public class RntbdContextRequest { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestDecoder.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestDecoder.java index 85039affbe648..4551f126e1880 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestDecoder.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestEncoder.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestEncoder.java index 9d3063b4e311b..9920e172a64dd 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestEncoder.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdFramer.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdFramer.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdFramer.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdFramer.java index 4aa36213a7f42..bdaad39d0f65f 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdFramer.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdFramer.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.CorruptedFrameException; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdObjectMapper.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdObjectMapper.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdObjectMapper.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdObjectMapper.java index 71b8d74372df5..6c6b8c280083b 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdObjectMapper.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdObjectMapper.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequest.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequest.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequest.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequest.java index 470bd3d43e6cf..5925eb6081ca9 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequest.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequest.java @@ -22,9 +22,9 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import io.netty.buffer.ByteBuf; import java.util.Objects; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestArgs.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestArgs.java similarity index 95% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestArgs.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestArgs.java index 76e152ef807b6..b59fc12d74099 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestArgs.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestArgs.java @@ -22,10 +22,10 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.google.common.base.Stopwatch; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import io.netty.channel.ChannelHandlerContext; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestDecoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestDecoder.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestDecoder.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestDecoder.java index fc5fadf63bbf4..150f619fc07fe 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestDecoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestDecoder.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestEncoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestEncoder.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestEncoder.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestEncoder.java index 34efeebaa6bb6..68a6802896b3f 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestEncoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestEncoder.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestFrame.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFrame.java similarity index 95% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestFrame.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFrame.java index 726f03cacf668..6ba43e32ad178 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestFrame.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFrame.java @@ -22,17 +22,17 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; import io.netty.buffer.ByteBuf; import java.util.Locale; import java.util.UUID; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdResourceType; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResourceType; final class RntbdRequestFrame { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestFramer.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFramer.java similarity index 95% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestFramer.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFramer.java index 81201cad3a6e8..472e0fb2b4a2d 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestFramer.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFramer.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestHeaders.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestHeaders.java similarity index 94% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestHeaders.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestHeaders.java index 9d74a7009df9d..6a86d7c348b7d 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdRequestHeaders.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestHeaders.java @@ -22,22 +22,22 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.fasterxml.jackson.annotation.JsonFilter; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.IndexingDirective; -import com.microsoft.azure.cosmosdb.internal.ContentSerializationFormat; -import com.microsoft.azure.cosmosdb.internal.EnumerationDirection; -import com.microsoft.azure.cosmosdb.internal.FanoutOperationState; -import com.microsoft.azure.cosmosdb.internal.MigrateCollectionDirective; -import com.microsoft.azure.cosmosdb.internal.Paths; -import com.microsoft.azure.cosmosdb.internal.ReadFeedKeyType; -import com.microsoft.azure.cosmosdb.internal.RemoteStorageType; -import com.microsoft.azure.cosmosdb.internal.ResourceId; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.IndexingDirective; +import com.azure.data.cosmos.internal.ContentSerializationFormat; +import com.azure.data.cosmos.internal.EnumerationDirection; +import com.azure.data.cosmos.internal.FanoutOperationState; +import com.azure.data.cosmos.internal.MigrateCollectionDirective; +import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.ReadFeedKeyType; +import com.azure.data.cosmos.internal.RemoteStorageType; +import com.azure.data.cosmos.internal.ResourceId; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import io.netty.buffer.ByteBuf; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.StringUtils; @@ -50,18 +50,18 @@ import java.util.Objects; import java.util.function.Supplier; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.HttpHeaders; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.WFConstants.BackendHeaders; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdConsistencyLevel; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdContentSerializationFormat; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdEnumerationDirection; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdFanoutOperationState; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdIndexingDirective; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdMigrateCollectionDirective; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdReadFeedKeyType; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdRemoteStorageType; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdRequestHeader; +import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; +import static com.azure.data.cosmos.directconnectivity.WFConstants.BackendHeaders; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdConsistencyLevel; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdContentSerializationFormat; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdEnumerationDirection; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdFanoutOperationState; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdIndexingDirective; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdMigrateCollectionDirective; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdReadFeedKeyType; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdRemoteStorageType; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdRequestHeader; @JsonFilter("RntbdToken") final class RntbdRequestHeaders extends RntbdTokenStream { @@ -174,7 +174,7 @@ final class RntbdRequestHeaders extends RntbdTokenStream { this.fillTokenFromHeader(headers, this::getTransportRequestID, HttpHeaders.TRANSPORT_REQUEST_ID); // Will be null in case of direct, which is fine - BE will use the value slice the connection context this. - // When this is used in Gateway, the header value will be populated with the proxied HTTP request's header, + // When this is used in GATEWAY, the header value will be populated with the proxied HTTP request's header, // and BE will respect the per-request value. this.fillTokenFromHeader(headers, this::getClientVersion, HttpHeaders.VERSION); @@ -648,19 +648,19 @@ private void addConsistencyLevelHeader(Map headers) { } switch (level) { - case Strong: + case STRONG: this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Strong.id()); break; - case BoundedStaleness: + case BOUNDED_STALENESS: this.getConsistencyLevel().setValue(RntbdConsistencyLevel.BoundedStaleness.id()); break; - case Session: + case SESSION: this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Session.id()); break; - case Eventual: + case EVENTUAL: this.getConsistencyLevel().setValue(RntbdConsistencyLevel.Eventual.id()); break; - case ConsistentPrefix: + case CONSISTENT_PREFIX: this.getConsistencyLevel().setValue(RntbdConsistencyLevel.ConsistentPrefix.id()); break; default: @@ -842,13 +842,13 @@ private void addIndexingDirectiveHeader(Map headers) { } switch (directive) { - case Default: + case DEFAULT: this.getIndexingDirective().setValue(RntbdIndexingDirective.Default.id()); break; - case Exclude: + case EXCLUDE: this.getIndexingDirective().setValue(RntbdIndexingDirective.Exclude.id()); break; - case Include: + case INCLUDE: this.getIndexingDirective().setValue(RntbdIndexingDirective.Include.id()); break; default: @@ -1278,7 +1278,7 @@ private void fillTokenFromHeader(Map headers, Supplier - * All but inbound request management events are ignored. + * ALL but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event @@ -602,16 +602,16 @@ private void messageReceived(ChannelHandlerContext context, RntbdResponse respon } else { - // Map response to a DocumentClientException + // Map response to a CosmosClientException - final DocumentClientException cause; + final CosmosClientException cause; // ..Fetch required header values final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); - // ..Create Error instance + // ..CREATE Error instance final ObjectMapper mapper = new ObjectMapper(); final Error error; @@ -639,7 +639,7 @@ private void messageReceived(ChannelHandlerContext context, RntbdResponse respon this.getRntbdContext().orElseThrow(IllegalStateException::new), activityId ); - // ..Create DocumentClientException based on status and sub-status codes + // ..CREATE CosmosClientException based on status and sub-status codes switch (status.code()) { @@ -723,12 +723,12 @@ private void messageReceived(ChannelHandlerContext context, RntbdResponse respon break; default: - cause = new DocumentClientException(status.code(), error, responseHeaders); + cause = new CosmosClientException(status.code(), error, responseHeaders); break; } logger.trace("{}[activityId: {}, statusCode: {}, subStatusCode: {}] {}", - context.channel(), cause.getActivityId(), cause.getStatusCode(), cause.getSubStatusCode(), + context.channel(), cause.message(), cause.statusCode(), cause.subStatusCode(), cause.getMessage() ); diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponse.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponse.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponse.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponse.java index cc0f2c21d1c59..af46f086154a8 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponse.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponse.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @@ -33,7 +33,7 @@ import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreResponse; +import com.azure.data.cosmos.directconnectivity.StoreResponse; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufUtil; @@ -52,7 +52,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; import static java.lang.Math.min; @JsonPropertyOrder({ "frame", "headers", "content" }) diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponseDecoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseDecoder.java similarity index 97% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponseDecoder.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseDecoder.java index 2f34fe65ca695..6399a985ff258 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponseDecoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseDecoder.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponseHeaders.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseHeaders.java similarity index 98% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponseHeaders.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseHeaders.java index b1a207179b8ad..a719e836dfbf0 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponseHeaders.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseHeaders.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.annotation.JsonProperty; @@ -41,10 +41,10 @@ import java.util.function.BiConsumer; import java.util.function.Function; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.HttpHeaders; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.WFConstants.BackendHeaders; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdIndexingDirective; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; +import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; +import static com.azure.data.cosmos.directconnectivity.WFConstants.BackendHeaders; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdIndexingDirective; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; @JsonFilter("RntbdToken") class RntbdResponseHeaders extends RntbdTokenStream { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponseStatus.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseStatus.java similarity index 98% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponseStatus.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseStatus.java index c314d25190040..57ebdc44b6e32 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdResponseStatus.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseStatus.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdToken.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdToken.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdToken.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdToken.java index 0b21e011ee70b..85169cff66dcf 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdToken.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdToken.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -37,7 +37,7 @@ import java.util.Objects; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdHeader; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdHeader; @JsonPropertyOrder({ "id", "name", "type", "present", "required", "value" }) class RntbdToken { @@ -150,7 +150,7 @@ void decode(ByteBuf in) { ((ByteBuf)this.value).release(); } - this.value = this.header.type().codec().readSlice(in).retain(); // No data transfer until the first call to RntbdToken.getValue + this.value = this.header.type().codec().readSlice(in).retain(); // No data transfer until the first call to RntbdToken.value } final void encode(ByteBuf out) { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdTokenStream.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenStream.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdTokenStream.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenStream.java index 887114a1cdd9f..61ef60106e689 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdTokenStream.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenStream.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -32,7 +32,7 @@ import java.util.Objects; import java.util.stream.Collector; -import static com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdConstants.RntbdHeader; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdHeader; abstract class RntbdTokenStream & RntbdHeader> { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdTokenType.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenType.java similarity index 99% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdTokenType.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenType.java index 776e77320acf4..cf0ff0a6bb65c 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdTokenType.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenType.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import com.google.common.base.Utf8; import io.netty.buffer.ByteBuf; @@ -34,7 +34,7 @@ enum RntbdTokenType { - // All values are encoded as little endian byte sequences except for Guid + // ALL values are encoded as little endian byte sequences except for Guid // Guid values are serialized in Microsoft GUID byte order // Reference: GUID structure and System.Guid type @@ -46,9 +46,9 @@ enum RntbdTokenType { LongLong((byte)0x05, RntbdLong.codec), // long => long Guid((byte)0x06, RntbdGuid.codec), // byte[16] => UUID - SmallString((byte)0x07, RntbdShortString.codec), // (byte, byte[0..255]) => String - String((byte)0x08, RntbdString.codec), // (short, byte[0..64KiB]) => String - ULongString((byte)0x09, RntbdLongString.codec), // (int, byte[0..2GiB-1]) => String + SmallString((byte)0x07, RntbdShortString.codec), // (byte, byte[0..255]) => STRING + String((byte)0x08, RntbdString.codec), // (short, byte[0..64KiB]) => STRING + ULongString((byte)0x09, RntbdLongString.codec), // (int, byte[0..2GiB-1]) => STRING SmallBytes((byte)0x0A, RntbdShortBytes.codec), // (byte, byte[0..255]) => byte[] Bytes((byte)0x0B, RntbdBytes.codec), // (short, byte[0..64KiB]) => byte[] diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdUUID.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdUUID.java similarity index 98% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdUUID.java rename to direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdUUID.java index 0e36ca9b25491..cab3162b3c21c 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/rntbd/RntbdUUID.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdUUID.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd; +package com.azure.data.cosmos.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/ContentSerializationFormat.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java similarity index 92% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/ContentSerializationFormat.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java index fb9a8fe974d36..12edb9f2d6df8 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/ContentSerializationFormat.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; public enum ContentSerializationFormat { /** @@ -31,7 +31,7 @@ public enum ContentSerializationFormat { JsonText, /** - * Custom binary for Cosmos DB that encodes a superset of JSON values. + * CUSTOM binary for Cosmos DB that encodes a superset of JSON values. */ CosmosBinary, } diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/EnumerationDirection.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/EnumerationDirection.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java index d4b6aed5351ff..4515312aadb21 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/EnumerationDirection.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; public enum EnumerationDirection { /** diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/FanoutOperationState.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/FanoutOperationState.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java index b8c3a4786e803..862ed362c944c 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/FanoutOperationState.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; public enum FanoutOperationState { /** diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/MigrateCollectionDirective.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/MigrateCollectionDirective.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java index 5d3f30231fa13..ffead99b1a898 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/MigrateCollectionDirective.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; public enum MigrateCollectionDirective { /** diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/ReadFeedKeyType.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/ReadFeedKeyType.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java index f84a40047e9af..7d4ae90623ec2 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/ReadFeedKeyType.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * Type of Start and End key for ReadFeedKey diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/RemoteStorageType.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java similarity index 96% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/RemoteStorageType.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java index e0f65239a64c4..b36fecad18f33 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/RemoteStorageType.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java @@ -22,7 +22,7 @@ * */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; public enum RemoteStorageType { /** diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/Int128.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java similarity index 98% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/Int128.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java index c74a4ff99a01a..07cd07b6d877c 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/Int128.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.math.BigInteger; diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MurmurHash3_128.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java similarity index 98% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MurmurHash3_128.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java index 06224c795a64a..c7214375ff803 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MurmurHash3_128.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; public class MurmurHash3_128 { diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MurmurHash3_32.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java similarity index 98% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MurmurHash3_32.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java index e92cb2e411870..b5c723f177afb 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/MurmurHash3_32.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; /* * The MurmurHash3 algorithm was created by Austin Appleby and placed in the public domain. diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternalHelper.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java similarity index 93% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternalHelper.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java index d0c81ddf8c194..a322e3bc213e5 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternalHelper.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; -import com.microsoft.azure.cosmosdb.CommonsBridgeInternal; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.PartitionKind; -import com.microsoft.azure.cosmosdb.internal.Bytes; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.CommonsBridgeInternal; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.PartitionKind; +import com.azure.data.cosmos.internal.Bytes; +import com.azure.data.cosmos.internal.RMResources; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -152,21 +152,21 @@ public static String getEffectivePartitionKeyString(PartitionKeyInternal partiti return MaximumExclusiveEffectivePartitionKey; } - if (partitionKeyInternal.components.size() < partitionKeyDefinition.getPaths().size()) { + if (partitionKeyInternal.components.size() < partitionKeyDefinition.paths().size()) { throw new IllegalArgumentException(RMResources.TooFewPartitionKeyComponents); } - if (partitionKeyInternal.components.size() > partitionKeyDefinition.getPaths().size() && strict) { + if (partitionKeyInternal.components.size() > partitionKeyDefinition.paths().size() && strict) { throw new IllegalArgumentException(RMResources.TooManyPartitionKeyComponents); } - PartitionKind kind = partitionKeyDefinition.getKind(); + PartitionKind kind = partitionKeyDefinition.kind(); if (kind == null) { - kind = PartitionKind.Hash; + kind = PartitionKind.HASH; } switch (kind) { - case Hash: + case HASH: if (CommonsBridgeInternal.isV2(partitionKeyDefinition)) { // V2 return getEffectivePartitionKeyForHashPartitioningV2(partitionKeyInternal); diff --git a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/UInt128.java b/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java similarity index 95% rename from direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/UInt128.java rename to direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java index 4241b78cd705c..f34a5ba77b712 100644 --- a/direct-impl/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/UInt128.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; class UInt128 { long low; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/PartitionKeyHashingTests.java b/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java similarity index 81% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/PartitionKeyHashingTests.java rename to direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java index 72b83febf4229..dfdfdf0452803 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/PartitionKeyHashingTests.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java @@ -1,4 +1,4 @@ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.Arrays; import java.util.HashMap; @@ -7,7 +7,7 @@ import org.testng.annotations.Test; import com.fasterxml.jackson.databind.node.NullNode; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternalHelper; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; @@ -36,8 +36,8 @@ public void effectivePartitionKeyHashV1() { for (Map.Entry entry : keyToEffectivePartitionKeyString.entrySet()) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); - partitionKeyDef.setKind(PartitionKind.Hash); - partitionKeyDef.setPaths(Arrays.asList(new String[]{"\\id"})); + partitionKeyDef.kind(PartitionKind.HASH); + partitionKeyDef.paths(Arrays.asList(new String[]{"\\id"})); String actualEffectiveKeyString = PartitionKeyInternalHelper.getEffectivePartitionKeyString(new PartitionKey(entry.getKey()).getInternalPartitionKey(),partitionKeyDef, true); assertThat(entry.getValue()).isEqualTo(actualEffectiveKeyString); } @@ -66,9 +66,9 @@ public void effectivePartitionKeyHashV2() { for (Map.Entry entry : keyToEffectivePartitionKeyString.entrySet()) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); - partitionKeyDef.setKind(PartitionKind.Hash); - partitionKeyDef.setVersion(PartitionKeyDefinitionVersion.V2); - partitionKeyDef.setPaths(Arrays.asList(new String[]{"\\id"})); + partitionKeyDef.kind(PartitionKind.HASH); + partitionKeyDef.version(PartitionKeyDefinitionVersion.V2); + partitionKeyDef.paths(Arrays.asList(new String[]{"\\id"})); String actualEffectiveKeyString = PartitionKeyInternalHelper.getEffectivePartitionKeyString(new PartitionKey(entry.getKey()).getInternalPartitionKey(),partitionKeyDef, true); assertThat(entry.getValue()).isEqualTo(actualEffectiveKeyString); } @@ -76,19 +76,19 @@ public void effectivePartitionKeyHashV2() { @Test(groups = "unit") public void hashV2PartitionKeyDeserialization() { - String partitionKeyDefinitionStr = "{\"paths\":[\"/pk\"],\"kind\":\"Hash\",\"version\":2}"; + String partitionKeyDefinitionStr = "{\"paths\":[\"/pk\"],\"kind\":\"HASH\",\"version\":2}"; PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(partitionKeyDefinitionStr); - assertThat(partitionKeyDef.getVersion()).isEqualTo(PartitionKeyDefinitionVersion.V2); - assertThat(partitionKeyDef.getKind()).isEqualTo(PartitionKind.Hash); - assertThat(partitionKeyDef.getPaths().toArray()[0]).isEqualTo("/pk"); + assertThat(partitionKeyDef.version()).isEqualTo(PartitionKeyDefinitionVersion.V2); + assertThat(partitionKeyDef.kind()).isEqualTo(PartitionKind.HASH); + assertThat(partitionKeyDef.paths().toArray()[0]).isEqualTo("/pk"); } @Test(groups = "unit") public void hashV1PartitionKeyDeserialization() { - String partitionKeyDefinitionStr = "{\"paths\":[\"/pk\"],\"kind\":\"Hash\"}"; + String partitionKeyDefinitionStr = "{\"paths\":[\"/pk\"],\"kind\":\"HASH\"}"; PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(partitionKeyDefinitionStr); - assertThat(partitionKeyDef.getVersion()).isNull(); - assertThat(partitionKeyDef.getKind()).isEqualTo(PartitionKind.Hash); - assertThat(partitionKeyDef.getPaths().toArray()[0]).isEqualTo("/pk"); + assertThat(partitionKeyDef.version()).isNull(); + assertThat(partitionKeyDef.kind()).isEqualTo(PartitionKind.HASH); + assertThat(partitionKeyDef.paths().toArray()[0]).isEqualTo("/pk"); } } diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressResolverTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java similarity index 86% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressResolverTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java index 4c1fadafdeca0..3d5c815248ace 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressResolverTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java @@ -21,28 +21,28 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.routing.CollectionRoutingMap; -import com.microsoft.azure.cosmosdb.internal.routing.IServerIdentity; -import com.microsoft.azure.cosmosdb.internal.routing.InMemoryCollectionRoutingMap; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternalHelper; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.rx.internal.ICollectionRoutingMapCache; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionException; -import com.microsoft.azure.cosmosdb.rx.internal.NotFoundException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.IServerIdentity; +import com.azure.data.cosmos.internal.routing.InMemoryCollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.mutable.MutableObject; @@ -95,21 +95,21 @@ public void setup() throws Exception { this.addressResolver.initializeCaches(this.collectionCache, this.collectionRoutingMapCache, this.fabricAddressCache); this.collection1 = new DocumentCollection(); - this.collection1.setId("coll"); - this.collection1.setResourceId("rid1"); + this.collection1.id("coll"); + this.collection1.resourceId("rid1"); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); - partitionKeyDef.setPaths(ImmutableList.of("/field1")); + partitionKeyDef.paths(ImmutableList.of("/field1")); this.collection1.setPartitionKey(partitionKeyDef); this.collection2 = new DocumentCollection(); - this.collection2.setId("coll"); - this.collection2.setResourceId("rid2"); + this.collection2.id("coll"); + this.collection2.resourceId("rid2"); new PartitionKeyDefinition(); - partitionKeyDef.setPaths(ImmutableList.of("/field1")); + partitionKeyDef.paths(ImmutableList.of("/field1")); this.collection2.setPartitionKey(partitionKeyDef); Func1>, Void> addPartitionKeyRangeFunc = listArg -> { - listArg.forEach(tuple -> ((ServiceIdentity) tuple.right).partitionKeyRangeIds.add(new PartitionKeyRangeIdentity(collection1.getResourceId(), tuple.left.getId()))); + listArg.forEach(tuple -> ((ServiceIdentity) tuple.right).partitionKeyRangeIds.add(new PartitionKeyRangeIdentity(collection1.resourceId(), tuple.left.id()))); return null; }; @@ -127,7 +127,7 @@ public void setup() throws Exception { this.routingMapCollection1BeforeSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap( rangesBeforeSplit1, - collection1.getResourceId()); + collection1.resourceId()); List> rangesAfterSplit1 = new ArrayList<>(); @@ -146,7 +146,7 @@ public void setup() throws Exception { addPartitionKeyRangeFunc.call(rangesAfterSplit1); - this.routingMapCollection1AfterSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesAfterSplit1, collection1.getResourceId()); + this.routingMapCollection1AfterSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesAfterSplit1, collection1.resourceId()); List> rangesBeforeSplit2 = new ArrayList<>(); @@ -160,7 +160,7 @@ public void setup() throws Exception { addPartitionKeyRangeFunc.call(rangesBeforeSplit2); - this.routingMapCollection2BeforeSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesBeforeSplit2, collection2.getResourceId()); + this.routingMapCollection2BeforeSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesBeforeSplit2, collection2.resourceId()); List> rangesAfterSplit2 = new ArrayList<>(); @@ -181,7 +181,7 @@ public void setup() throws Exception { addPartitionKeyRangeFunc.call(rangesAfterSplit2); - this.routingMapCollection2AfterSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesAfterSplit2, collection2.getResourceId()); + this.routingMapCollection2AfterSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesAfterSplit2, collection2.resourceId()); } private void TestCacheRefreshWhileRouteByPartitionKey( @@ -203,7 +203,7 @@ private void TestCacheRefreshWhileRouteByPartitionKey( boolean nameBased) throws Exception { if (targetServiceIdentity != null && targetPartitionKeyRange != null) { - targetServiceIdentity.partitionKeyRangeIds.add(new PartitionKeyRangeIdentity(collectionAfterRefresh != null ? collectionAfterRefresh.getResourceId() : collectionBeforeRefresh.getResourceId(), targetPartitionKeyRange.getId())); + targetServiceIdentity.partitionKeyRangeIds.add(new PartitionKeyRangeIdentity(collectionAfterRefresh != null ? collectionAfterRefresh.resourceId() : collectionBeforeRefresh.resourceId(), targetPartitionKeyRange.id())); } this.initializeMocks( @@ -248,7 +248,7 @@ private void TestCacheRefreshWhileRouteByPartitionKey( assertThat(targetAddresses[0].getPhysicalUri()).isEqualTo(resolvedAddresses[0].getPhysicalUri()); // Assert.AreEqual(targetServiceIdentity, request.requestContext.TargetIdentity); - assertThat(targetPartitionKeyRange.getId()).isEqualTo(request.requestContext.resolvedPartitionKeyRange.getId()); + assertThat(targetPartitionKeyRange.id()).isEqualTo(request.requestContext.resolvedPartitionKeyRange.id()); } private void TestCacheRefreshWhileRouteByPartitionKeyRangeId( @@ -271,7 +271,7 @@ private void TestCacheRefreshWhileRouteByPartitionKeyRangeId( boolean nameBased) throws Exception { if (targetServiceIdentity != null && targetPartitionKeyRange != null) { - targetServiceIdentity.partitionKeyRangeIds.add(new PartitionKeyRangeIdentity(collectionAfterRefresh != null ? collectionAfterRefresh.getResourceId() : collectionBeforeRefresh.getResourceId(), targetPartitionKeyRange.getId())); + targetServiceIdentity.partitionKeyRangeIds.add(new PartitionKeyRangeIdentity(collectionAfterRefresh != null ? collectionAfterRefresh.resourceId() : collectionBeforeRefresh.resourceId(), targetPartitionKeyRange.id())); } this.initializeMocks( @@ -318,7 +318,7 @@ private void TestCacheRefreshWhileRouteByPartitionKeyRangeId( assertThat(targetAddresses[0].getPhysicalUri()).isEqualTo(resolvedAddresses[0].getPhysicalUri()); // Assert.AreEqual(targetServiceIdentity, request.requestContext.TargetIdentity); - assertThat(targetPartitionKeyRange.getId()).isEqualTo(request.requestContext.resolvedPartitionKeyRange.getId()); + assertThat(targetPartitionKeyRange.id()).isEqualTo(request.requestContext.resolvedPartitionKeyRange.id()); } private void initializeMocks( @@ -477,9 +477,9 @@ private static ServiceIdentity findMatchingServiceIdentity(Map ServiceIdentity findMatchingServiceIdentity(Map replicaAddresses = new ArrayList<>(); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos2", Protocol.Https)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos2", Protocol.HTTPS)); AddressSelector.getPrimaryUri(request, replicaAddresses); } @@ -69,9 +69,9 @@ public void getPrimaryUri() throws Exception { List replicaAddresses = new ArrayList<>(); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.Https)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.HTTPS)); URI res = AddressSelector.getPrimaryUri(request, replicaAddresses); @@ -85,9 +85,9 @@ public void getPrimaryUri_WithRequestReplicaIndex() throws Exception { List replicaAddresses = new ArrayList<>(); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos2", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.Https)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos2", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.HTTPS)); URI res = AddressSelector.getPrimaryUri(request, replicaAddresses); @@ -97,18 +97,18 @@ public void getPrimaryUri_WithRequestReplicaIndex() throws Exception { @Test(groups = "unit") public void resolvePrimaryUriAsync() { IAddressResolver addressResolver = Mockito.mock(IAddressResolver.class); - AddressSelector selector = new AddressSelector(addressResolver, Protocol.Https); + AddressSelector selector = new AddressSelector(addressResolver, Protocol.HTTPS); RxDocumentServiceRequest request = Mockito.mock(RxDocumentServiceRequest.class); Mockito.doReturn(null).when(request).getDefaultReplicaIndex(); List replicaAddresses = new ArrayList<>(); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos4", Protocol.Tcp)); - replicaAddresses.add(new AddressInformation(true, true, "https://cosmos5", Protocol.Tcp)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.Https)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos4", Protocol.TCP)); + replicaAddresses.add(new AddressInformation(true, true, "https://cosmos5", Protocol.TCP)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.HTTPS)); Mockito.doReturn(Single.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); @@ -120,18 +120,18 @@ public void resolvePrimaryUriAsync() { @Test(groups = "unit") public void resolveAllUriAsync() { IAddressResolver addressResolver = Mockito.mock(IAddressResolver.class); - AddressSelector selector = new AddressSelector(addressResolver, Protocol.Https); + AddressSelector selector = new AddressSelector(addressResolver, Protocol.HTTPS); RxDocumentServiceRequest request = Mockito.mock(RxDocumentServiceRequest.class); Mockito.doReturn(null).when(request).getDefaultReplicaIndex(); List replicaAddresses = new ArrayList<>(); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos4", Protocol.Tcp)); - replicaAddresses.add(new AddressInformation(true, true, "https://cosmos5", Protocol.Tcp)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.Https)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos4", Protocol.TCP)); + replicaAddresses.add(new AddressInformation(true, true, "https://cosmos5", Protocol.TCP)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.HTTPS)); Mockito.doReturn(Single.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); @@ -143,41 +143,41 @@ public void resolveAllUriAsync() { @Test(groups = "unit") public void resolveAddressesAsync() { IAddressResolver addressResolver = Mockito.mock(IAddressResolver.class); - AddressSelector selector = new AddressSelector(addressResolver, Protocol.Https); + AddressSelector selector = new AddressSelector(addressResolver, Protocol.HTTPS); RxDocumentServiceRequest request = Mockito.mock(RxDocumentServiceRequest.class); Mockito.doReturn(null).when(request).getDefaultReplicaIndex(); List replicaAddresses = new ArrayList<>(); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos4", Protocol.Tcp)); - replicaAddresses.add(new AddressInformation(true, true, "https://cosmos5", Protocol.Tcp)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.Https)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos4", Protocol.TCP)); + replicaAddresses.add(new AddressInformation(true, true, "https://cosmos5", Protocol.TCP)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.HTTPS)); Mockito.doReturn(Single.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); List res = selector.resolveAddressesAsync(request, false).toBlocking().value(); - assertThat(res).isEqualTo(replicaAddresses.stream().filter(a -> a.getProtocolName().equals(Protocol.Https.name())).collect(Collectors.toList())); + assertThat(res).isEqualTo(replicaAddresses.stream().filter(a -> a.getProtocolName().equals(Protocol.HTTPS.name())).collect(Collectors.toList())); } @Test(groups = "unit") public void resolveAllUriAsync_RNTBD() { IAddressResolver addressResolver = Mockito.mock(IAddressResolver.class); - AddressSelector selector = new AddressSelector(addressResolver, Protocol.Tcp); + AddressSelector selector = new AddressSelector(addressResolver, Protocol.TCP); RxDocumentServiceRequest request = Mockito.mock(RxDocumentServiceRequest.class); Mockito.doReturn(null).when(request).getDefaultReplicaIndex(); List replicaAddresses = new ArrayList<>(); - replicaAddresses.add(new AddressInformation(true, false, "rntbd://cosmos1", Protocol.Tcp)); - replicaAddresses.add(new AddressInformation(true, true, "rntbd://cosmos2", Protocol.Tcp)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.Https)); - replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.Https)); + replicaAddresses.add(new AddressInformation(true, false, "rntbd://cosmos1", Protocol.TCP)); + replicaAddresses.add(new AddressInformation(true, true, "rntbd://cosmos2", Protocol.TCP)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos1", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.HTTPS)); + replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.HTTPS)); Mockito.doReturn(Single.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressSelectorWrapper.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java similarity index 98% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressSelectorWrapper.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java index a968ffb24bc2f..b1f3b52d3a9f8 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressSelectorWrapper.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.assertj.core.api.Condition; @@ -464,7 +464,7 @@ public static class Simple extends Builder { private URI primaryAddress; private List secondaryAddresses; static Simple create() { - return new Simple(Protocol.Https); + return new Simple(Protocol.HTTPS); } public Simple(Protocol protocol) { diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java similarity index 90% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyReaderTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java index 36c3795fe9610..a067058a7b2e4 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java @@ -21,26 +21,26 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.ISessionToken; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.VectorSessionToken; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.DocumentServiceRequestContext; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.NotFoundException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ISessionToken; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.VectorSessionToken; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.DocumentServiceRequestContext; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; import org.mockito.Mockito; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -53,7 +53,7 @@ import java.util.List; import java.util.concurrent.TimeUnit; -import static com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import static com.azure.data.cosmos.internal.Utils.ValueHolder; import static org.assertj.core.api.Assertions.assertThat; public class ConsistencyReaderTest { @@ -63,21 +63,21 @@ public class ConsistencyReaderTest { public Object[][] deduceReadModeArgProvider() { return new Object[][]{ // account consistency, request consistency, expected readmode, expected consistency to use, whether use session - { ConsistencyLevel.Strong, null, ReadMode.Strong, ConsistencyLevel.Strong, false}, - { ConsistencyLevel.Strong, ConsistencyLevel.Eventual, ReadMode.Any, ConsistencyLevel.Eventual, false}, - { ConsistencyLevel.Strong, ConsistencyLevel.Session, ReadMode.Any, ConsistencyLevel.Session, true}, - { ConsistencyLevel.Session, ConsistencyLevel.Eventual, ReadMode.Any, ConsistencyLevel.Eventual, false}, - { ConsistencyLevel.Session, ConsistencyLevel.Session, ReadMode.Any, ConsistencyLevel.Session, true}, - { ConsistencyLevel.Session, ConsistencyLevel.Eventual, ReadMode.Any, ConsistencyLevel.Eventual, false}, - { ConsistencyLevel.Session, null, ReadMode.Any, ConsistencyLevel.Session, true}, - { ConsistencyLevel.Eventual, ConsistencyLevel.Eventual, ReadMode.Any, ConsistencyLevel.Eventual, false}, - { ConsistencyLevel.Eventual, null, ReadMode.Any, ConsistencyLevel.Eventual, false}, + { ConsistencyLevel.STRONG, null, ReadMode.Strong, ConsistencyLevel.STRONG, false}, + { ConsistencyLevel.STRONG, ConsistencyLevel.EVENTUAL, ReadMode.Any, ConsistencyLevel.EVENTUAL, false}, + { ConsistencyLevel.STRONG, ConsistencyLevel.SESSION, ReadMode.Any, ConsistencyLevel.SESSION, true}, + { ConsistencyLevel.SESSION, ConsistencyLevel.EVENTUAL, ReadMode.Any, ConsistencyLevel.EVENTUAL, false}, + { ConsistencyLevel.SESSION, ConsistencyLevel.SESSION, ReadMode.Any, ConsistencyLevel.SESSION, true}, + { ConsistencyLevel.SESSION, ConsistencyLevel.EVENTUAL, ReadMode.Any, ConsistencyLevel.EVENTUAL, false}, + { ConsistencyLevel.SESSION, null, ReadMode.Any, ConsistencyLevel.SESSION, true}, + { ConsistencyLevel.EVENTUAL, ConsistencyLevel.EVENTUAL, ReadMode.Any, ConsistencyLevel.EVENTUAL, false}, + { ConsistencyLevel.EVENTUAL, null, ReadMode.Any, ConsistencyLevel.EVENTUAL, false}, }; } @Test(groups = "unit", dataProvider = "deduceReadModeArgProvider") public void deduceReadMode(ConsistencyLevel accountConsistencyLevel, ConsistencyLevel requestConsistency, ReadMode expectedReadMode, - ConsistencyLevel expectedConsistencyToUse, boolean expectedToUseSession) throws DocumentClientException { + ConsistencyLevel expectedConsistencyToUse, boolean expectedToUseSession) throws CosmosClientException { AddressSelector addressSelector = Mockito.mock(AddressSelector.class); ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class); TransportClient transportClient = Mockito.mock(TransportClient.class); @@ -127,7 +127,7 @@ public void replicaSizes(int systemMaxReplicaCount, AddressSelector addressSelector = Mockito.mock(AddressSelector.class); ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class); TransportClient transportClient = Mockito.mock(TransportClient.class); - GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.Strong, + GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.STRONG, systemMaxReplicaCount, systemMinReplicaCount, userMaxReplicaCount, @@ -189,7 +189,7 @@ public void readAny() { .storeResponseOn(secondaries.get(2), OperationType.Read, ResourceType.Document, secondaryResponse3, true) .build(); - GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.Strong); + GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.STRONG); ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class); IAuthorizationTokenProvider authorizationTokenProvider = Mockito.mock(IAuthorizationTokenProvider.class); @@ -201,7 +201,7 @@ public void readAny() { RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Eventual.name()); + request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.EVENTUAL.name()); TimeoutHelper timeout = Mockito.mock(TimeoutHelper.class); boolean forceRefresh = false; @@ -298,7 +298,7 @@ public void readSessionConsistency_SomeReplicasLagBehindAndReturningResponseWith .storeResponseOn(secondaries.get(2), OperationType.Read, ResourceType.Document, secondaryResponse3, true) .build(); - GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.Strong); + GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.STRONG); ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class); IAuthorizationTokenProvider authorizationTokenProvider = Mockito.mock(IAuthorizationTokenProvider.class); @@ -310,7 +310,7 @@ public void readSessionConsistency_SomeReplicasLagBehindAndReturningResponseWith RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Session.name()); + request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); request.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); assertThat(VectorSessionToken.tryCreate("-1#" + fasterReplicaLSN , sessionToken)).isTrue(); @@ -371,10 +371,10 @@ public void sessionNotAvailableFromSomeReplicasThrowingNotFound_FindReplicaSatis String partitionKeyRangeId = "1"; NotFoundException foundException = new NotFoundException(); - foundException.getResponseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + slowReplicaLSN); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(slowReplicaLSN)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(slowReplicaLSN)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); + foundException.responseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + slowReplicaLSN); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(slowReplicaLSN)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(slowReplicaLSN)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); StoreResponse storeResponse = StoreResponseBuilder.create() .withSessionToken(partitionKeyRangeId + ":-1#" + fasterReplicaLSN) @@ -407,7 +407,7 @@ public void sessionNotAvailableFromSomeReplicasThrowingNotFound_FindReplicaSatis ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class); Configs configs = new Configs(); - GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.Strong, + GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.STRONG, 4, 3, 4, @@ -425,7 +425,7 @@ public void sessionNotAvailableFromSomeReplicasThrowingNotFound_FindReplicaSatis TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Session.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); assertThat(VectorSessionToken.tryCreate("-1#" + fasterReplicaLSN , sessionToken)).isTrue(); @@ -451,10 +451,10 @@ public void sessionRead_LegitimateNotFound() { String partitionKeyRangeId = "73"; NotFoundException foundException = new NotFoundException(); - foundException.getResponseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(lsn)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(lsn)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); + foundException.responseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(lsn)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(lsn)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); TransportClientWrapper transportClientWrapper = new TransportClientWrapper.Builder.ReplicaResponseBuilder .SequentialBuilder() @@ -477,7 +477,7 @@ public void sessionRead_LegitimateNotFound() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Session.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); assertThat(VectorSessionToken.tryCreate("-1#" + lsn , sessionToken)).isTrue(); @@ -488,7 +488,7 @@ public void sessionRead_LegitimateNotFound() { Mockito.doReturn(sessionToken.v).when(sessionContainer).resolvePartitionLocalSessionToken(Mockito.eq(dsr), Mockito.anyString()); Configs configs = new Configs(); - GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.Strong, + GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.STRONG, 4, 3, 4, @@ -517,10 +517,10 @@ public void sessionRead_ReplicasDoNotHaveTheRequestedLSN() { long globalCommittedLsn = 651174; String partitionKeyRangeId = "73"; NotFoundException foundException = new NotFoundException(); - foundException.getResponseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(651175)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(651175)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); + foundException.responseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(651175)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(651175)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); TransportClientWrapper transportClientWrapper = new TransportClientWrapper.Builder.ReplicaResponseBuilder .SequentialBuilder() @@ -543,7 +543,7 @@ public void sessionRead_ReplicasDoNotHaveTheRequestedLSN() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Session.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); assertThat(VectorSessionToken.tryCreate("-1#" + (lsn + 1) , sessionToken)).isTrue(); @@ -554,7 +554,7 @@ public void sessionRead_ReplicasDoNotHaveTheRequestedLSN() { Mockito.doReturn(sessionToken.v).when(sessionContainer).resolvePartitionLocalSessionToken(Mockito.eq(dsr), Mockito.anyString()); Configs configs = new Configs(); - GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.Strong, + GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.STRONG, 4, 3, 4, @@ -581,10 +581,10 @@ public void requestRateTooLarge_BubbleUp() { String partitionKeyRangeId = "73"; RequestRateTooLargeException requestTooLargeException = new RequestRateTooLargeException(); - requestTooLargeException.getResponseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); - requestTooLargeException.getResponseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(651175)); - requestTooLargeException.getResponseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(651175)); - requestTooLargeException.getResponseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); + requestTooLargeException.responseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); + requestTooLargeException.responseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(651175)); + requestTooLargeException.responseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(651175)); + requestTooLargeException.responseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); TransportClientWrapper transportClientWrapper = new TransportClientWrapper.Builder.ReplicaResponseBuilder .SequentialBuilder() @@ -607,7 +607,7 @@ public void requestRateTooLarge_BubbleUp() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Session.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); assertThat(VectorSessionToken.tryCreate("-1#" + lsn , sessionToken)).isTrue(); @@ -618,7 +618,7 @@ public void requestRateTooLarge_BubbleUp() { Mockito.doReturn(sessionToken.v).when(sessionContainer).resolvePartitionLocalSessionToken(Mockito.eq(dsr), Mockito.anyString()); Configs configs = new Configs(); - GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.Strong, + GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.STRONG, 4, 3, 4, @@ -776,7 +776,7 @@ public static void validateException(Single single, private PartitionKeyRange partitionKeyRangeWithId(String id) { PartitionKeyRange partitionKeyRange = Mockito.mock(PartitionKeyRange.class); - Mockito.doReturn(id).when(partitionKeyRange).getId(); + Mockito.doReturn(id).when(partitionKeyRange).id(); return partitionKeyRange; } } diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyReaderUnderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderUnderTest.java similarity index 93% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyReaderUnderTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderUnderTest.java index 4f35b9c0e9738..7e2a8408a3096 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyReaderUnderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderUnderTest.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import org.mockito.Mockito; public class ConsistencyReaderUnderTest extends ConsistencyReader { diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyWriterTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java similarity index 89% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyWriterTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java index 02f5b97aef373..f5ca74e97b022 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ConsistencyWriterTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java @@ -21,18 +21,18 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.internal.DocumentServiceRequestContext; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionIsMigratingException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionKeyRangeIsSplittingException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.DocumentServiceRequestContext; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.PartitionIsMigratingException; +import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -52,10 +52,10 @@ import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.StatusCodes.GONE; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.SubStatusCodes.COMPLETING_PARTITION_MIGRATION; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.SubStatusCodes.COMPLETING_SPLIT; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE; +import static com.azure.data.cosmos.internal.HttpConstants.StatusCodes.GONE; +import static com.azure.data.cosmos.internal.HttpConstants.SubStatusCodes.COMPLETING_PARTITION_MIGRATION; +import static com.azure.data.cosmos.internal.HttpConstants.SubStatusCodes.COMPLETING_SPLIT; +import static com.azure.data.cosmos.internal.HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE; import static org.assertj.core.api.Assertions.assertThat; public class ConsistencyWriterTest { @@ -221,14 +221,14 @@ public void timeout2() throws Exception { public Object[][] globalStrongArgProvider() { return new Object[][]{ { - ConsistencyLevel.Session, + ConsistencyLevel.SESSION, Mockito.mock(RxDocumentServiceRequest.class), Mockito.mock(StoreResponse.class), false, }, { - ConsistencyLevel.Eventual, + ConsistencyLevel.EVENTUAL, Mockito.mock(RxDocumentServiceRequest.class), Mockito.mock(StoreResponse.class), @@ -236,7 +236,7 @@ public Object[][] globalStrongArgProvider() { }, { - ConsistencyLevel.Eventual, + ConsistencyLevel.EVENTUAL, Mockito.mock(RxDocumentServiceRequest.class), StoreResponseBuilder.create() .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, Integer.toString(5)) @@ -245,7 +245,7 @@ public Object[][] globalStrongArgProvider() { }, { - ConsistencyLevel.Strong, + ConsistencyLevel.STRONG, Mockito.mock(RxDocumentServiceRequest.class), StoreResponseBuilder.create() .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, Integer.toString(5)) @@ -254,7 +254,7 @@ public Object[][] globalStrongArgProvider() { }, { - ConsistencyLevel.Strong, + ConsistencyLevel.STRONG, Mockito.mock(RxDocumentServiceRequest.class), StoreResponseBuilder.create() .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, Integer.toString(0)) @@ -289,8 +289,8 @@ private void initializeConsistencyWriter(boolean useMultipleWriteLocation) { useMultipleWriteLocation); } - // TODO: add more mocking unit tests for Global Strong (mocking unit tests) - // TODO: add more tests for Session behaviour (mocking unit tests) + // TODO: add more mocking unit tests for Global STRONG (mocking unit tests) + // TODO: add more tests for SESSION behaviour (mocking unit tests) // TODO: add more tests for error handling behaviour (mocking unit tests) // TODO: add tests for replica catch up (request barrier while loop) (mocking unit tests) // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/320977 diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/EndpointMock.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/EndpointMock.java similarity index 98% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/EndpointMock.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/EndpointMock.java index d2d709b3bb185..3dc677c48daf3 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/EndpointMock.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/EndpointMock.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.collections.map.HashedMap; import java.net.URI; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ExceptionBuilder.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ExceptionBuilder.java similarity index 73% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ExceptionBuilder.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ExceptionBuilder.java index d73c90350fb12..467e8ece1e2ed 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ExceptionBuilder.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ExceptionBuilder.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionIsMigratingException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.PartitionIsMigratingException; +import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; import java.util.AbstractMap; import java.util.ArrayList; @@ -34,7 +34,7 @@ import java.util.Map; import java.util.stream.Collectors; -public class ExceptionBuilder { +public class ExceptionBuilder { private Integer status; private List> headerEntries; private String message; @@ -65,21 +65,21 @@ public ExceptionBuilder withMessage(String message) { public GoneException asGoneException() { assert status == null; GoneException dce = new GoneException(); - dce.getResponseHeaders().putAll(headerEntries.stream().collect(Collectors.toMap(i -> i.getKey(), i -> i.getValue()))); + dce.responseHeaders().putAll(headerEntries.stream().collect(Collectors.toMap(i -> i.getKey(), i -> i.getValue()))); return dce; } public InvalidPartitionException asInvalidPartitionException() { assert status == null; InvalidPartitionException dce = new InvalidPartitionException(); - dce.getResponseHeaders().putAll(headerEntries.stream().collect(Collectors.toMap(i -> i.getKey(), i -> i.getValue()))); + dce.responseHeaders().putAll(headerEntries.stream().collect(Collectors.toMap(i -> i.getKey(), i -> i.getValue()))); return dce; } public PartitionKeyRangeGoneException asPartitionKeyRangeGoneException() { assert status == null; PartitionKeyRangeGoneException dce = new PartitionKeyRangeGoneException(); - dce.getResponseHeaders().putAll(headerEntries.stream().collect(Collectors.toMap(i -> i.getKey(), i -> i.getValue()))); + dce.responseHeaders().putAll(headerEntries.stream().collect(Collectors.toMap(i -> i.getKey(), i -> i.getValue()))); return dce; } @@ -87,14 +87,14 @@ public PartitionKeyRangeGoneException asPartitionKeyRangeGoneException() { public PartitionKeyRangeIsSplittingException asPartitionKeyRangeIsSplittingException() { assert status == null; PartitionKeyRangeIsSplittingException dce = new PartitionKeyRangeIsSplittingException(); - dce.getResponseHeaders().putAll(headerEntries.stream().collect(Collectors.toMap(i -> i.getKey(), i -> i.getValue()))); + dce.responseHeaders().putAll(headerEntries.stream().collect(Collectors.toMap(i -> i.getKey(), i -> i.getValue()))); return dce; } public PartitionIsMigratingException asPartitionIsMigratingException() { assert status == null; PartitionIsMigratingException dce = new PartitionIsMigratingException(); - dce.getResponseHeaders().putAll(headerEntries.stream().collect(Collectors.toMap(i -> i.getKey(), i -> i.getValue()))); + dce.responseHeaders().putAll(headerEntries.stream().collect(Collectors.toMap(i -> i.getKey(), i -> i.getValue()))); return dce; } } diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Function1WithCheckedException.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function1WithCheckedException.java similarity index 95% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Function1WithCheckedException.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function1WithCheckedException.java index 3e55f35763fe3..cc1f731c279ad 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Function1WithCheckedException.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function1WithCheckedException.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; @FunctionalInterface public interface Function1WithCheckedException{ diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Function2WithCheckedException.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function2WithCheckedException.java similarity index 95% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Function2WithCheckedException.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function2WithCheckedException.java index 093ce601fcfed..f6f0b5c926a00 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/Function2WithCheckedException.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function2WithCheckedException.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; @FunctionalInterface public interface Function2WithCheckedException{ diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java similarity index 94% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java index 0b536d36c7403..f2cd8fa529fc9 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DatabaseAccount; -import com.microsoft.azure.cosmosdb.ReplicationPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.DatabaseAccount; +import com.azure.data.cosmos.ReplicationPolicy; import org.mockito.Mockito; import rx.Single; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java similarity index 89% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java index b9895fe301b72..d2a01a4a94ae9 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java @@ -22,18 +22,18 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.internal.BadRequestException; -import com.microsoft.azure.cosmosdb.rx.internal.IRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionIsMigratingException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionKeyRangeIsSplittingException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.IRetryPolicy; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.PartitionIsMigratingException; +import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.testng.annotations.Test; import rx.Single; @@ -121,8 +121,8 @@ public void shouldRetryWithInvalidPartitionException() { shouldRetryResult = goneAndRetryWithRetryPolicy.shouldRetry(new InvalidPartitionException()).toBlocking() .value(); assertThat(shouldRetryResult.shouldRetry).isFalse(); - DocumentClientException clientException = (DocumentClientException) shouldRetryResult.exception; - assertThat(clientException.getStatusCode()).isEqualTo(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE); + CosmosClientException clientException = (CosmosClientException) shouldRetryResult.exception; + assertThat(clientException.statusCode()).isEqualTo(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE); } diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpClientMockWrapper.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpClientMockWrapper.java similarity index 99% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpClientMockWrapper.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpClientMockWrapper.java index f456424a0319e..692cb5af6fcbd 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpClientMockWrapper.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpClientMockWrapper.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpTransportClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java similarity index 97% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpTransportClientTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java index f4ca18efd0521..a8729e10cb6de 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/HttpTransportClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java @@ -21,21 +21,21 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.InternalServerErrorException; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.internal.BadRequestException; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionException; -import com.microsoft.azure.cosmosdb.rx.internal.NotFoundException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionIsMigratingException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionKeyRangeIsSplittingException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.PartitionIsMigratingException; +import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import io.netty.buffer.ByteBuf; import io.netty.channel.ConnectTimeoutException; import io.netty.handler.codec.http.EmptyHttpHeaders; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/MultiStoreResultValidator.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MultiStoreResultValidator.java similarity index 95% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/MultiStoreResultValidator.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MultiStoreResultValidator.java index 3b948d992ba4e..f6eabb6554778 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/MultiStoreResultValidator.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MultiStoreResultValidator.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.base.Predicates; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.rx.FailureValidator; import org.apache.commons.lang3.mutable.MutableObject; import org.assertj.core.description.Description; import org.assertj.core.description.TextDescription; @@ -86,7 +86,7 @@ public void validate(List storeResults) { for(StoreResult srr: storeResults) { try { storeResponseValidator.validate(srr.toResponse()); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { fail(e.getMessage()); } } @@ -148,7 +148,7 @@ public void validate(List storeResults) { for(StoreResult srr: storeResults) { try { failureValidator.validate(srr.getException()); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { fail(e.getMessage()); } } diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/MurmurHash3_32Test.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MurmurHash3_32Test.java similarity index 97% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/MurmurHash3_32Test.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MurmurHash3_32Test.java index 0e8e01b2baa58..bd6fb05c40584 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/MurmurHash3_32Test.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MurmurHash3_32Test.java @@ -22,11 +22,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; -import com.microsoft.azure.cosmosdb.internal.routing.MurmurHash3_32; +import com.azure.data.cosmos.internal.routing.MurmurHash3_32; import org.apache.commons.lang3.RandomUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionKeyInternalTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java similarity index 96% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionKeyInternalTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java index 46d72c3e5b66d..12f93f5600573 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionKeyInternalTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java @@ -22,18 +22,18 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import com.microsoft.azure.cosmosdb.CommonsBridgeInternal; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.PartitionKind; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternalHelper; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternalUtils; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.CommonsBridgeInternal; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.PartitionKind; +import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternalUtils; +import com.azure.data.cosmos.internal.RMResources; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import rx.functions.Func2; @@ -312,7 +312,7 @@ public void hashEffectivePartitionKey() { .isEqualTo(PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey); PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); - partitionKeyDefinition.setPaths(Lists.newArrayList("/A", "/B", "/C", "/E", "/F", "/G")); + partitionKeyDefinition.paths(Lists.newArrayList("/A", "/B", "/C", "/E", "/F", "/G")); PartitionKeyInternal partitionKey = PartitionKeyInternal.fromObjectArray( new Object[]{2, true, false, null, Undefined.Value(), "Привет!"}, true); @@ -355,7 +355,7 @@ public void managedNativeCompatibility() { PartitionKeyInternal.fromJsonString("[\"по-русски\",null,true,false,{},5.5]"); PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); - pkDefinition.setPaths(ImmutableList.of("/field1", "/field2", "/field3", "/field4", "/field5", "/field6")); + pkDefinition.paths(ImmutableList.of("/field1", "/field2", "/field3", "/field4", "/field5", "/field6")); String effectivePartitionKey = PartitionKeyInternalHelper.getEffectivePartitionKeyString(partitionKey, pkDefinition); assertThat("05C1D39FA55F0408D1C0D1BF2ED281D284D282D282D1BBD1B9000103020005C016").isEqualTo(effectivePartitionKey); @@ -440,7 +440,7 @@ private static void validateEffectivePartitionKeyV2(String partitionKeyRangeJson PartitionKeyInternal partitionKey = PartitionKeyInternal.fromJsonString(partitionKeyRangeJson); PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); - partitionKeyDefinition.setKind(PartitionKind.Hash); + partitionKeyDefinition.kind(PartitionKind.HASH); CommonsBridgeInternal.setV2(partitionKeyDefinition); ArrayList paths = new ArrayList(); for (int i = 0; i < partitionKey.getComponents().size(); i++) { @@ -448,7 +448,7 @@ private static void validateEffectivePartitionKeyV2(String partitionKeyRangeJson } if (paths.size() > 0) { - partitionKeyDefinition.setPaths(paths); + partitionKeyDefinition.paths(paths); } String hexEncodedEffectivePartitionKey = PartitionKeyInternalHelper.getEffectivePartitionKeyString(partitionKey, partitionKeyDefinition); @@ -462,7 +462,7 @@ private void verifyComparison(String leftKey, String rightKey, int result) { private static void verifyEffectivePartitionKeyEncoding(String buffer, int length, String expectedValue, boolean v2) { PartitionKeyDefinition pkDefinition = new PartitionKeyDefinition(); - pkDefinition.setPaths(ImmutableList.of("/field1")); + pkDefinition.paths(ImmutableList.of("/field1")); if (v2) { CommonsBridgeInternal.setV2(pkDefinition); } diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionKeyTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java similarity index 88% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionKeyTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java index 31164b31156ca..60bab86d51a5f 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionKeyTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java @@ -21,14 +21,14 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternalHelper; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; +import com.azure.data.cosmos.internal.RMResources; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -72,7 +72,7 @@ public void partitionKeyCompare(Object partitionKey, String partitionKeyAsJson) @Test(groups = "unit") public void tooFewPartitionKeyComponents() { PartitionKeyDefinition pkd = new PartitionKeyDefinition(); - pkd.setPaths(ImmutableList.of("/pk1", "/pk2")); + pkd.paths(ImmutableList.of("/pk1", "/pk2")); PartitionKey pk = PartitionKey.FromJsonString("[\"PartitionKeyValue\"]"); try { @@ -89,7 +89,7 @@ public void tooFewPartitionKeyComponents() { @Test(groups = "unit") public void tooManyPartitionKeyComponents() { PartitionKeyDefinition pkd = new PartitionKeyDefinition(); - pkd.setPaths(ImmutableList.of("/pk1")); + pkd.paths(ImmutableList.of("/pk1")); PartitionKey pk = PartitionKey.FromJsonString("[true, false]"); try { diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/QuorumReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java similarity index 97% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/QuorumReaderTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java index cff71c20577a9..6fe2c07533bef 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/QuorumReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java @@ -21,21 +21,21 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.DocumentServiceRequestContextValidator; -import com.microsoft.azure.cosmosdb.rx.DocumentServiceRequestValidator; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.DocumentServiceRequestContext; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.rx.DocumentServiceRequestContextValidator; +import com.azure.data.cosmos.rx.DocumentServiceRequestValidator; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.DocumentServiceRequestContext; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.mockito.Mockito; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicaAddressFactory.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicaAddressFactory.java similarity index 97% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicaAddressFactory.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicaAddressFactory.java index 472f9e19eb7db..fcc53b36e0353 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicaAddressFactory.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicaAddressFactory.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import org.apache.commons.lang3.RandomStringUtils; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java similarity index 89% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java index dfc26fef75a42..e5aff73af344e 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java @@ -21,21 +21,21 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.SessionContainer; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.DocumentServiceRequestContext; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionKeyRangeIsSplittingException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.SessionContainer; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.DocumentServiceRequestContext; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.assertj.core.api.Assertions; import org.mockito.Mockito; import org.testng.annotations.DataProvider; @@ -55,9 +55,9 @@ public class ReplicatedResourceClientPartitionSplitTest { public Object[][] partitionIsSplittingArgProvider() { return new Object[][]{ // Consistency mode, number of partition splitting exception till split migration completes - { ConsistencyLevel.Eventual, 1}, - { ConsistencyLevel.Eventual, 2}, - { ConsistencyLevel.Eventual, Integer.MAX_VALUE }, // server side partition split operation never completes + { ConsistencyLevel.EVENTUAL, 1}, + { ConsistencyLevel.EVENTUAL, 2}, + { ConsistencyLevel.EVENTUAL, Integer.MAX_VALUE }, // server side partition split operation never completes }; } @@ -72,7 +72,7 @@ public void partitionSplit_RefreshCache_Read(ConsistencyLevel consistencyLevel, String partitionKeyRangeIdBeforeSplit = "1"; String partitionKeyRangeIdAfterSplit = "2"; - AddressSelectorWrapper addressSelectorWrapper = AddressSelectorWrapper.Builder.ReplicaMoveBuilder.create(Protocol.Https) + AddressSelectorWrapper addressSelectorWrapper = AddressSelectorWrapper.Builder.ReplicaMoveBuilder.create(Protocol.HTTPS) .withPrimaryMove(primaryAddressBeforeMove, primaryAddressAfterMove) .withSecondaryMove(secondary1AddressBeforeMove, secondary1AddressAfterMove) .newPartitionKeyRangeIdOnRefresh(r -> partitionKeyRangeWithId(partitionKeyRangeIdAfterSplit)) @@ -121,7 +121,7 @@ public void partitionSplit_RefreshCache_Read(ConsistencyLevel consistencyLevel, TransportClientWrapper transportClientWrapper = transportClientWrapperBuilder.build(); - GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.Strong, + GatewayServiceConfiguratorReaderMock gatewayServiceConfigurationReaderWrapper = GatewayServiceConfiguratorReaderMock.from(ConsistencyLevel.STRONG, 4, 3, 4, @@ -158,7 +158,7 @@ public void partitionSplit_RefreshCache_Read(ConsistencyLevel consistencyLevel, addressSelectorWrapper.verifyNumberOfForceCacheRefreshGreaterThanOrEqualTo(1); } else { - FailureValidator validator = FailureValidator.builder().instanceOf(DocumentClientException.class) + FailureValidator validator = FailureValidator.builder().instanceOf(CosmosClientException.class) .statusCode(503).build(); validateFailure(storeResponseObs, validator, TIMEOUT); } @@ -212,7 +212,7 @@ public static void validateFailure(Single single, FailureValidato private PartitionKeyRange partitionKeyRangeWithId(String id) { PartitionKeyRange partitionKeyRange = Mockito.mock(PartitionKeyRange.class); - Mockito.doReturn(id).when(partitionKeyRange).getId(); + Mockito.doReturn(id).when(partitionKeyRange).id(); return partitionKeyRange; } } diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicatedResourceClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java similarity index 87% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicatedResourceClientTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java index 55c8c4c6da040..0328d3bd013aa 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/ReplicatedResourceClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java @@ -22,15 +22,15 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.assertj.core.api.Assertions; import org.mockito.Matchers; import org.mockito.Mockito; @@ -65,9 +65,9 @@ public void setup() throws Exception { @Test(groups = { "unit" }, timeOut = TIMEOUT) public void invokeAsyncWithGoneException() { Configs configs = new Configs(); - ReplicatedResourceClient resourceClient = new ReplicatedResourceClient(configs, new AddressSelector(addressResolver, Protocol.Https), null, + ReplicatedResourceClient resourceClient = new ReplicatedResourceClient(configs, new AddressSelector(addressResolver, Protocol.HTTPS), null, transportClient, serviceConfigReader, authorizationTokenProvider, enableReadRequestsFallback, false); - FailureValidator validator = FailureValidator.builder().instanceOf(DocumentClientException.class).build(); + FailureValidator validator = FailureValidator.builder().instanceOf(CosmosClientException.class).build(); RxDocumentServiceRequest request = Mockito.spy(RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Document)); Mockito.when(addressResolver.resolveAsync(Matchers.any(), Matchers.anyBoolean())) diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RntbdTransportClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java similarity index 94% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RntbdTransportClientTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java index 44ec29a004e1f..e39fc7894afe5 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/RntbdTransportClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java @@ -21,34 +21,34 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.BaseAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.internal.InternalServerErrorException; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.Paths; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdContext; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdContextNegotiator; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdContextRequest; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdRequestArgs; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdRequestEncoder; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdRequestManager; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdResponse; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdResponseDecoder; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdUUID; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.internal.BadRequestException; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionException; -import com.microsoft.azure.cosmosdb.rx.internal.NotFoundException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionIsMigratingException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionKeyRangeIsSplittingException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContext; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContextNegotiator; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContextRequest; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestArgs; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestEncoder; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestManager; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdResponse; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdResponseDecoder; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdUUID; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.PartitionIsMigratingException; +import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandler; @@ -78,9 +78,9 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.HttpHeaders; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.HttpMethods; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.SubStatusCodes; +import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; +import static com.azure.data.cosmos.internal.HttpConstants.HttpMethods; +import static com.azure.data.cosmos.internal.HttpConstants.SubStatusCodes; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; @@ -673,7 +673,7 @@ public void onNext(StoreResponse response) { public void verifyNetworkFailure( FailureValidator.Builder builder, RxDocumentServiceRequest request, - DocumentClientException exception + CosmosClientException exception ) { throw new UnsupportedOperationException("TODO: DANOBLE: Implement this test"); } diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreReaderDotNetTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java similarity index 95% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreReaderDotNetTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java index 9b0d4bfa0b983..b8d6733b10744 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreReaderDotNetTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java @@ -21,27 +21,27 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.ReplicationPolicy; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.SessionContainer; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.internal.AuthorizationTokenType; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.DocumentServiceRequestContext; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.ReplicationPolicy; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.SessionContainer; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.AuthorizationTokenType; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.DocumentServiceRequestContext; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.Strings; import org.apache.commons.lang3.StringUtils; import org.mockito.Matchers; import org.mockito.Mockito; @@ -72,7 +72,7 @@ public void addressCache() { // setup mocks for address information AddressInformation[] addressInformation = new AddressInformation[3]; for (int i = 0; i < 3; i++) { - addressInformation[i] = new AddressInformation(true, true, "http://replica-" + i, Protocol.Https); + addressInformation[i] = new AddressInformation(true, true, "http://replica-" + i, Protocol.HTTPS); } IAddressResolver mockAddressCache = Mockito.mock(IAddressResolver.class); @@ -103,7 +103,7 @@ public void transportClient() { String physicalUri = "rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/" + Integer.toString(i) + (i == 0 ? "p" : "s") + "/"; - addressInformation[i] = new AddressInformation(true, true, physicalUri, Protocol.Tcp); + addressInformation[i] = new AddressInformation(true, true, physicalUri, Protocol.TCP); } @@ -420,7 +420,7 @@ private AddressInformation[] getMockAddressInformationDuringUpgrade() { String physicalUri = "rntbd://dummytenant.documents.azure.com:14003/apps/APPGUID/services/SERVICEGUID/partitions/PARTITIONGUID/replicas/" + Integer.toString(i) + (i == 0 ? "p" : "s") + "/"; - addressInformation[i] = new AddressInformation(true, i == 0 ? true : false, physicalUri, Protocol.Tcp); + addressInformation[i] = new AddressInformation(true, i == 0 ? true : false, physicalUri, Protocol.TCP); } return addressInformation; @@ -464,7 +464,7 @@ public void storeReaderBarrier() { // entity.requestContext.timeoutHelper = new TimeoutHelper(new TimeSpan(2, 2, 2)); entity.requestContext.timeoutHelper = Mockito.mock(TimeoutHelper.class); - // when the store reader throws Invalid Partition exception, the higher layer should + // when the store reader throws INVALID Partition exception, the higher layer should // clear this target identity. // entity.requestContext.TargetIdentity = new ServiceIdentity("dummyTargetIdentity1", new Uri("http://dummyTargetIdentity1"), false); entity.requestContext.resolvedPartitionKeyRange = new PartitionKeyRange(); @@ -477,7 +477,7 @@ public void storeReaderBarrier() { assertThat(addressInfo[0]).isEqualTo(addressInformation[0]); - AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.Tcp); + AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.TCP); URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false /*forceAddressRefresh*/).toBlocking().value(); // check if the address return from Address Selector matches the original address info @@ -590,12 +590,12 @@ public void storeClient() throws URISyntaxException { entity.setResourceId("1-MxAPlgMgA="); // set consistency level on the request to Bounded Staleness - entity.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.BoundedStaleness.toString()); + entity.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.BOUNDED_STALENESS.toString()); // also setup timeout helper, used in store reader entity.requestContext.timeoutHelper = new TimeoutHelper(Duration.ofSeconds(2 * 60 * 60 + 2 * 60 + 2)); - // when the store reader throws Invalid Partition exception, the higher layer should + // when the store reader throws INVALID Partition exception, the higher layer should entity.requestContext.resolvedPartitionKeyRange = new PartitionKeyRange(); AddressInformation[] addressInformations = getMockAddressInformationDuringUpgrade(); @@ -605,7 +605,7 @@ public void storeClient() throws URISyntaxException { AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).toBlocking().value(); assertThat(addressInfo[0]).isEqualTo(addressInformations[0]); - AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.Tcp); + AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.TCP); URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false).toBlocking().value(); // check if the address return from Address Selector matches the original address info @@ -677,12 +677,12 @@ public void globalStrongConsistentWrite() { entity.setResourceId("1-MxAPlgMgA="); // set consistency level on the request to Bounded Staleness - entity.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Strong.toString()); + entity.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.STRONG.toString()); // also setup timeout helper, used in store reader entity.requestContext.timeoutHelper = new TimeoutHelper(Duration.ofSeconds(2 * 60 * 60 + 2 * 60 + 2)); - // when the store reader throws Invalid Partition exception, the higher layer should + // when the store reader throws INVALID Partition exception, the higher layer should // clear this target identity. entity.requestContext.resolvedPartitionKeyRange = new PartitionKeyRange(); @@ -693,7 +693,7 @@ public void globalStrongConsistentWrite() { AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).toBlocking().value(); assertThat(addressInformations[0]).isEqualTo(addressInfo[0]); - AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.Tcp); + AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.TCP); URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false).toBlocking().value(); // check if the address return from Address Selector matches the original address info @@ -763,12 +763,12 @@ public void globalStrongConsistency() { entity.setResourceId("1-MxAPlgMgA="); // set consistency level on the request to Bounded Staleness - entity.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.BoundedStaleness.toString()); + entity.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.BOUNDED_STALENESS.toString()); // also setup timeout helper, used in store reader entity.requestContext.timeoutHelper = new TimeoutHelper(Duration.ofSeconds(2 * 60 * 60 + 2 * 60 + 2)); - // when the store reader throws Invalid Partition exception, the higher layer should + // when the store reader throws INVALID Partition exception, the higher layer should // clear this target identity. entity.requestContext.resolvedPartitionKeyRange = new PartitionKeyRange(); @@ -779,7 +779,7 @@ public void globalStrongConsistency() { AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).toBlocking().value(); assertThat(addressInfo[0]).isEqualTo(addressInformations[0]); - AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.Tcp); + AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.TCP); URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false).toBlocking().value(); // check if the address return from Address Selector matches the original address info @@ -807,7 +807,7 @@ public void globalStrongConsistency() { QuorumReader reader = new QuorumReader(new Configs(),mockTransportClient, addressSelector, storeReader, mockServiceConfigReader, mockAuthorizationTokenProvider); - entity.requestContext.originalRequestConsistencyLevel = ConsistencyLevel.Strong; + entity.requestContext.originalRequestConsistencyLevel = ConsistencyLevel.STRONG; StoreResponse result = reader.readStrongAsync(entity, 2, ReadMode.Strong).toBlocking().value(); assertThat(result.getLSN()).isEqualTo(100); @@ -839,10 +839,10 @@ public void globalStrongConsistency() { GatewayServiceConfigurationReader mockServiceConfigReader = Mockito.mock(GatewayServiceConfigurationReader.class); Mockito.when(mockServiceConfigReader.getUserReplicationPolicy()).thenReturn(replicationPolicy); - Mockito.when(mockServiceConfigReader.getDefaultConsistencyLevel()).thenReturn(ConsistencyLevel.Strong); + Mockito.when(mockServiceConfigReader.getDefaultConsistencyLevel()).thenReturn(ConsistencyLevel.STRONG); QuorumReader reader = new QuorumReader(new Configs(), mockTransportClient, addressSelector, storeReader, mockServiceConfigReader, mockAuthorizationTokenProvider); - entity.requestContext.originalRequestConsistencyLevel = ConsistencyLevel.Strong; + entity.requestContext.originalRequestConsistencyLevel = ConsistencyLevel.STRONG; entity.requestContext.quorumSelectedLSN = -1; entity.requestContext.globalCommittedSelectedLSN = -1; try { @@ -881,10 +881,10 @@ public void globalStrongConsistency() { GatewayServiceConfigurationReader mockServiceConfigReader = Mockito.mock(GatewayServiceConfigurationReader.class); Mockito.when(mockServiceConfigReader.getUserReplicationPolicy()).thenReturn(replicationPolicy); - Mockito.when(mockServiceConfigReader.getDefaultConsistencyLevel()).thenReturn(ConsistencyLevel.Strong); + Mockito.when(mockServiceConfigReader.getDefaultConsistencyLevel()).thenReturn(ConsistencyLevel.STRONG); QuorumReader reader = new QuorumReader(new Configs(), mockTransportClient, addressSelector, storeReader, mockServiceConfigReader, mockAuthorizationTokenProvider); - entity.requestContext.originalRequestConsistencyLevel = ConsistencyLevel.Strong; + entity.requestContext.originalRequestConsistencyLevel = ConsistencyLevel.STRONG; entity.requestContext.performLocalRefreshOnGoneException = true; StoreResponse result = reader.readStrongAsync(entity, 2, ReadMode.Strong).toBlocking().value(); diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java similarity index 91% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreReaderTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java index 7ed77154118c1..9010e80abde8b 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java @@ -21,26 +21,26 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.ISessionToken; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.VectorSessionToken; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.internal.DocumentServiceRequestContext; -import com.microsoft.azure.cosmosdb.rx.internal.NotFoundException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionIsMigratingException; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionKeyRangeIsSplittingException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ISessionToken; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.VectorSessionToken; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.DocumentServiceRequestContext; +import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.PartitionIsMigratingException; +import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; import org.assertj.core.api.AssertionsForClassTypes; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; @@ -57,10 +57,10 @@ import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.StatusCodes.GONE; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.SubStatusCodes.COMPLETING_PARTITION_MIGRATION; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.SubStatusCodes.COMPLETING_SPLIT; -import static com.microsoft.azure.cosmosdb.internal.HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE; +import static com.azure.data.cosmos.internal.HttpConstants.StatusCodes.GONE; +import static com.azure.data.cosmos.internal.HttpConstants.SubStatusCodes.COMPLETING_PARTITION_MIGRATION; +import static com.azure.data.cosmos.internal.HttpConstants.SubStatusCodes.COMPLETING_SPLIT; +import static com.azure.data.cosmos.internal.HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE; import static org.assertj.core.api.Assertions.assertThat; public class StoreReaderTest { @@ -130,11 +130,11 @@ public Object[][] verifyCanContinueOnExceptionArgProvider() { } @Test(groups = "unit", dataProvider = "verifyCanContinueOnExceptionArgProvider") - public void verifyCanContinueOnException(DocumentClientException dce, Boolean shouldVerify) { - DocumentClientException capturedFailure = null; + public void verifyCanContinueOnException(CosmosClientException dce, Boolean shouldVerify) { + CosmosClientException capturedFailure = null; try { StoreReader.verifyCanContinueOnException(dce); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { capturedFailure = e; } @@ -206,10 +206,10 @@ public void sessionNotAvailableFromSomeReplicas_FindReplicaSatisfyingRequestedSe long globalCommittedLsn = 651174; String partitionKeyRangeId = "73"; NotFoundException foundException = new NotFoundException(); - foundException.getResponseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + slowReplicaLSN); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(slowReplicaLSN)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(slowReplicaLSN)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); + foundException.responseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + slowReplicaLSN); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(slowReplicaLSN)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(slowReplicaLSN)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); long fasterReplicaLSN = 651176; @@ -247,7 +247,7 @@ public void sessionNotAvailableFromSomeReplicas_FindReplicaSatisfyingRequestedSe TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Session.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); dsr.requestContext.sessionToken = sessionToken.v; @@ -296,10 +296,10 @@ public void sessionRead_LegitimateNotFound() { String partitionKeyRangeId = "73"; NotFoundException foundException = new NotFoundException(); - foundException.getResponseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(lsn)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(lsn)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); + foundException.responseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(lsn)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(lsn)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); TransportClientWrapper transportClientWrapper = new TransportClientWrapper.Builder.ReplicaResponseBuilder .SequentialBuilder() @@ -324,7 +324,7 @@ public void sessionRead_LegitimateNotFound() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Session.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); dsr.requestContext.sessionToken = sessionToken.v; @@ -365,10 +365,10 @@ public void sessionRead_ReplicasDoNotHaveTheRequestedLSN_NoResult() { String partitionKeyRangeId = "73"; NotFoundException foundException = new NotFoundException(); - foundException.getResponseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(lsn)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(lsn)); - foundException.getResponseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); + foundException.responseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LSN, Long.toString(lsn)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(lsn)); + foundException.responseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); TransportClientWrapper transportClientWrapper = new TransportClientWrapper.Builder.ReplicaResponseBuilder .SequentialBuilder() @@ -393,7 +393,7 @@ public void sessionRead_ReplicasDoNotHaveTheRequestedLSN_NoResult() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Session.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); dsr.requestContext.sessionToken = sessionToken.v; @@ -427,10 +427,10 @@ public void requestRateTooLarge_BubbleUp() { String partitionKeyRangeId = "257"; RequestRateTooLargeException requestRateTooLargeException = new RequestRateTooLargeException(); - requestRateTooLargeException.getResponseHeaders().put(HttpConstants.HttpHeaders.LSN, Long.toString(lsn)); - requestRateTooLargeException.getResponseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); - requestRateTooLargeException.getResponseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(lsn)); - requestRateTooLargeException.getResponseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); + requestRateTooLargeException.responseHeaders().put(HttpConstants.HttpHeaders.LSN, Long.toString(lsn)); + requestRateTooLargeException.responseHeaders().put(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, Long.toString(globalCommittedLsn)); + requestRateTooLargeException.responseHeaders().put(WFConstants.BackendHeaders.LOCAL_LSN, Long.toString(lsn)); + requestRateTooLargeException.responseHeaders().put(HttpConstants.HttpHeaders.SESSION_TOKEN, partitionKeyRangeId + ":-1#" + lsn); TransportClientWrapper transportClientWrapper = new TransportClientWrapper.Builder.ReplicaResponseBuilder .SequentialBuilder() @@ -455,7 +455,7 @@ public void requestRateTooLarge_BubbleUp() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.Session.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); dsr.requestContext.sessionToken = sessionToken.v; @@ -639,7 +639,7 @@ public void readPrimaryAsync_RetryOnPrimaryReplicaMove(Exception firstExceptionF request.requestContext.resolvedPartitionKeyRange = partitionKeyRangeWithId("12"); request.requestContext.requestChargeTracker = new RequestChargeTracker(); - AddressSelectorWrapper addressSelectorWrapper = AddressSelectorWrapper.Builder.PrimaryReplicaMoveBuilder.create(Protocol.Https) + AddressSelectorWrapper addressSelectorWrapper = AddressSelectorWrapper.Builder.PrimaryReplicaMoveBuilder.create(Protocol.HTTPS) .withPrimaryReplicaMove(primaryURIPriorToRefresh, primaryURIAfterRefresh).build(); StoreReader storeReader = new StoreReader(transportClientWrapper.transportClient, addressSelectorWrapper.addressSelector, sessionContainer); @@ -673,7 +673,7 @@ public void readPrimaryAsync_RetryOnPrimaryReplicaMove(Exception firstExceptionF @DataProvider(name = "readMultipleReplicasAsyncArgProvider") public Object[][] readMultipleReplicasAsyncArgProvider() { return new Object[][]{ - // boolean includePrimary, int replicaCountToRead, ReadMode.Strong + // boolean includePrimary, int replicaCountToRead, ReadMode.STRONG { false, 3, ReadMode.Strong }, { true, 3, ReadMode.Strong }, { false, 3, ReadMode.Any }, @@ -825,7 +825,7 @@ public static void validateException(Single single, private PartitionKeyRange partitionKeyRangeWithId(String id) { PartitionKeyRange partitionKeyRange = Mockito.mock(PartitionKeyRange.class); - Mockito.doReturn(id).when(partitionKeyRange).getId(); + Mockito.doReturn(id).when(partitionKeyRange).id(); return partitionKeyRange; } } diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreReaderUnderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java similarity index 94% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreReaderUnderTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java index f2953ac71c4e4..aeeef1bf3478e 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreReaderUnderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.tuple.Pair; import rx.Single; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponseValidator.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseValidator.java similarity index 97% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponseValidator.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseValidator.java index 708d2a36b9a30..0d930285adcef 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResponseValidator.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseValidator.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.HttpConstants; import org.assertj.core.api.Condition; import java.util.ArrayList; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResultValidator.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResultValidator.java similarity index 95% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResultValidator.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResultValidator.java index a526001f84ddb..05303ffad5fdc 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/StoreResultValidator.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResultValidator.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.rx.FailureValidator; import java.net.URI; import java.util.ArrayList; @@ -65,7 +65,7 @@ public Builder withStoreResponse(StoreResponseValidator storeResponseValidator) public void validate(StoreResult storeResult) { try { storeResponseValidator.validate(storeResult.toResponse()); - }catch (DocumentClientException e) { + }catch (CosmosClientException e) { fail(e.getMessage()); } } @@ -80,7 +80,7 @@ public Builder withException(FailureValidator failureValidator) { public void validate(StoreResult storeResult) { try { failureValidator.validate(storeResult.getException()); - }catch (DocumentClientException e) { + }catch (CosmosClientException e) { fail(e.getMessage()); } } diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TimeoutHelperTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TimeoutHelperTest.java similarity index 97% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TimeoutHelperTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TimeoutHelperTest.java index 4f0b3105087b6..0435980577842 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TimeoutHelperTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TimeoutHelperTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TransportClientWrapper.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TransportClientWrapper.java similarity index 97% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TransportClientWrapper.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TransportClientWrapper.java index c92b6204b3ecf..ad62c85a2e960 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/TransportClientWrapper.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TransportClientWrapper.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; import org.apache.commons.lang3.tuple.Pair; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/WebExceptionUtilityTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtilityTest.java similarity index 98% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/WebExceptionUtilityTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtilityTest.java index 8d80eece8e9f9..9badc630da439 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/WebExceptionUtilityTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtilityTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import io.netty.channel.ChannelException; import io.netty.channel.ConnectTimeoutException; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryUtilsTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java similarity index 92% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryUtilsTest.java rename to direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java index 606380453abac..20a67b7123e0c 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryUtilsTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.time.Duration; import java.util.concurrent.TimeUnit; @@ -34,14 +34,11 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.internal.Quadruple; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.GoneException; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreResponse; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreResponseBuilder; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreResponseValidator; -import com.microsoft.azure.cosmosdb.rx.internal.IRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.RetryUtils; -import com.microsoft.azure.cosmosdb.rx.internal.IRetryPolicy.ShouldRetryResult; +import com.azure.data.cosmos.directconnectivity.GoneException; +import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.azure.data.cosmos.directconnectivity.StoreResponseBuilder; +import com.azure.data.cosmos.directconnectivity.StoreResponseValidator; +import com.azure.data.cosmos.internal.IRetryPolicy.ShouldRetryResult; import rx.Single; import rx.functions.Func1; diff --git a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternalUtils.java b/direct-impl/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java similarity index 96% rename from direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternalUtils.java rename to direct-impl/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java index b4e9875f6cf80..5751d70a08d51 100644 --- a/direct-impl/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/PartitionKeyInternalUtils.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import com.google.common.collect.ImmutableList; diff --git a/direct-impl/src/test/resources/log4j.properties b/direct-impl/src/test/resources/log4j.properties index 00b89ecf16b75..09c5242466d25 100644 --- a/direct-impl/src/test/resources/log4j.properties +++ b/direct-impl/src/test/resources/log4j.properties @@ -7,7 +7,7 @@ log4j.rootLogger=INFO, A1 log4j.category.io.netty=INFO log4j.category.io.reactivex=INFO -log4j.category.com.microsoft.azure.cosmosdb=INFO +log4j.category.com.azure.data.cosmos=INFO # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender diff --git a/examples/pom.xml b/examples/pom.xml index 8865464255d38..e37d8f347da83 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -69,7 +69,7 @@ exec-maven-plugin 1.2.1 - com.microsoft.azure.cosmosdb.benchmark.Main + com.azure.data.cosmos.benchmark.Main @@ -81,7 +81,7 @@ - com.microsoft.azure.cosmosdb.rx.examples.multimaster.samples.Main + com.azure.data.cosmos.rx.examples.multimaster.samples.Main diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/AccountSettings.java b/examples/src/main/java/com/azure/data/cosmos/examples/AccountSettings.java similarity index 96% rename from examples/src/main/java/com/microsoft/azure/cosmos/examples/AccountSettings.java rename to examples/src/main/java/com/azure/data/cosmos/examples/AccountSettings.java index b3fa7538971d4..11b748b8710c3 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmos/examples/AccountSettings.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/AccountSettings.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmos.examples; +package com.azure.data.cosmos.examples; import org.apache.commons.lang3.StringUtils; @@ -43,7 +43,7 @@ * https://docs.microsoft.com/en-us/azure/cosmos-db/local-emulator-export-ssl-certificates */ public class AccountSettings { - // Replace MASTER_KEY and HOST with values from your Azure Cosmos DB account. + // REPLACE MASTER_KEY and HOST with values from your Azure Cosmos DB account. // The default values are credentials of the local emulator, which are not used in any production environment. public static String MASTER_KEY = System.getProperty("ACCOUNT_KEY", diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java b/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java similarity index 75% rename from examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java rename to examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java index 16e4f9bb963e7..00fd6d45a78ba 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmos/examples/BasicDemo.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java @@ -20,18 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.examples; - -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItemResponse; +package com.azure.data.cosmos.examples; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; @@ -57,7 +52,7 @@ private void start(){ .key(AccountSettings.MASTER_KEY) .build(); - //Create a database and a container + //CREATE a database and a container createDbAndContainerBlocking(); //Get a proxy reference to container @@ -67,16 +62,16 @@ private void start(){ TestObject testObject = new TestObject("item_new_id_1", "test", "test description", "US"); TestObject testObject2 = new TestObject("item_new_id_2", "test2", "test description2", "CA"); - //Create an Item async + //CREATE an Item async Mono itemResponseMono = container.createItem(testObject, testObject.country); - //Create another Item async + //CREATE another Item async Mono itemResponseMono1 = container.createItem(testObject2, testObject2.country); //Wait for completion try { - itemResponseMono.doOnError(throwable -> log("Create item 1", throwable)) + itemResponseMono.doOnError(throwable -> log("CREATE item 1", throwable)) .mergeWith(itemResponseMono1) - .doOnError(throwable -> log("Create item 2 ", throwable)) + .doOnError(throwable -> log("CREATE item 2 ", throwable)) .doOnComplete(() -> log("Items created")) .publishOn(Schedulers.elastic()) .blockLast(); @@ -98,29 +93,29 @@ private void start(){ private void createAndReplaceItem() { TestObject replaceObject = new TestObject("item_new_id_3", "test3", "test description3", "JP"); CosmosItem cosmosItem = null; - //Create item sync + //CREATE item sync try { cosmosItem = container.createItem(replaceObject, replaceObject.country) - .doOnError(throwable -> log("Create 3", throwable)) + .doOnError(throwable -> log("CREATE 3", throwable)) .publishOn(Schedulers.elastic()) .block() - .getItem(); + .item(); }catch (RuntimeException e){ log("Couldn't create items due to above exceptions"); } if(cosmosItem != null) { replaceObject.setName("new name test3"); - //Replace the item and wait for completion + //REPLACE the item and wait for completion cosmosItem.replace(replaceObject).block(); } } private void createDbAndContainerBlocking() { client.createDatabaseIfNotExists(DATABASE_NAME) - .doOnSuccess(cosmosDatabaseResponse -> log("Database: " + cosmosDatabaseResponse.getDatabase().getId())) - .flatMap(dbResponse -> dbResponse.getDatabase().createContainerIfNotExists(new CosmosContainerSettings(CONTAINER_NAME, "/country"))) - .doOnSuccess(cosmosContainerResponse -> log("Container: " + cosmosContainerResponse.getContainer().getId())) + .doOnSuccess(cosmosDatabaseResponse -> log("Database: " + cosmosDatabaseResponse.database().id())) + .flatMap(dbResponse -> dbResponse.database().createContainerIfNotExists(new CosmosContainerSettings(CONTAINER_NAME, "/country"))) + .doOnSuccess(cosmosContainerResponse -> log("Container: " + cosmosContainerResponse.container().id())) .doOnError(throwable -> log(throwable.getMessage())) .publishOn(Schedulers.elastic()) .block(); @@ -131,9 +126,9 @@ private void queryItems(){ log("+ Querying the collection "); String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setMaxDegreeOfParallelism(2); - Flux> queryFlux = container.queryItems(query, options); + options.enableCrossPartitionQuery(true); + options.maxDegreeOfParallelism(2); + Flux> queryFlux = container.queryItems(query, options); queryFlux.publishOn(Schedulers.elastic()).subscribe(cosmosItemFeedResponse -> {}, throwable -> {}, @@ -143,7 +138,7 @@ private void queryItems(){ .toIterable() .forEach(cosmosItemFeedResponse -> { - log(cosmosItemFeedResponse.getResults()); + log(cosmosItemFeedResponse.results()); }); } @@ -152,17 +147,17 @@ private void queryWithContinuationToken(){ log("+ Query with paging using continuation token"); String query = "SELECT * from root r "; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setPopulateQueryMetrics(true); - options.setMaxItemCount(1); + options.enableCrossPartitionQuery(true); + options.populateQueryMetrics(true); + options.maxItemCount(1); String continuation = null; do{ - options.setRequestContinuation(continuation); - Flux> queryFlux = container.queryItems(query, options); - FeedResponse page = queryFlux.blockFirst(); + options.requestContinuation(continuation); + Flux> queryFlux = container.queryItems(query, options); + FeedResponse page = queryFlux.blockFirst(); assert page != null; - log(page.getResults()); - continuation = page.getResponseContinuation(); + log(page.results()); + continuation = page.continuationToken(); }while(continuation!= null); } @@ -172,7 +167,7 @@ private void log(Object object) { } private void log(String msg, Throwable throwable){ - log(msg + ": " + ((DocumentClientException)throwable).getStatusCode()); + log(msg + ": " + ((CosmosClientException)throwable).statusCode()); } class TestObject { diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java similarity index 80% rename from examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java rename to examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java index a3a8da69dc194..d483bad06208f 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java @@ -20,20 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.examples.ChangeFeed; - -import com.microsoft.azure.cosmos.ChangeFeedProcessor; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerResponse; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.SerializationFormattingPolicy; +package com.azure.data.cosmos.examples.ChangeFeed; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.SerializationFormattingPolicy; import org.apache.commons.lang3.RandomStringUtils; import reactor.core.publisher.Mono; @@ -57,16 +51,16 @@ public static void main (String[]args) { try { - System.out.println("-->Create DocumentClient"); + System.out.println("-->CREATE DocumentClient"); CosmosClient client = getCosmosClient(); - System.out.println("-->Create sample's database: " + DATABASE_NAME); + System.out.println("-->CREATE sample's database: " + DATABASE_NAME); CosmosDatabase cosmosDatabase = createNewDatabase(client, DATABASE_NAME); - System.out.println("-->Create container for documents: " + COLLECTION_NAME); + System.out.println("-->CREATE container for documents: " + COLLECTION_NAME); CosmosContainer feedContainer = createNewCollection(client, DATABASE_NAME, COLLECTION_NAME); - System.out.println("-->Create container for lease: " + COLLECTION_NAME + "-leases"); + System.out.println("-->CREATE container for lease: " + COLLECTION_NAME + "-leases"); CosmosContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases"); Mono changeFeedProcessor1 = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); @@ -93,7 +87,7 @@ public static void main (String[]args) { throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time"); } - System.out.println("-->Delete sample's database: " + DATABASE_NAME); + System.out.println("-->DELETE sample's database: " + DATABASE_NAME); deleteDatabase(cosmosDatabase); Thread.sleep(15000); @@ -120,13 +114,13 @@ public static CosmosClient getCosmosClient() { return CosmosClient.builder() .endpoint(SampleConfigurations.HOST) .key(SampleConfigurations.MASTER_KEY) - .connectionPolicy(ConnectionPolicy.GetDefault()) - .consistencyLevel(ConsistencyLevel.Eventual) + .connectionPolicy(ConnectionPolicy.defaultPolicy()) + .consistencyLevel(ConsistencyLevel.EVENTUAL) .build(); } public static CosmosDatabase createNewDatabase(CosmosClient client, String databaseName) { - return client.createDatabaseIfNotExists(databaseName).block().getDatabase(); + return client.createDatabaseIfNotExists(databaseName).block().database(); } public static void deleteDatabase(CosmosDatabase cosmosDatabase) { @@ -145,10 +139,10 @@ public static CosmosContainer createNewCollection(CosmosClient client, String da throw new IllegalArgumentException(String.format("Collection %s already exists in database %s.", collectionName, databaseName)); } } catch (RuntimeException ex) { - if (ex.getCause() instanceof DocumentClientException) { - DocumentClientException documentClientException = (DocumentClientException) ex.getCause(); + if (ex.getCause() instanceof CosmosClientException) { + CosmosClientException cosmosClientException = (CosmosClientException) ex.getCause(); - if (documentClientException.getStatusCode() != 404) { + if (cosmosClientException.statusCode() != 404) { throw ex; } } else { @@ -167,7 +161,7 @@ public static CosmosContainer createNewCollection(CosmosClient client, String da throw new RuntimeException(String.format("Failed to create collection %s in database %s.", collectionName, databaseName)); } - return containerResponse.getContainer(); + return containerResponse.container(); } public static CosmosContainer createNewLeaseCollection(CosmosClient client, String databaseName, String leaseCollectionName) { @@ -188,10 +182,10 @@ public static CosmosContainer createNewLeaseCollection(CosmosClient client, Stri } } } catch (RuntimeException ex) { - if (ex.getCause() instanceof DocumentClientException) { - DocumentClientException documentClientException = (DocumentClientException) ex.getCause(); + if (ex.getCause() instanceof CosmosClientException) { + CosmosClientException cosmosClientException = (CosmosClientException) ex.getCause(); - if (documentClientException.getStatusCode() != 404) { + if (cosmosClientException.statusCode() != 404) { throw ex; } } else { @@ -209,17 +203,17 @@ public static CosmosContainer createNewLeaseCollection(CosmosClient client, Stri throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName)); } - return leaseContainerResponse.getContainer(); + return leaseContainerResponse.container(); } public static void createNewDocuments(CosmosContainer containerClient, int count, Duration delay) { String suffix = RandomStringUtils.randomAlphabetic(10); for (int i = 0; i <= count; i++) { - CosmosItemSettings document = new CosmosItemSettings(); - document.setId(String.format("0%d-%s", i, suffix)); + CosmosItemProperties document = new CosmosItemProperties(); + document.id(String.format("0%d-%s", i, suffix)); containerClient.createItem(document).subscribe(doc -> { - System.out.println("---->DOCUMENT WRITE: " + doc.getCosmosItemSettings().toJson(SerializationFormattingPolicy.Indented)); + System.out.println("---->DOCUMENT WRITE: " + doc.properties().toJson(SerializationFormattingPolicy.INDENTED)); }); long remainingWork = delay.toMillis(); diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleConfigurations.java b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleConfigurations.java similarity index 95% rename from examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleConfigurations.java rename to examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleConfigurations.java index f55b3be2cd41c..9657dc22363ee 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleConfigurations.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleConfigurations.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.examples.ChangeFeed; +package com.azure.data.cosmos.examples.ChangeFeed; import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; @@ -39,7 +39,7 @@ * If none of the above is set, emulator endpoint will be used. */ public final class SampleConfigurations { - // Replace MASTER_KEY and HOST with values from your Azure Cosmos DB account. + // REPLACE MASTER_KEY and HOST with values from your Azure Cosmos DB account. // The default values are credentials of the local emulator, which are not used in any production environment. // public static String MASTER_KEY = diff --git a/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleObserverImpl.java b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java similarity index 78% rename from examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleObserverImpl.java rename to examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java index 137e07af94225..269d75153181d 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmos/examples/ChangeFeed/SampleObserverImpl.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java @@ -20,14 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.examples.ChangeFeed; +package com.azure.data.cosmos.examples.ChangeFeed; -import com.microsoft.azure.cosmos.ChangeFeedObserver; -import com.microsoft.azure.cosmos.ChangeFeedObserverCloseReason; -import com.microsoft.azure.cosmos.ChangeFeedObserverContext; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.SerializationFormattingPolicy; +import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.ChangeFeedObserverCloseReason; +import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.SerializationFormattingPolicy; import java.util.List; @@ -46,11 +46,11 @@ public void close(ChangeFeedObserverContext context, ChangeFeedObserverCloseReas } @Override - public void processChanges(ChangeFeedObserverContext context, List docs) { + public void processChanges(ChangeFeedObserverContext context, List docs) { System.out.println("--->SampleObserverImpl::processChanges() START"); - for (CosmosItemSettings document : docs) { - System.out.println("---->DOCUMENT RECEIVED: " + document.toJson(SerializationFormattingPolicy.Indented)); + for (CosmosItemProperties document : docs) { + System.out.println("---->DOCUMENT RECEIVED: " + document.toJson(SerializationFormattingPolicy.INDENTED)); } System.out.println("--->SampleObserverImpl::processChanges() END"); } diff --git a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/ConfigurationManager.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/ConfigurationManager.java similarity index 95% rename from examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/ConfigurationManager.java rename to examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/ConfigurationManager.java index a09f58c3da257..4651739076c90 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/ConfigurationManager.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/ConfigurationManager.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples.multimaster; +package com.azure.data.cosmos.rx.examples.multimaster; import java.util.Properties; diff --git a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/Helpers.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java similarity index 75% rename from examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/Helpers.java rename to examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java index 389faee55a6ee..27d275f03ba29 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/Helpers.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples.multimaster; +package com.azure.data.cosmos.rx.examples.multimaster; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.AsyncDocumentClient; import rx.Observable; import rx.Single; @@ -46,13 +46,13 @@ static public Single createDatabaseIfNotExists(AsyncDocumentClient cli return client.readDatabase("/dbs/" + databaseName, null) .onErrorResumeNext( e -> { - if (e instanceof DocumentClientException) { - DocumentClientException dce = (DocumentClientException) e; - if (dce.getStatusCode() == 404) { + if (e instanceof CosmosClientException) { + CosmosClientException dce = (CosmosClientException) e; + if (dce.statusCode() == 404) { // if doesn't exist create it Database d = new Database(); - d.setId(databaseName); + d.id(databaseName); return client.createDatabase(d, null); } @@ -67,13 +67,13 @@ static public Single createCollectionIfNotExists(AsyncDocume return client.readCollection(createDocumentCollectionUri(databaseName, collectionName), null) .onErrorResumeNext( e -> { - if (e instanceof DocumentClientException) { - DocumentClientException dce = (DocumentClientException) e; - if (dce.getStatusCode() == 404) { + if (e instanceof CosmosClientException) { + CosmosClientException dce = (CosmosClientException) e; + if (dce.statusCode() == 404) { // if doesn't exist create it DocumentCollection collection = new DocumentCollection(); - collection.setId(collectionName); + collection.id(collectionName); return client.createCollection(createDatabaseUri(databaseName), collection, null); } @@ -85,12 +85,12 @@ static public Single createCollectionIfNotExists(AsyncDocume } static public Single createCollectionIfNotExists(AsyncDocumentClient client, String databaseName, DocumentCollection collection) { - return client.readCollection(createDocumentCollectionUri(databaseName, collection.getId()), null) + return client.readCollection(createDocumentCollectionUri(databaseName, collection.id()), null) .onErrorResumeNext( e -> { - if (e instanceof DocumentClientException) { - DocumentClientException dce = (DocumentClientException) e; - if (dce.getStatusCode() == 404) { + if (e instanceof CosmosClientException) { + CosmosClientException dce = (CosmosClientException) e; + if (dce.statusCode() == 404) { // if doesn't exist create it return client.createCollection(createDatabaseUri(databaseName), collection, null); diff --git a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/ConflictWorker.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java similarity index 86% rename from examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/ConflictWorker.java rename to examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java index 6f6f4548f7f0c..9af8773ae8381 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/ConflictWorker.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java @@ -21,23 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples.multimaster.samples; - -import com.microsoft.azure.cosmosdb.AccessCondition; -import com.microsoft.azure.cosmosdb.AccessConditionType; -import com.microsoft.azure.cosmosdb.Conflict; -import com.microsoft.azure.cosmosdb.ConflictResolutionMode; -import com.microsoft.azure.cosmosdb.ConflictResolutionPolicy; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.examples.multimaster.Helpers; +package com.azure.data.cosmos.rx.examples.multimaster.samples; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.rx.examples.multimaster.Helpers; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -103,7 +90,7 @@ private DocumentCollection createCollectionIfNotExists(AsyncDocumentClient creat private DocumentCollection getCollectionDefForManual(String id) { DocumentCollection collection = new DocumentCollection(); - collection.setId(id); + collection.id(id); ConflictResolutionPolicy policy = ConflictResolutionPolicy.createCustomPolicy(); collection.setConflictResolutionPolicy(policy); return collection; @@ -111,7 +98,7 @@ private DocumentCollection getCollectionDefForManual(String id) { private DocumentCollection getCollectionDefForLastWinWrites(String id, String conflictResolutionPath) { DocumentCollection collection = new DocumentCollection(); - collection.setId(id); + collection.id(id); ConflictResolutionPolicy policy = ConflictResolutionPolicy.createLastWriterWinsPolicy(conflictResolutionPath); collection.setConflictResolutionPolicy(policy); return collection; @@ -119,7 +106,7 @@ private DocumentCollection getCollectionDefForLastWinWrites(String id, String co private DocumentCollection getCollectionDefForCustom(String id, String storedProc) { DocumentCollection collection = new DocumentCollection(); - collection.setId(id); + collection.id(id); ConflictResolutionPolicy policy = ConflictResolutionPolicy.createCustomPolicy(storedProc); collection.setConflictResolutionPolicy(policy); return collection; @@ -143,7 +130,7 @@ public void initialize() throws Exception { String.format("dbs/%s/colls/%s/sprocs/%s", this.databaseName, this.udpCollectionName, "resolver"))); StoredProcedure lwwSproc = new StoredProcedure(); - lwwSproc.setId("resolver"); + lwwSproc.id("resolver"); lwwSproc.setBody(IOUtils.toString( getClass().getClassLoader().getResourceAsStream("resolver-storedproc.txt"), "UTF-8")); @@ -161,10 +148,10 @@ public void runManualConflict() throws Exception { logger.info("\r\nInsert Conflict\r\n"); this.runInsertConflictOnManual(); - logger.info("\r\nUpdate Conflict\r\n"); + logger.info("\r\nUPDATE Conflict\r\n"); this.runUpdateConflictOnManual(); - logger.info("\r\nDelete Conflict\r\n"); + logger.info("\r\nDELETE Conflict\r\n"); this.runDeleteConflictOnManual(); } @@ -172,10 +159,10 @@ public void runLWWConflict() throws Exception { logger.info("\r\nInsert Conflict\r\n"); this.runInsertConflictOnLWW(); - logger.info("\r\nUpdate Conflict\r\n"); + logger.info("\r\nUPDATE Conflict\r\n"); this.runUpdateConflictOnLWW(); - logger.info("\r\nDelete Conflict\r\n"); + logger.info("\r\nDELETE Conflict\r\n"); this.runDeleteConflictOnLWW(); } @@ -183,10 +170,10 @@ public void runUDPConflict() throws Exception { logger.info("\r\nInsert Conflict\r\n"); this.runInsertConflictOnUdp(); - logger.info("\r\nUpdate Conflict\r\n"); + logger.info("\r\nUPDATE Conflict\r\n"); this.runUpdateConflictOnUdp(); - logger.info("\r\nDelete Conflict\r\n"); + logger.info("\r\nDELETE Conflict\r\n"); this.runDeleteConflictOnUdp(); } @@ -197,7 +184,7 @@ public void runInsertConflictOnManual() throws Exception { ArrayList> insertTask = new ArrayList>(); Document conflictDocument = new Document(); - conflictDocument.setId(UUID.randomUUID().toString()); + conflictDocument.id(UUID.randomUUID().toString()); int index = 0; for (AsyncDocumentClient client : this.clients) { @@ -222,7 +209,7 @@ public void runInsertConflictOnManual() throws Exception { public void runUpdateConflictOnManual() throws Exception { do { Document conflictDocument = new Document(); - conflictDocument.setId(UUID.randomUUID().toString()); + conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.manualCollectionUri, conflictDocument, 0) @@ -258,7 +245,7 @@ public void runUpdateConflictOnManual() throws Exception { public void runDeleteConflictOnManual() throws Exception { do { Document conflictDocument = new Document(); - conflictDocument.setId(UUID.randomUUID().toString()); + conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.manualCollectionUri, conflictDocument, 0) .firstOrDefault(null).toBlocking().first(); @@ -299,7 +286,7 @@ public void runInsertConflictOnLWW() throws Exception { ArrayList> insertTask = new ArrayList>(); Document conflictDocument = new Document(); - conflictDocument.setId(UUID.randomUUID().toString()); + conflictDocument.id(UUID.randomUUID().toString()); int index = 0; for (AsyncDocumentClient client : this.clients) { @@ -324,7 +311,7 @@ public void runInsertConflictOnLWW() throws Exception { public void runUpdateConflictOnLWW() throws Exception { do { Document conflictDocument = new Document(); - conflictDocument.setId(UUID.randomUUID().toString()); + conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.lwwCollectionUri, conflictDocument, 0) .firstOrDefault(null).toBlocking().first(); @@ -359,7 +346,7 @@ public void runUpdateConflictOnLWW() throws Exception { public void runDeleteConflictOnLWW() throws Exception { do { Document conflictDocument = new Document(); - conflictDocument.setId(UUID.randomUUID().toString()); + conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.lwwCollectionUri, conflictDocument, 0) .firstOrDefault(null).toBlocking().first(); @@ -386,7 +373,7 @@ public void runDeleteConflictOnLWW() throws Exception { if (conflictDocuments.size() > 1) { logger.info("Inserted {} conflicts, verifying conflict resolution", conflictDocuments.size()); - //Delete should always win. irrespective of LWW. + //DELETE should always win. irrespective of LWW. this.validateLWW(this.clients, conflictDocuments, true); break; } else { @@ -402,7 +389,7 @@ public void runInsertConflictOnUdp() throws Exception { ArrayList> insertTask = new ArrayList>(); Document conflictDocument = new Document(); - conflictDocument.setId(UUID.randomUUID().toString()); + conflictDocument.id(UUID.randomUUID().toString()); int index = 0; for (AsyncDocumentClient client : this.clients) { @@ -427,7 +414,7 @@ public void runInsertConflictOnUdp() throws Exception { public void runUpdateConflictOnUdp() throws Exception { do { Document conflictDocument = new Document(); - conflictDocument.setId(UUID.randomUUID().toString()); + conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.udpCollectionUri, conflictDocument, 0) .firstOrDefault(null).toBlocking().first(); @@ -461,7 +448,7 @@ public void runUpdateConflictOnUdp() throws Exception { public void runDeleteConflictOnUdp() throws Exception { do { Document conflictDocument = new Document(); - conflictDocument.setId(UUID.randomUUID().toString()); + conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.udpCollectionUri, conflictDocument, 0) .firstOrDefault(null).toBlocking().first(); @@ -487,7 +474,7 @@ public void runDeleteConflictOnUdp() throws Exception { if (conflictDocuments.size() > 1) { logger.info("2) Caused {} delete conflicts, verifying conflict resolution", conflictDocuments.size()); - //Delete should always win. irrespective of LWW. + //DELETE should always win. irrespective of LWW. this.validateUDPAsync(this.clients, conflictDocuments, true); break; } else { @@ -512,9 +499,9 @@ private Observable tryInsertDocument(AsyncDocumentClient client, Strin } private boolean hasDocumentClientException(Throwable e, int statusCode) { - if (e instanceof DocumentClientException) { - DocumentClientException dce = (DocumentClientException) e; - return dce.getStatusCode() == statusCode; + if (e instanceof CosmosClientException) { + CosmosClientException dce = (CosmosClientException) e; + return dce.statusCode() == statusCode; } return false; @@ -522,7 +509,7 @@ private boolean hasDocumentClientException(Throwable e, int statusCode) { private boolean hasDocumentClientExceptionCause(Throwable e) { while (e != null) { - if (e instanceof DocumentClientException) { + if (e instanceof CosmosClientException) { return true; } @@ -533,9 +520,9 @@ private boolean hasDocumentClientExceptionCause(Throwable e) { private boolean hasDocumentClientExceptionCause(Throwable e, int statusCode) { while (e != null) { - if (e instanceof DocumentClientException) { - DocumentClientException dce = (DocumentClientException) e; - return dce.getStatusCode() == statusCode; + if (e instanceof CosmosClientException) { + CosmosClientException dce = (CosmosClientException) e; + return dce.statusCode() == statusCode; } e = e.getCause(); @@ -550,11 +537,11 @@ private Observable tryUpdateDocument(AsyncDocumentClient client, Strin RequestOptions options = new RequestOptions(); options.setAccessCondition(new AccessCondition()); - options.getAccessCondition().setType(AccessConditionType.IfMatch); - options.getAccessCondition().setCondition(document.getETag()); + options.getAccessCondition().type(AccessConditionType.IF_MATCH); + options.getAccessCondition().condition(document.etag()); - return client.replaceDocument(document.getSelfLink(), document, null).onErrorResumeNext(e -> { + return client.replaceDocument(document.selfLink(), document, null).onErrorResumeNext(e -> { // pre condition failed if (hasDocumentClientException(e, 412)) { @@ -572,11 +559,11 @@ private Observable tryDeleteDocument(AsyncDocumentClient client, Strin RequestOptions options = new RequestOptions(); options.setAccessCondition(new AccessCondition()); - options.getAccessCondition().setType(AccessConditionType.IfMatch); - options.getAccessCondition().setCondition(document.getETag()); + options.getAccessCondition().type(AccessConditionType.IF_MATCH); + options.getAccessCondition().condition(document.etag()); - return client.deleteDocument(document.getSelfLink(), options).onErrorResumeNext(e -> { + return client.deleteDocument(document.selfLink(), options).onErrorResumeNext(e -> { // pre condition failed if (hasDocumentClientException(e, 412)) { @@ -613,21 +600,21 @@ private boolean validateManualConflict(AsyncDocumentClient client, Document conf FeedResponse response = client.readConflicts(this.manualCollectionUri, null) .first().toBlocking().single(); - for (Conflict conflict : response.getResults()) { + for (Conflict conflict : response.results()) { if (!isDelete(conflict)) { Document conflictDocumentContent = conflict.getResource(Document.class); - if (equals(conflictDocument.getId(), conflictDocumentContent.getId())) { - if (equals(conflictDocument.getResourceId(), conflictDocumentContent.getResourceId()) && - equals(conflictDocument.getETag(), conflictDocumentContent.getETag())) { + if (equals(conflictDocument.id(), conflictDocumentContent.id())) { + if (equals(conflictDocument.resourceId(), conflictDocumentContent.resourceId()) && + equals(conflictDocument.etag(), conflictDocumentContent.etag())) { logger.info("Document from Region {} lost conflict @ {}", - conflictDocument.getId(), + conflictDocument.id(), conflictDocument.getInt("regionId"), client.getReadEndpoint()); return true; } else { try { //Checking whether this is the winner. - Document winnerDocument = client.readDocument(conflictDocument.getSelfLink(), null) + Document winnerDocument = client.readDocument(conflictDocument.selfLink(), null) .toBlocking().single().getResource(); logger.info("Document from region {} won the conflict @ {}", conflictDocument.getInt("regionId"), @@ -647,8 +634,8 @@ private boolean validateManualConflict(AsyncDocumentClient client, Document conf } } } else { - if (equals(conflict.getSourceResourceId(), conflictDocument.getResourceId())) { - logger.info("Delete conflict found @ {}", + if (equals(conflict.getSourceResourceId(), conflictDocument.resourceId())) { + logger.info("DELETE conflict found @ {}", client.getReadEndpoint()); return false; } @@ -656,7 +643,7 @@ private boolean validateManualConflict(AsyncDocumentClient client, Document conf } logger.error("Document {} is not found in conflict feed @ {}, retrying", - conflictDocument.getId(), + conflictDocument.id(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); @@ -668,23 +655,23 @@ private void deleteConflict(Document conflictDocument) { FeedResponse conflicts = delClient.readConflicts(this.manualCollectionUri, null).first().toBlocking().single(); - for (Conflict conflict : conflicts.getResults()) { + for (Conflict conflict : conflicts.results()) { if (!isDelete(conflict)) { Document conflictContent = conflict.getResource(Document.class); - if (equals(conflictContent.getResourceId(), conflictDocument.getResourceId()) - && equals(conflictContent.getETag(), conflictDocument.getETag())) { + if (equals(conflictContent.resourceId(), conflictDocument.resourceId()) + && equals(conflictContent.etag(), conflictDocument.etag())) { logger.info("Deleting manual conflict {} from region {}", conflict.getSourceResourceId(), conflictContent.getInt("regionId")); - delClient.deleteConflict(conflict.getSelfLink(), null) + delClient.deleteConflict(conflict.selfLink(), null) .toBlocking().single(); } - } else if (equals(conflict.getSourceResourceId(), conflictDocument.getResourceId())) { + } else if (equals(conflict.getSourceResourceId(), conflictDocument.resourceId())) { logger.info("Deleting manual conflict {} from region {}", conflict.getSourceResourceId(), conflictDocument.getInt("regionId")); - delClient.deleteConflict(conflict.getSelfLink(), null) + delClient.deleteConflict(conflict.selfLink(), null) .toBlocking().single(); } } @@ -705,18 +692,18 @@ private void validateLWW(AsyncDocumentClient client, List conflictDocu FeedResponse response = client.readConflicts(this.lwwCollectionUri, null) .first().toBlocking().single(); - if (response.getResults().size() != 0) { - logger.error("Found {} conflicts in the lww collection", response.getResults().size()); + if (response.results().size() != 0) { + logger.error("Found {} conflicts in the lww collection", response.results().size()); return; } if (hasDeleteConflict) { do { try { - client.readDocument(conflictDocument.get(0).getSelfLink(), null).toBlocking().single(); + client.readDocument(conflictDocument.get(0).selfLink(), null).toBlocking().single(); - logger.error("Delete conflict for document {} didnt win @ {}", - conflictDocument.get(0).getId(), + logger.error("DELETE conflict for document {} didnt win @ {}", + conflictDocument.get(0).id(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); @@ -728,11 +715,11 @@ private void validateLWW(AsyncDocumentClient client, List conflictDocu // NotFound if (hasDocumentClientExceptionCause(exception, 404)) { - logger.info("Delete conflict won @ {}", client.getReadEndpoint()); + logger.info("DELETE conflict won @ {}", client.getReadEndpoint()); return; } else { - logger.error("Delete conflict for document {} didnt win @ {}", - conflictDocument.get(0).getId(), + logger.error("DELETE conflict for document {} didnt win @ {}", + conflictDocument.get(0).id(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); @@ -755,7 +742,7 @@ private void validateLWW(AsyncDocumentClient client, List conflictDocu while (true) { try { - Document existingDocument = client.readDocument(winnerDocument.getSelfLink(), null) + Document existingDocument = client.readDocument(winnerDocument.selfLink(), null) .toBlocking().single().getResource(); if (existingDocument.getInt("regionId") == winnerDocument.getInt("regionId")) { @@ -795,8 +782,8 @@ private String documentNameLink(String collectionId, String documentId) { private void validateUDPAsync(AsyncDocumentClient client, List conflictDocument, boolean hasDeleteConflict) throws Exception { FeedResponse response = client.readConflicts(this.udpCollectionUri, null).first().toBlocking().single(); - if (response.getResults().size() != 0) { - logger.error("Found {} conflicts in the udp collection", response.getResults().size()); + if (response.results().size() != 0) { + logger.error("Found {} conflicts in the udp collection", response.results().size()); return; } @@ -804,22 +791,22 @@ private void validateUDPAsync(AsyncDocumentClient client, List conflic do { try { client.readDocument( - documentNameLink(udpCollectionName, conflictDocument.get(0).getId()), null) + documentNameLink(udpCollectionName, conflictDocument.get(0).id()), null) .toBlocking().single(); - logger.error("Delete conflict for document {} didnt win @ {}", - conflictDocument.get(0).getId(), + logger.error("DELETE conflict for document {} didnt win @ {}", + conflictDocument.get(0).id(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); } catch (Exception exception) { if (hasDocumentClientExceptionCause(exception, 404)) { - logger.info("Delete conflict won @ {}", client.getReadEndpoint()); + logger.info("DELETE conflict won @ {}", client.getReadEndpoint()); return; } else { - logger.error("Delete conflict for document {} didnt win @ {}", - conflictDocument.get(0).getId(), + logger.error("DELETE conflict for document {} didnt win @ {}", + conflictDocument.get(0).id(), client.getReadEndpoint()); TimeUnit.MILLISECONDS.sleep(500); @@ -844,7 +831,7 @@ private void validateUDPAsync(AsyncDocumentClient client, List conflic try { Document existingDocument = client.readDocument( - documentNameLink(udpCollectionName, winnerDocument.getId()), null) + documentNameLink(udpCollectionName, winnerDocument.id()), null) .toBlocking().single().getResource(); if (existingDocument.getInt("regionId") == winnerDocument.getInt( diff --git a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/Main.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Main.java similarity index 94% rename from examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/Main.java rename to examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Main.java index 58f1864a54d33..b05e012dda6b1 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/Main.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Main.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples.multimaster.samples; +package com.azure.data.cosmos.rx.examples.multimaster.samples; -import com.microsoft.azure.cosmosdb.rx.examples.multimaster.ConfigurationManager; +import com.azure.data.cosmos.rx.examples.multimaster.ConfigurationManager; import org.apache.commons.io.IOUtils; import java.io.FileInputStream; diff --git a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/MultiMasterScenario.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java similarity index 93% rename from examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/MultiMasterScenario.java rename to examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java index 5c127de357fca..bb3cdbb1ff70f 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/MultiMasterScenario.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java @@ -21,18 +21,17 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples.multimaster.samples; +package com.azure.data.cosmos.rx.examples.multimaster.samples; import com.google.common.base.Preconditions; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.examples.multimaster.ConfigurationManager; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.rx.examples.multimaster.ConfigurationManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; -import javax.net.ssl.SSLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -72,14 +71,14 @@ public MultiMasterScenario() { for (String region : regions) { ConnectionPolicy policy = new ConnectionPolicy(); - policy.setUsingMultipleWriteLocations(true); - policy.setPreferredLocations(Collections.singletonList(region)); + policy.usingMultipleWriteLocations(true); + policy.preferredLocations(Collections.singletonList(region)); AsyncDocumentClient client = new AsyncDocumentClient.Builder() .withMasterKeyOrResourceToken(this.accountKey) .withServiceEndpoint(this.accountEndpoint) - .withConsistencyLevel(ConsistencyLevel.Eventual) + .withConsistencyLevel(ConsistencyLevel.EVENTUAL) .withConnectionPolicy(policy).build(); diff --git a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/Worker.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java similarity index 80% rename from examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/Worker.java rename to examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java index 90a5ab77aaff2..daf278f43add2 100644 --- a/examples/src/main/java/com/microsoft/azure/cosmosdb/rx/examples/multimaster/samples/Worker.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java @@ -21,14 +21,14 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples.multimaster.samples; +package com.azure.data.cosmos.rx.examples.multimaster.samples; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.rx.*; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; @@ -70,7 +70,7 @@ public Completable runLoopAsync(int documentsToInsert) { long startTick = System.currentTimeMillis(); Document d = new Document(); - d.setId(UUID.randomUUID().toString()); + d.id(UUID.randomUUID().toString()); this.client.createDocument(this.documentCollectionUri, d, null, false) .subscribeOn(schedulerForBlockingWork).toBlocking().single(); @@ -105,13 +105,13 @@ public Completable readAllAsync(int expectedNumberOfDocuments) { do { FeedOptions options = new FeedOptions(); - options.setRequestContinuation(response != null ? response.getResponseContinuation() : null); + options.requestContinuation(response != null ? response.continuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).first() .subscribeOn(schedulerForBlockingWork).toBlocking().single(); - totalItemRead += response.getResults().size(); - } while (response.getResponseContinuation() != null); + totalItemRead += response.results().size(); + } while (response.continuationToken() != null); if (totalItemRead < expectedNumberOfDocuments) { logger.info("Total item read {} from {} is less than {}, retrying reads", @@ -127,7 +127,7 @@ public Completable readAllAsync(int expectedNumberOfDocuments) { } continue; } else { - logger.info("Read {} items from {}", totalItemRead, this.client.getReadEndpoint()); + logger.info("READ {} items from {}", totalItemRead, this.client.getReadEndpoint()); break; } } @@ -142,22 +142,22 @@ void deleteAll() { do { FeedOptions options = new FeedOptions(); - options.setRequestContinuation(response != null ? response.getResponseContinuation() : null); + options.requestContinuation(response != null ? response.continuationToken() : null); response = this.client.readDocuments(this.documentCollectionUri, options).first() .subscribeOn(schedulerForBlockingWork).toBlocking().single(); - documents.addAll(response.getResults()); - } while (response.getResponseContinuation() != null); + documents.addAll(response.results()); + } while (response.continuationToken() != null); for (Document document : documents) { try { - this.client.deleteDocument(document.getSelfLink(), null) + this.client.deleteDocument(document.selfLink(), null) .subscribeOn(schedulerForBlockingWork).toBlocking().single(); } catch (RuntimeException exEx) { - DocumentClientException dce = getDocumentClientExceptionCause(exEx); + CosmosClientException dce = getDocumentClientExceptionCause(exEx); - if (dce.getStatusCode() != 404) { + if (dce.statusCode() != 404) { logger.info("Error occurred while deleting {} from {}", dce, client.getWriteEndpoint()); } } @@ -166,11 +166,11 @@ void deleteAll() { logger.info("Deleted all documents from region {}", this.client.getWriteEndpoint()); } - private DocumentClientException getDocumentClientExceptionCause(Throwable e) { + private CosmosClientException getDocumentClientExceptionCause(Throwable e) { while (e != null) { - if (e instanceof DocumentClientException) { - return (DocumentClientException) e; + if (e instanceof CosmosClientException) { + return (CosmosClientException) e; } e = e.getCause(); diff --git a/examples/src/main/resources/log4j.properties b/examples/src/main/resources/log4j.properties index 00b7fefa64130..a8f16e5dee315 100644 --- a/examples/src/main/resources/log4j.properties +++ b/examples/src/main/resources/log4j.properties @@ -5,12 +5,12 @@ log4j.rootLogger=WARN, A1 log4j.category.io.netty=INFO log4j.category.io.reactivex=INFO -log4j.category.com.microsoft.azure.cosmosdb.rx.examples.multimaster.samples.ConflictWorker=INFO -log4j.category.com.microsoft.azure.cosmosdb.rx.examples.multimaster.samples.Main=INFO -log4j.category.com.microsoft.azure.cosmosdb.rx.examples.multimaster.samples.Worker=INFO -log4j.category.com.microsoft.azure.cosmosdb.rx.examples.multimaster.samples.MultiMasterScenario=INFO -log4j.category.com.microsoft.azure.cosmosdb.rx.examples.multimaster.ConfigurationManager=INFO -log4j.category.com.microsoft.azure.cosmosdb.rx.examples.multimaster.Helpers=INFO +log4j.category.com.azure.data.cosmos.rx.examples.multimaster.samples.ConflictWorker=INFO +log4j.category.com.azure.data.cosmos.rx.examples.multimaster.samples.Main=INFO +log4j.category.com.azure.data.cosmos.rx.examples.multimaster.samples.Worker=INFO +log4j.category.com.azure.data.cosmos.rx.examples.multimaster.samples.MultiMasterScenario=INFO +log4j.category.com.azure.data.cosmos.rx.examples.multimaster.ConfigurationManager=INFO +log4j.category.com.azure.data.cosmos.rx.examples.multimaster.Helpers=INFO # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/CollectionCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java similarity index 86% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/CollectionCRUDAsyncAPITest.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java index 4ed8e550f35ed..7e9d50bacf271 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/CollectionCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java @@ -20,24 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; +package com.azure.data.cosmos.rx.examples; +import com.azure.data.cosmos.*; import com.google.common.util.concurrent.ListenableFuture; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.Index; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; @@ -80,7 +66,7 @@ *

* To Modify the Collection's throughput after it has been created, you need to * update the corresponding Offer. Please see - * {@see com.microsoft.azure.cosmosdb.rx.examples.OfferCRUDAsyncAPITest#testUpdateOffer()} + * {@see com.azure.data.cosmos.rx.examples.OfferCRUDAsyncAPITest#testUpdateOffer()} */ public class CollectionCRUDAsyncAPITest { private final static int TIMEOUT = 120000; @@ -91,12 +77,12 @@ public class CollectionCRUDAsyncAPITest { @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); createdDatabase = Utils.createDatabaseForTest(asyncClient); @@ -105,11 +91,11 @@ public void setUp() { @BeforeMethod(groups = "samples", timeOut = TIMEOUT) public void before() { collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); collectionDefinition.setPartitionKey(partitionKeyDef); } @@ -120,7 +106,7 @@ public void shutdown() { } /** - * Create a document collection using async api. + * CREATE a document collection using async api. * If you want a single partition collection with 10,000 RU/s throughput, * the only way to do so is to create a single partition collection with lower * throughput (400) and then increase the throughput. @@ -149,7 +135,7 @@ public void createCollection_SinglePartition_Async() throws Exception { } /** - * Create a document collection using async api. + * CREATE a document collection using async api. * This test uses java8 lambda expression. * See testCreateCollection_Async_withoutLambda for usage without lambda * expressions. @@ -181,7 +167,7 @@ public void createCollection_MultiPartition_Async() throws Exception { } /** - * Create a document Collection using async api, without java8 lambda expressions + * CREATE a document Collection using async api, without java8 lambda expressions */ @Test(groups = "samples", timeOut = TIMEOUT) public void createCollection_Async_withoutLambda() throws Exception { @@ -216,7 +202,7 @@ public void call(Throwable error) { } /** - * Create a collection in a blocking manner + * CREATE a collection in a blocking manner */ @Test(groups = "samples", timeOut = TIMEOUT) public void createCollection_toBlocking() { @@ -239,7 +225,7 @@ public void createCollection_toBlocking() { public void createCollection_toBlocking_CollectionAlreadyExists_Fails() { asyncClient.createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single(); - // Create the collection for test. + // CREATE the collection for test. Observable> collectionForTestObservable = asyncClient .createCollection(getDatabaseLink(), collectionDefinition, null); @@ -248,7 +234,7 @@ public void createCollection_toBlocking_CollectionAlreadyExists_Fails() { .single(); // Gets the single result assertThat("Should not reach here", false); } catch (Exception e) { - assertThat("Collection already exists.", ((DocumentClientException) e.getCause()).getStatusCode(), + assertThat("Collection already exists.", ((CosmosClientException) e.getCause()).statusCode(), equalTo(409)); } } @@ -273,16 +259,16 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception } /** - * Read a Collection in an Async manner + * READ a Collection in an Async manner */ @Test(groups = "samples", timeOut = TIMEOUT) public void createAndReadCollection() throws Exception { - // Create a Collection + // CREATE a Collection DocumentCollection documentCollection = asyncClient .createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single() .getResource(); - // Read the created collection using async api + // READ the created collection using async api Observable> readCollectionObservable = asyncClient .readCollection(getCollectionLink(documentCollection), null); @@ -303,16 +289,16 @@ public void createAndReadCollection() throws Exception { } /** - * Delete a Collection in an Async manner + * DELETE a Collection in an Async manner */ @Test(groups = "samples", timeOut = TIMEOUT) public void createAndDeleteCollection() throws Exception { - // Create a Collection + // CREATE a Collection DocumentCollection documentCollection = asyncClient .createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single() .getResource(); - // Delete the created collection using async api + // DELETE the created collection using async api Observable> deleteCollectionObservable = asyncClient .deleteCollection(getCollectionLink(documentCollection), null); @@ -337,14 +323,14 @@ public void createAndDeleteCollection() throws Exception { */ @Test(groups = "samples", timeOut = TIMEOUT) public void collectionCreateAndQuery() throws Exception { - // Create a Collection + // CREATE a Collection DocumentCollection collection = asyncClient .createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single() .getResource(); // Query the created collection using async api Observable> queryCollectionObservable = asyncClient.queryCollections( - getDatabaseLink(), String.format("SELECT * FROM r where r.id = '%s'", collection.getId()), + getDatabaseLink(), String.format("SELECT * FROM r where r.id = '%s'", collection.id()), null); final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -355,13 +341,13 @@ public void collectionCreateAndQuery() throws Exception { // First element of the list should have only 1 result FeedResponse collectionFeedResponse = collectionFeedResponseList.get(0); - assertThat(collectionFeedResponse.getResults().size(), equalTo(1)); + assertThat(collectionFeedResponse.results().size(), equalTo(1)); // This collection should have the same id as the one we created - DocumentCollection foundCollection = collectionFeedResponse.getResults().get(0); - assertThat(foundCollection.getId(), equalTo(collection.getId())); + DocumentCollection foundCollection = collectionFeedResponse.results().get(0); + assertThat(foundCollection.id(), equalTo(collection.id())); - System.out.println(collectionFeedResponse.getActivityId()); + System.out.println(collectionFeedResponse.activityId()); countDownLatch.countDown(); }, error -> { System.err.println("an error occurred while querying the collection: actual cause: " + error.getMessage()); @@ -373,39 +359,39 @@ public void collectionCreateAndQuery() throws Exception { } private String getDatabaseLink() { - return "dbs/" + createdDatabase.getId(); + return "dbs/" + createdDatabase.id(); } private String getCollectionLink(DocumentCollection collection) { - return "dbs/" + createdDatabase.getId() + "/colls/" + collection.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + collection.id(); } private DocumentCollection getMultiPartitionCollectionDefinition() { DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); // Set the partitionKeyDefinition for a partitioned collection. // Here, we are setting the partitionKey of the Collection to be /city PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); List paths = new ArrayList<>(); paths.add("/city"); - partitionKeyDefinition.setPaths(paths); + partitionKeyDefinition.paths(paths); collectionDefinition.setPartitionKey(partitionKeyDefinition); // Set indexing policy to be range range for string and number IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); + includedPath.path("/*"); Collection indexes = new ArrayList<>(); - Index stringIndex = Index.Range(DataType.String); + Index stringIndex = Index.Range(DataType.STRING); stringIndex.set("precision", -1); indexes.add(stringIndex); - Index numberIndex = Index.Range(DataType.Number); + Index numberIndex = Index.Range(DataType.NUMBER); numberIndex.set("precision", -1); indexes.add(numberIndex); - includedPath.setIndexes(indexes); + includedPath.indexes(indexes); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); collectionDefinition.setIndexingPolicy(indexingPolicy); diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/ConflictAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java similarity index 79% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/ConflictAPITest.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java index d82c4aa07b9dd..212a8d2852750 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/ConflictAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java @@ -20,21 +20,21 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; +package com.azure.data.cosmos.rx.examples; import com.google.common.util.concurrent.ListenableFuture; -import com.microsoft.azure.cosmosdb.Conflict; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.azure.data.cosmos.Conflict; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -69,28 +69,28 @@ public class ConflictAPITest { @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); client = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); collectionDefinition.setPartitionKey(partitionKeyDef); - // Create database + // CREATE database createdDatabase = Utils.createDatabaseForTest(client); - // Create collection + // CREATE collection createdCollection = client - .createCollection("/dbs/" + createdDatabase.getId(), collectionDefinition, null) + .createCollection("/dbs/" + createdDatabase.id(), collectionDefinition, null) .toBlocking().single().getResource(); int numberOfDocuments = 20; @@ -108,7 +108,7 @@ public void shutdown() { } /** - * Read conflicts + * READ conflicts * Converts the conflict read feed observable to blocking observable and * uses that to find all conflicts */ @@ -117,7 +117,7 @@ public void readConflicts_toBlocking_toIterator() { // read all conflicts int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); + options.maxItemCount(requestPageSize); Observable> conflictReadFeedObservable = client .readConflicts(getCollectionLink(), options); @@ -131,11 +131,11 @@ public void readConflicts_toBlocking_toIterator() { int numberOfResults = 0; while (it.hasNext()) { FeedResponse page = it.next(); - System.out.println("items: " + page.getResults()); - String pageSizeAsString = page.getResponseHeaders().get(HttpConstants.HttpHeaders.ITEM_COUNT); + System.out.println("items: " + page.results()); + String pageSizeAsString = page.responseHeaders().get(HttpConstants.HttpHeaders.ITEM_COUNT); assertThat("header item count must be present", pageSizeAsString, notNullValue()); int pageSize = Integer.valueOf(pageSizeAsString); - assertThat("Result size must match header item count", page.getResults(), hasSize(pageSize)); + assertThat("Result size must match header item count", page.results(), hasSize(pageSize)); numberOfResults += pageSize; } assertThat("number of total results", numberOfResults, equalTo(expectedNumberOfConflicts)); @@ -151,7 +151,7 @@ public void readConflicts_toBlocking_toIterator() { public void transformObservableToGoogleGuavaListenableFuture() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); + options.maxItemCount(requestPageSize); Observable> conflictReadFeedObservable = client .readConflicts(getCollectionLink(), options); @@ -166,13 +166,13 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception int totalNumberOfRetrievedConflicts = 0; for (FeedResponse page : pageList) { - totalNumberOfRetrievedConflicts += page.getResults().size(); + totalNumberOfRetrievedConflicts += page.results().size(); } assertThat(0, equalTo(totalNumberOfRetrievedConflicts)); } private String getCollectionLink() { - return "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(); } } diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DatabaseCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java similarity index 87% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DatabaseCRUDAsyncAPITest.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java index 1f2fdfde4b646..826f119ed278e 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DatabaseCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java @@ -20,17 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; +package com.azure.data.cosmos.rx.examples; +import com.azure.data.cosmos.*; import com.google.common.util.concurrent.ListenableFuture; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -77,20 +70,20 @@ public class DatabaseCRUDAsyncAPITest { @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); } private Database getDatabaseDefinition() { Database databaseDefinition = new Database(); - databaseDefinition.setId(Utils.generateDatabaseId()); + databaseDefinition.id(Utils.generateDatabaseId()); - databaseIds.add(databaseDefinition.getId()); + databaseIds.add(databaseDefinition.id()); return databaseDefinition; } @@ -104,7 +97,7 @@ public void shutdown() { } /** - * Create a database using async api. + * CREATE a database using async api. * This test uses java8 lambda expression. * See testCreateDatabase_Async_withoutLambda for usage without lambda. */ @@ -130,7 +123,7 @@ public void createDatabase_Async() throws Exception { } /** - * Create a database using async api, without java8 lambda expressions + * CREATE a database using async api, without java8 lambda expressions */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDatabase_Async_withoutLambda() throws Exception { @@ -165,7 +158,7 @@ public void call(Throwable error) { } /** - * Create a database in a blocking manner + * CREATE a database in a blocking manner */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDatabase_toBlocking() { @@ -189,7 +182,7 @@ public void createDatabase_toBlocking_DatabaseAlreadyExists_Fails() { Database databaseDefinition = getDatabaseDefinition(); asyncClient.createDatabase(databaseDefinition, null).toBlocking().single(); - // Create the database for test. + // CREATE the database for test. Observable> databaseForTestObservable = asyncClient .createDatabase(databaseDefinition, null); @@ -198,7 +191,7 @@ public void createDatabase_toBlocking_DatabaseAlreadyExists_Fails() { .single(); // Gets the single result assertThat("Should not reach here", false); } catch (Exception e) { - assertThat("Database already exists.", ((DocumentClientException) e.getCause()).getStatusCode(), + assertThat("Database already exists.", ((CosmosClientException) e.getCause()).statusCode(), equalTo(409)); } } @@ -222,15 +215,15 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception } /** - * Read a Database in an Async manner + * READ a Database in an Async manner */ @Test(groups = "samples", timeOut = TIMEOUT) public void createAndReadDatabase() throws Exception { - // Create a database + // CREATE a database Database database = asyncClient.createDatabase(getDatabaseDefinition(), null).toBlocking().single().getResource(); - // Read the created database using async api - Observable> readDatabaseObservable = asyncClient.readDatabase("dbs/" + database.getId(), + // READ the created database using async api + Observable> readDatabaseObservable = asyncClient.readDatabase("dbs/" + database.id(), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -250,16 +243,16 @@ public void createAndReadDatabase() throws Exception { } /** - * Delete a Database in an Async manner + * DELETE a Database in an Async manner */ @Test(groups = "samples", timeOut = TIMEOUT) public void createAndDeleteDatabase() throws Exception { - // Create a database + // CREATE a database Database database = asyncClient.createDatabase(getDatabaseDefinition(), null).toBlocking().single().getResource(); - // Delete the created database using async api + // DELETE the created database using async api Observable> deleteDatabaseObservable = asyncClient - .deleteDatabase("dbs/" + database.getId(), null); + .deleteDatabase("dbs/" + database.id(), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -282,13 +275,13 @@ public void createAndDeleteDatabase() throws Exception { */ @Test(groups = "samples", timeOut = TIMEOUT) public void databaseCreateAndQuery() throws Exception { - // Create a database + // CREATE a database Database databaseDefinition = getDatabaseDefinition(); asyncClient.createDatabase(databaseDefinition, null).toBlocking().single().getResource(); // Query the created database using async api Observable> queryDatabaseObservable = asyncClient - .queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseDefinition.getId()), null); + .queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseDefinition.id()), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -298,13 +291,13 @@ public void databaseCreateAndQuery() throws Exception { // First element of the list should have only 1 result FeedResponse databaseFeedResponse = databaseFeedResponseList.get(0); - assertThat(databaseFeedResponse.getResults().size(), equalTo(1)); + assertThat(databaseFeedResponse.results().size(), equalTo(1)); // This database should have the same id as the one we created - Database foundDatabase = databaseFeedResponse.getResults().get(0); - assertThat(foundDatabase.getId(), equalTo(databaseDefinition.getId())); + Database foundDatabase = databaseFeedResponse.results().get(0); + assertThat(foundDatabase.id(), equalTo(databaseDefinition.id())); - System.out.println(databaseFeedResponse.getActivityId()); + System.out.println(databaseFeedResponse.activityId()); completionLatch.countDown(); }, error -> { System.err.println("an error occurred while querying the database: actual cause: " + error.getMessage()); diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java similarity index 87% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentCRUDAsyncAPITest.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java index c68157454ca46..0c7ba9fbb8349 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java @@ -20,29 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; +package com.azure.data.cosmos.rx.examples; +import com.azure.data.cosmos.*; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.util.concurrent.ListenableFuture; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import org.apache.commons.lang3.RandomUtils; -import org.assertj.core.api.Assertions; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -98,29 +84,29 @@ public class DocumentCRUDAsyncAPITest { public void setUp() { // Sets up the requirements for each test ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); ArrayList partitionKeyPaths = new ArrayList(); partitionKeyPaths.add(PARTITION_KEY_PATH); - partitionKeyDefinition.setPaths(partitionKeyPaths); + partitionKeyDefinition.paths(partitionKeyPaths); collectionDefinition.setPartitionKey(partitionKeyDefinition); - // Create database + // CREATE database createdDatabase = Utils.createDatabaseForTest(asyncClient); - // Create collection + // CREATE collection createdCollection = asyncClient - .createCollection("dbs/" + createdDatabase.getId(), collectionDefinition, null) + .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) .toBlocking().single().getResource(); } @@ -131,7 +117,7 @@ public void shutdown() { } /** - * Create a document using java8 lambda expressions + * CREATE a document using java8 lambda expressions */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_Async() throws Exception { @@ -157,7 +143,7 @@ public void createDocument_Async() throws Exception { } /** - * Create a document without java8 lambda expressions + * CREATE a document without java8 lambda expressions */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_Async_withoutLambda() throws Exception { @@ -194,7 +180,7 @@ public void call(Throwable error) { } /** - * Create a document in a blocking manner + * CREATE a document in a blocking manner */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_toBlocking() { @@ -208,22 +194,22 @@ public void createDocument_toBlocking() { } /** - * Create a document with a programmatically set definition, in an Async manner + * CREATE a document with a programmatically set definition, in an Async manner */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDocumentWithProgrammableDocumentDefinition() throws Exception { Document documentDefinition = new Document(); - documentDefinition.setId("test-document"); + documentDefinition.id("test-document"); documentDefinition.set("counter", 1); - // Create a document + // CREATE a document Document createdDocument = asyncClient .createDocument(getCollectionLink(), documentDefinition, null, false).toBlocking().single() .getResource(); RequestOptions options = new RequestOptions(); options.setPartitionKey(PartitionKey.None); - // Read the created document + // READ the created document Observable> readDocumentObservable = asyncClient .readDocument(getDocumentLink(createdDocument), options); @@ -233,7 +219,7 @@ public void createDocumentWithProgrammableDocumentDefinition() throws Exception Document readDocument = documentResourceResponse.getResource(); // The read document must be the same as the written document - assertThat(readDocument.getId(), equalTo("test-document")); + assertThat(readDocument.id(), equalTo("test-document")); assertThat(readDocument.getInt("counter"), equalTo(1)); System.out.println(documentResourceResponse.getActivityId()); completionLatch.countDown(); @@ -246,11 +232,11 @@ public void createDocumentWithProgrammableDocumentDefinition() throws Exception } /** - * Create 10 documents and sum up all the documents creation request charges + * CREATE 10 documents and sum up all the documents creation request charges */ @Test(groups = "samples", timeOut = TIMEOUT) public void documentCreation_SumUpRequestCharge() throws Exception { - // Create 10 documents + // CREATE 10 documents List>> listOfCreateDocumentObservables = new ArrayList<>(); for (int i = 0; i < 10; i++) { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), i)); @@ -263,7 +249,7 @@ public void documentCreation_SumUpRequestCharge() throws Exception { // Merge all document creation observables into one observable Observable> mergedObservable = Observable.merge(listOfCreateDocumentObservables); - // Create a new observable emitting the total charge of creating all 10 + // CREATE a new observable emitting the total charge of creating all 10 // documents. Observable totalChargeObservable = mergedObservable .map(ResourceResponse::getRequestCharge) @@ -296,7 +282,7 @@ public void createDocument_toBlocking_DocumentAlreadyExists_Fails() { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); asyncClient.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); - // Create the document + // CREATE the document Observable> createDocumentObservable = asyncClient .createDocument(getCollectionLink(), doc, null, false); @@ -305,7 +291,7 @@ public void createDocument_toBlocking_DocumentAlreadyExists_Fails() { .single(); // Gets the single result Assert.fail("Document Already Exists. Document Creation must fail"); } catch (Exception e) { - assertThat("Document already exists.", ((DocumentClientException) e.getCause()).getStatusCode(), + assertThat("Document already exists.", ((CosmosClientException) e.getCause()).statusCode(), equalTo(409)); } } @@ -322,7 +308,7 @@ public void createDocument_Async_DocumentAlreadyExists_Fails() throws Exception Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); asyncClient.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); - // Create the document + // CREATE the document Observable> createDocumentObservable = asyncClient .createDocument(getCollectionLink(), doc, null, false); @@ -336,23 +322,23 @@ public void createDocument_Async_DocumentAlreadyExists_Fails() throws Exception Thread.sleep(2000); assertThat(errorList, hasSize(1)); - assertThat(errorList.get(0), is(instanceOf(DocumentClientException.class))); - assertThat(((DocumentClientException) errorList.get(0)).getStatusCode(), equalTo(409)); + assertThat(errorList.get(0), is(instanceOf(CosmosClientException.class))); + assertThat(((CosmosClientException) errorList.get(0)).statusCode(), equalTo(409)); } /** - * Replace a document + * REPLACE a document */ @Test(groups = "samples", timeOut = TIMEOUT) public void documentReplace_Async() throws Exception { - // Create a document + // CREATE a document Document createdDocument = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); createdDocument = asyncClient.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() .single().getResource(); // Try to replace the existing document Document replacingDocument = new Document( - String.format("{ 'id': 'doc%s', 'counter': '%d', 'new-prop' : '2'}", createdDocument.getId(), 1)); + String.format("{ 'id': 'doc%s', 'counter': '%d', 'new-prop' : '2'}", createdDocument.id(), 1)); Observable> replaceDocumentObservable = asyncClient .replaceDocument(getDocumentLink(createdDocument), replacingDocument, null); @@ -374,13 +360,13 @@ public void documentReplace_Async() throws Exception { */ @Test(groups = "samples", timeOut = TIMEOUT) public void documentUpsert_Async() throws Exception { - // Create a document + // CREATE a document Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); asyncClient.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); // Upsert the existing document Document upsertingDocument = new Document( - String.format("{ 'id': 'doc%s', 'counter': '%d', 'new-prop' : '2'}", doc.getId(), 1)); + String.format("{ 'id': 'doc%s', 'counter': '%d', 'new-prop' : '2'}", doc.id(), 1)); Observable> upsertDocumentObservable = asyncClient .upsertDocument(getCollectionLink(), upsertingDocument, null, false); @@ -398,11 +384,11 @@ public void documentUpsert_Async() throws Exception { } /** - * Delete a document + * DELETE a document */ @Test(groups = "samples", timeOut = TIMEOUT) public void documentDelete_Async() throws Exception { - // Create a document + // CREATE a document Document createdDocument = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d', 'mypk' : '%s'}", UUID.randomUUID().toString(), 1, UUID.randomUUID().toString())); createdDocument = asyncClient.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() .single().getResource(); @@ -410,7 +396,7 @@ public void documentDelete_Async() throws Exception { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(createdDocument.getString("mypk"))); - // Delete the existing document + // DELETE the existing document Observable> deleteDocumentObservable = asyncClient .deleteDocument(getDocumentLink(createdDocument), options); @@ -427,10 +413,10 @@ public void documentDelete_Async() throws Exception { // Assert document is deleted FeedOptions queryOptions = new FeedOptions(); - queryOptions.setEnableCrossPartitionQuery(true); + queryOptions.enableCrossPartitionQuery(true); List listOfDocuments = asyncClient - .queryDocuments(getCollectionLink(), String.format("SELECT * FROM r where r.id = '%s'", createdDocument.getId()), queryOptions) - .map(FeedResponse::getResults) // Map page to its list of documents + .queryDocuments(getCollectionLink(), String.format("SELECT * FROM r where r.id = '%s'", createdDocument.id()), queryOptions) + .map(FeedResponse::results) // Map page to its list of documents .concatMap(Observable::from) // Flatten the observable .toList() // Transform to a observable .toBlocking() // Block @@ -441,16 +427,16 @@ public void documentDelete_Async() throws Exception { } /** - * Read a document + * READ a document */ @Test(groups = "samples", timeOut = TIMEOUT) public void documentRead_Async() throws Exception { - // Create a document + // CREATE a document Document createdDocument = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d', 'mypk' : '%s'}", UUID.randomUUID().toString(), 1, UUID.randomUUID().toString())); createdDocument = asyncClient.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() .single().getResource(); - // Read the document + // READ the document RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(createdDocument.getString("mypk"))); Observable> readDocumentObservable = asyncClient @@ -503,7 +489,7 @@ public void customSerialization() throws Exception { options.setPartitionKey(new PartitionKey(testObject.mypk)); Document readDocument = asyncClient - .readDocument(createdDocument.getSelfLink(), options) + .readDocument(createdDocument.selfLink(), options) .toBlocking() .single() .getResource(); @@ -533,10 +519,10 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception } private String getCollectionLink() { - return "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(); } private String getDocumentLink(Document createdDocument) { - return "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId() + "/docs/" + createdDocument.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id() + "/docs/" + createdDocument.id(); } } diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentQueryAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java similarity index 85% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentQueryAsyncAPITest.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java index 0cb6ec4013996..dd5c7ecb504b0 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/DocumentQueryAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java @@ -20,23 +20,23 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; +package com.azure.data.cosmos.rx.examples; import com.google.common.util.concurrent.ListenableFuture; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.SqlParameterCollection; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.SqlParameterCollection; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.AsyncDocumentClient; import org.apache.commons.lang3.RandomStringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -92,29 +92,29 @@ public class DocumentQueryAsyncAPITest { @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); collectionDefinition.setPartitionKey(partitionKeyDef); - // Create database + // CREATE database createdDatabase = Utils.createDatabaseForTest(asyncClient); - // Create collection + // CREATE collection createdCollection = asyncClient - .createCollection("dbs/" + createdDatabase.getId(), collectionDefinition, null) + .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) .toBlocking().single().getResource(); numberOfDocuments = 20; @@ -140,8 +140,8 @@ public void shutdown() { public void queryDocuments_Async() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(requestPageSize); + options.enableCrossPartitionQuery(true); Observable> documentQueryObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); @@ -159,7 +159,7 @@ public void queryDocuments_Async() throws Exception { } for (@SuppressWarnings("unused") - Document d : page.getResults()) { + Document d : page.results()) { resultsCountDown.countDown(); } }); @@ -187,8 +187,8 @@ public void queryDocuments_Async() throws Exception { public void queryDocuments_Async_withoutLambda() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(requestPageSize); + options.enableCrossPartitionQuery(true); Observable> documentQueryObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); @@ -209,7 +209,7 @@ public void call(FeedResponse t) { } catch (InterruptedException e) { } - for (Document d : t.getResults()) { + for (Document d : t.results()) { resultsCountDown.countDown(); } } @@ -237,12 +237,12 @@ public void call(FeedResponse t) { public void queryDocuments_findTotalRequestCharge() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(requestPageSize); + options.enableCrossPartitionQuery(true); Observable totalChargeObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options) - .map(FeedResponse::getRequestCharge) // Map the page to its request charge + .map(FeedResponse::requestCharge) // Map the page to its request charge .reduce((totalCharge, charge) -> totalCharge + charge); // Sum up all the request charges final CountDownLatch successfulCompletionLatch = new CountDownLatch(1); @@ -263,8 +263,8 @@ public void queryDocuments_findTotalRequestCharge() throws Exception { public void queryDocuments_unsubscribeAfterFirstPage() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(requestPageSize); + options.enableCrossPartitionQuery(true); Observable> requestChargeObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); @@ -308,8 +308,8 @@ public void onNext(FeedResponse page) { public void queryDocuments_filterFetchedResults() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(requestPageSize); + options.enableCrossPartitionQuery(true); Func1 isPrimeNumber = new Func1() { @@ -329,7 +329,7 @@ public Boolean call(Document doc) { List resultList = Collections.synchronizedList(new ArrayList()); asyncClient.queryDocuments(getCollectionLink(), "SELECT * FROM root", options) - .map(FeedResponse::getResults) // Map the page to the list of documents + .map(FeedResponse::results) // Map the page to the list of documents .concatMap(Observable::from) // Flatten the observable> to observable .filter(isPrimeNumber) // Filter documents using isPrimeNumber predicate .subscribe(doc -> resultList.add(doc)); // Collect the results @@ -368,8 +368,8 @@ public void queryDocuments_toBlocking_toIterator() { // Query for documents int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(requestPageSize); + options.enableCrossPartitionQuery(true); Observable> documentQueryObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); @@ -384,10 +384,10 @@ public void queryDocuments_toBlocking_toIterator() { FeedResponse page = it.next(); pageCounter++; - String pageSizeAsString = page.getResponseHeaders().get(HttpConstants.HttpHeaders.ITEM_COUNT); + String pageSizeAsString = page.responseHeaders().get(HttpConstants.HttpHeaders.ITEM_COUNT); assertThat("header item count must be present", pageSizeAsString, notNullValue()); int pageSize = Integer.valueOf(pageSizeAsString); - assertThat("Result size must match header item count", page.getResults(), hasSize(pageSize)); + assertThat("Result size must match header item count", page.results(), hasSize(pageSize)); numberOfResults += pageSize; } assertThat("number of total results", numberOfResults, equalTo(numberOfDocuments)); @@ -400,9 +400,9 @@ public void queryDocuments_toBlocking_toIterator() { */ @Test(groups = "samples", timeOut = TIMEOUT) public void qrderBy_Async() throws Exception { - // Create a partitioned collection + // CREATE a partitioned collection String collectionId = UUID.randomUUID().toString(); - DocumentCollection multiPartitionCollection = createMultiPartitionCollection("dbs/" + createdDatabase.getId(), + DocumentCollection multiPartitionCollection = createMultiPartitionCollection("dbs/" + createdDatabase.id(), collectionId, "/key"); // Insert documents @@ -411,30 +411,30 @@ public void qrderBy_Async() throws Exception { Document doc = new Document(String.format("{\"id\":\"documentId%d\",\"key\":\"%s\",\"prop\":%d}", i, RandomStringUtils.randomAlphabetic(2), i)); - asyncClient.createDocument("dbs/" + createdDatabase.getId() + "/colls/" + multiPartitionCollection.getId(), + asyncClient.createDocument("dbs/" + createdDatabase.id() + "/colls/" + multiPartitionCollection.id(), doc, null, true).toBlocking().single(); } // Query for the documents order by the prop field SqlQuerySpec query = new SqlQuerySpec("SELECT r.id FROM r ORDER BY r.prop", new SqlParameterCollection()); FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setMaxItemCount(5); + options.enableCrossPartitionQuery(true); + options.maxItemCount(5); // Max degree of parallelism determines the number of partitions that // the SDK establishes simultaneous connections to. - options.setMaxDegreeOfParallelism(2); + options.maxDegreeOfParallelism(2); // Get the observable order by query documents Observable> documentQueryObservable = asyncClient.queryDocuments( - "dbs/" + createdDatabase.getId() + "/colls/" + multiPartitionCollection.getId(), query, options); + "dbs/" + createdDatabase.id() + "/colls/" + multiPartitionCollection.id(), query, options); List resultList = Collections.synchronizedList(new ArrayList<>()); - documentQueryObservable.map(FeedResponse::getResults) + documentQueryObservable.map(FeedResponse::results) // Map the logical page to the list of documents in the page .concatMap(Observable::from) // Flatten the list of documents - .map(doc -> doc.getId()) // Map to the document Id + .map(doc -> doc.id()) // Map to the document Id .forEach(docId -> resultList.add(docId)); // Add each document Id to the resultList Thread.sleep(4000); @@ -458,8 +458,8 @@ public void qrderBy_Async() throws Exception { public void transformObservableToGoogleGuavaListenableFuture() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(requestPageSize); + options.enableCrossPartitionQuery(true); Observable> documentQueryObservable = asyncClient .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); @@ -474,13 +474,13 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception int totalNumberOfRetrievedDocuments = 0; for (FeedResponse page : pageList) { - totalNumberOfRetrievedDocuments += page.getResults().size(); + totalNumberOfRetrievedDocuments += page.results().size(); } assertThat(numberOfDocuments, equalTo(totalNumberOfRetrievedDocuments)); } private String getCollectionLink() { - return "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(); } private DocumentCollection createMultiPartitionCollection(String databaseLink, String collectionId, @@ -488,12 +488,12 @@ private DocumentCollection createMultiPartitionCollection(String databaseLink, S PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add(partitionKeyPath); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); RequestOptions options = new RequestOptions(); options.setOfferThroughput(10100); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(collectionId); + collectionDefinition.id(collectionId); collectionDefinition.setPartitionKey(partitionKeyDef); DocumentCollection createdCollection = asyncClient.createCollection(databaseLink, collectionDefinition, options) .toBlocking().single().getResource(); diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/InMemoryGroupbyTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java similarity index 81% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/InMemoryGroupbyTest.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java index 23c97a7dadba0..5e22f6cd16d5a 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/InMemoryGroupbyTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java @@ -20,20 +20,20 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; - -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.SqlParameter; -import com.microsoft.azure.cosmosdb.SqlParameterCollection; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +package com.azure.data.cosmos.rx.examples; + +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.SqlParameter; +import com.azure.data.cosmos.SqlParameterCollection; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -55,28 +55,28 @@ public class InMemoryGroupbyTest { @BeforeClass(groups = "samples", timeOut = TIMEOUT) public static void setUp() throws Exception { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); - // Create database + // CREATE database createdDatabase = Utils.createDatabaseForTest(asyncClient); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); collectionDefinition.setPartitionKey(partitionKeyDef); - // Create collection + // CREATE collection createdCollection = asyncClient - .createCollection("dbs/" + createdDatabase.getId(), collectionDefinition, null) + .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) .toBlocking().single().getResource(); int numberOfPayers = 10; @@ -118,15 +118,15 @@ public void groupByInMemory() { // If you want to understand the steps in more details see groupByInMemoryMoreDetail() int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(requestPageSize); + options.enableCrossPartitionQuery(true); Observable documentsObservable = asyncClient .queryDocuments(getCollectionLink(), new SqlQuerySpec("SELECT * FROM root r WHERE r.site_id=@site_id", new SqlParameterCollection(new SqlParameter("@site_id", "ABC"))), options) - .flatMap(page -> Observable.from(page.getResults())); + .flatMap(page -> Observable.from(page.results())); final LocalDateTime now = LocalDateTime.now(); @@ -151,15 +151,15 @@ public void groupByInMemory_MoreDetail() { int requestPageSize = 3; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(requestPageSize); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(requestPageSize); + options.enableCrossPartitionQuery(true); Observable documentsObservable = asyncClient .queryDocuments(getCollectionLink(), new SqlQuerySpec("SELECT * FROM root r WHERE r.site_id=@site_id", new SqlParameterCollection(new SqlParameter("@site_id", "ABC"))), options) - .flatMap(page -> Observable.from(page.getResults())); + .flatMap(page -> Observable.from(page.results())); final LocalDateTime now = LocalDateTime.now(); @@ -180,6 +180,6 @@ public void groupByInMemory_MoreDetail() { } private static String getCollectionLink() { - return "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(); } } diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/OfferCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java similarity index 78% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/OfferCRUDAsyncAPITest.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java index f64d4ec20fc34..c20ef269916bc 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/OfferCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java @@ -21,21 +21,21 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; - -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.Index; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +package com.azure.data.cosmos.rx.examples; + +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.DataType; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.IncludedPath; +import com.azure.data.cosmos.Index; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -61,15 +61,15 @@ public class OfferCRUDAsyncAPITest { @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); - // Create database + // CREATE database createdDatabase = Utils.createDatabaseForTest(asyncClient); } @@ -81,7 +81,7 @@ public void shutdown() { /** * Query for all the offers existing in the database account. - * Replace the required offer so that it has a higher throughput. + * REPLACE the required offer so that it has a higher throughput. */ @Test(groups = "samples", timeOut = TIMEOUT) public void updateOffer() throws Exception { @@ -93,8 +93,8 @@ public void updateOffer() throws Exception { RequestOptions multiPartitionRequestOptions = new RequestOptions(); multiPartitionRequestOptions.setOfferThroughput(initialThroughput); - // Create the collection - DocumentCollection createdCollection = asyncClient.createCollection("dbs/" + createdDatabase.getId(), + // CREATE the collection + DocumentCollection createdCollection = asyncClient.createCollection("dbs/" + createdDatabase.id(), getMultiPartitionCollectionDefinition(), multiPartitionRequestOptions).toBlocking().single() .getResource(); @@ -102,30 +102,30 @@ public void updateOffer() throws Exception { // Find offer associated with this collection asyncClient.queryOffers( - String.format("SELECT * FROM r where r.offerResourceId = '%s'", createdCollection.getResourceId()), + String.format("SELECT * FROM r where r.offerResourceId = '%s'", createdCollection.resourceId()), null).flatMap(offerFeedResponse -> { - List offerList = offerFeedResponse.getResults(); - // Number of offers returned should be 1 + List offerList = offerFeedResponse.results(); + // NUMBER of offers returned should be 1 assertThat(offerList.size(), equalTo(1)); // This offer must correspond to the collection we created Offer offer = offerList.get(0); int currentThroughput = offer.getThroughput(); - assertThat(offer.getString("offerResourceId"), equalTo(createdCollection.getResourceId())); + assertThat(offer.getString("offerResourceId"), equalTo(createdCollection.resourceId())); assertThat(currentThroughput, equalTo(initialThroughput)); System.out.println("initial throughput: " + currentThroughput); - // Update the offer's throughput + // UPDATE the offer's throughput offer.setThroughput(newThroughput); - // Replace the offer + // REPLACE the offer return asyncClient.replaceOffer(offer); }).subscribe(offerResourceResponse -> { Offer offer = offerResourceResponse.getResource(); int currentThroughput = offer.getThroughput(); // The current throughput of the offer must be equal to the new throughput value - assertThat(offer.getString("offerResourceId"), equalTo(createdCollection.getResourceId())); + assertThat(offer.getString("offerResourceId"), equalTo(createdCollection.resourceId())); assertThat(currentThroughput, equalTo(newThroughput)); System.out.println("updated throughput: " + currentThroughput); @@ -140,30 +140,30 @@ public void updateOffer() throws Exception { private DocumentCollection getMultiPartitionCollectionDefinition() { DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); // Set the partitionKeyDefinition for a partitioned collection // Here, we are setting the partitionKey of the Collection to be /city PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); List paths = new ArrayList<>(); paths.add("/city"); - partitionKeyDefinition.setPaths(paths); + partitionKeyDefinition.paths(paths); collectionDefinition.setPartitionKey(partitionKeyDefinition); // Set indexing policy to be range range for string and number IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); + includedPath.path("/*"); Collection indexes = new ArrayList<>(); - Index stringIndex = Index.Range(DataType.String); + Index stringIndex = Index.Range(DataType.STRING); stringIndex.set("precision", -1); indexes.add(stringIndex); - Index numberIndex = Index.Range(DataType.Number); + Index numberIndex = Index.Range(DataType.NUMBER); numberIndex.set("precision", -1); indexes.add(numberIndex); - includedPath.setIndexes(indexes); + includedPath.indexes(indexes); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); collectionDefinition.setIndexingPolicy(indexingPolicy); diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/StoredProcedureAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java similarity index 84% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/StoredProcedureAsyncAPITest.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java index aa06bf5013971..a3abfc1bc210a 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/StoredProcedureAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java @@ -21,23 +21,23 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; - -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.Index; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +package com.azure.data.cosmos.rx.examples; + +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.DataType; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.IncludedPath; +import com.azure.data.cosmos.Index; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.StoredProcedure; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -50,8 +50,6 @@ import java.util.UUID; import java.util.concurrent.CountDownLatch; -import javax.net.ssl.SSLException; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.core.Is.is; @@ -70,18 +68,18 @@ public class StoredProcedureAsyncAPITest { @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); createdDatabase = Utils.createDatabaseForTest(asyncClient); createdCollection = asyncClient - .createCollection("dbs/" + createdDatabase.getId(), getMultiPartitionCollectionDefinition(), null) + .createCollection("dbs/" + createdDatabase.id(), getMultiPartitionCollectionDefinition(), null) .toBlocking().single().getResource(); } @@ -96,7 +94,7 @@ public void shutdown() { */ @Test(groups = "samples", timeOut = TIMEOUT) public void scriptConsoleLogEnabled() throws Exception { - // Create a stored procedure + // CREATE a stored procedure StoredProcedure storedProcedure = new StoredProcedure( "{" + " 'id':'storedProcedureSample'," + @@ -106,10 +104,10 @@ public void scriptConsoleLogEnabled() throws Exception { " var myval = 1;" + " try {" + " console.log(\"The value of %s is %s.\", mytext, myval);" + - " getContext().getResponse().setBody(\"Success!\");" + + " getContext().getResponse().body(\"Success!\");" + " }" + " catch(err) {" + - " getContext().getResponse().setBody(\"inline err: [\" + err.number + \"] \" + err);" + + " getContext().getResponse().body(\"inline err: [\" + err.number + \"] \" + err);" + " }" + " }'" + "}"); @@ -149,13 +147,13 @@ public void scriptConsoleLogEnabled() throws Exception { */ @Test(groups = "samples", timeOut = TIMEOUT) public void executeStoredProcWithArgs() throws Exception { - // Create stored procedure + // CREATE stored procedure StoredProcedure storedProcedure = new StoredProcedure( "{" + " 'id': 'multiplySample'," + " 'body':" + " 'function (value, num) {" + - " getContext().getResponse().setBody(" + + " getContext().getResponse().body(" + " \"2*\" + value + \" is \" + num * 2 );" + " }'" + "}"); @@ -195,7 +193,7 @@ public void executeStoredProcWithPojoArgs() throws Exception { " 'id': 'storedProcedurePojoSample'," + " 'body':" + " 'function (value) {" + - " getContext().getResponse().setBody(" + + " getContext().getResponse().body(" + " \"a is \" + value.temp);" + " }'" + "}"); @@ -232,30 +230,30 @@ class SamplePojo { private static DocumentCollection getMultiPartitionCollectionDefinition() { DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); // Set the partitionKeyDefinition for a partitioned collection // Here, we are setting the partitionKey of the Collection to be /city PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); List paths = new ArrayList(); paths.add("/city"); - partitionKeyDefinition.setPaths(paths); + partitionKeyDefinition.paths(paths); collectionDefinition.setPartitionKey(partitionKeyDefinition); // Set indexing policy to be range range for string and number IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection includedPaths = new ArrayList(); IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); + includedPath.path("/*"); Collection indexes = new ArrayList(); - Index stringIndex = Index.Range(DataType.String); + Index stringIndex = Index.Range(DataType.STRING); stringIndex.set("precision", -1); indexes.add(stringIndex); - Index numberIndex = Index.Range(DataType.Number); + Index numberIndex = Index.Range(DataType.NUMBER); numberIndex.set("precision", -1); indexes.add(numberIndex); - includedPath.setIndexes(indexes); + includedPath.indexes(indexes); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); collectionDefinition.setIndexingPolicy(indexingPolicy); @@ -264,10 +262,10 @@ private static DocumentCollection getMultiPartitionCollectionDefinition() { } private String getCollectionLink() { - return "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(); } private String getSprocLink(StoredProcedure sproc) { - return "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId() + "/sprocs/" + sproc.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id() + "/sprocs/" + sproc.id(); } } \ No newline at end of file diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TestConfigurations.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java similarity index 95% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TestConfigurations.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java index f48ee5da652c8..0b7c7467cbb6d 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TestConfigurations.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; +package com.azure.data.cosmos.rx.examples; import org.apache.commons.lang3.StringUtils; @@ -40,7 +40,7 @@ * If none of the above is set, emulator endpoint will be used. */ public final class TestConfigurations { - // Replace MASTER_KEY and HOST with values from your Azure Cosmos DB account. + // REPLACE MASTER_KEY and HOST with values from your Azure Cosmos DB account. // The default values are credentials of the local emulator, which are not used in any production environment. // public static String MASTER_KEY = diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TokenResolverTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java similarity index 77% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TokenResolverTest.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java index 4c56170eb4972..7ace3b7d0d852 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/TokenResolverTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java @@ -21,25 +21,25 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; +package com.azure.data.cosmos.rx.examples; import com.google.common.collect.ImmutableMap; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.CosmosResourceType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.PermissionMode; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.TokenResolver; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosResourceType; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.PermissionMode; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.TokenResolver; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -78,92 +78,92 @@ public class TokenResolverTest { public void setUp() { // Sets up the requirements for each test ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); collectionDefinition.setPartitionKey(partitionKeyDef); - // Create database + // CREATE database createdDatabase = Utils.createDatabaseForTest(asyncClient); - // Create collection + // CREATE collection createdCollection = asyncClient - .createCollection("dbs/" + createdDatabase.getId(), collectionDefinition, null) + .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) .toBlocking().single().getResource(); for (int i = 0; i < 10; i++) { - // Create a document + // CREATE a document Document documentDefinition = new Document(); - documentDefinition.setId(UUID.randomUUID().toString()); - Document createdDocument = asyncClient.createDocument(createdCollection.getSelfLink(), documentDefinition, null, true).toBlocking().first().getResource(); + documentDefinition.id(UUID.randomUUID().toString()); + Document createdDocument = asyncClient.createDocument(createdCollection.selfLink(), documentDefinition, null, true).toBlocking().first().getResource(); - // Create a User who is meant to only read this document + // CREATE a User who is meant to only read this document User readUserDefinition = new User(); - readUserDefinition.setId(UUID.randomUUID().toString()); - User createdReadUser = asyncClient.createUser(createdDatabase.getSelfLink(), readUserDefinition, null).toBlocking().first().getResource(); + readUserDefinition.id(UUID.randomUUID().toString()); + User createdReadUser = asyncClient.createUser(createdDatabase.selfLink(), readUserDefinition, null).toBlocking().first().getResource(); - // Create a read only permission for the above document + // CREATE a read only permission for the above document Permission readOnlyPermissionDefinition = new Permission(); - readOnlyPermissionDefinition.setId(UUID.randomUUID().toString()); - readOnlyPermissionDefinition.setResourceLink(createdDocument.getSelfLink()); - readOnlyPermissionDefinition.setPermissionMode(PermissionMode.Read); + readOnlyPermissionDefinition.id(UUID.randomUUID().toString()); + readOnlyPermissionDefinition.setResourceLink(createdDocument.selfLink()); + readOnlyPermissionDefinition.setPermissionMode(PermissionMode.READ); // Assign the permission to the above user - Permission readOnlyCreatedPermission = asyncClient.createPermission(createdReadUser.getSelfLink(), readOnlyPermissionDefinition, null).toBlocking().first().getResource(); - userToReadOnlyResourceTokenMap.put(createdReadUser.getId(), readOnlyCreatedPermission.getToken()); + Permission readOnlyCreatedPermission = asyncClient.createPermission(createdReadUser.selfLink(), readOnlyPermissionDefinition, null).toBlocking().first().getResource(); + userToReadOnlyResourceTokenMap.put(createdReadUser.id(), readOnlyCreatedPermission.getToken()); - documentToReadUserMap.put(createdDocument.getSelfLink(), createdReadUser.getId()); + documentToReadUserMap.put(createdDocument.selfLink(), createdReadUser.id()); - // Create a User who can both read and write this document + // CREATE a User who can both read and write this document User readWriteUserDefinition = new User(); - readWriteUserDefinition.setId(UUID.randomUUID().toString()); - User createdReadWriteUser = asyncClient.createUser(createdDatabase.getSelfLink(), readWriteUserDefinition, null).toBlocking().first().getResource(); + readWriteUserDefinition.id(UUID.randomUUID().toString()); + User createdReadWriteUser = asyncClient.createUser(createdDatabase.selfLink(), readWriteUserDefinition, null).toBlocking().first().getResource(); - // Create a read/write permission for the above document + // CREATE a read/write permission for the above document Permission readWritePermissionDefinition = new Permission(); - readWritePermissionDefinition.setId(UUID.randomUUID().toString()); - readWritePermissionDefinition.setResourceLink(createdDocument.getSelfLink()); - readWritePermissionDefinition.setPermissionMode(PermissionMode.All); + readWritePermissionDefinition.id(UUID.randomUUID().toString()); + readWritePermissionDefinition.setResourceLink(createdDocument.selfLink()); + readWritePermissionDefinition.setPermissionMode(PermissionMode.ALL); // Assign the permission to the above user - Permission readWriteCreatedPermission = asyncClient.createPermission(createdReadWriteUser.getSelfLink(), readWritePermissionDefinition, null).toBlocking().first().getResource(); - userToReadWriteResourceTokenMap.put(createdReadWriteUser.getId(), readWriteCreatedPermission.getToken()); + Permission readWriteCreatedPermission = asyncClient.createPermission(createdReadWriteUser.selfLink(), readWritePermissionDefinition, null).toBlocking().first().getResource(); + userToReadWriteResourceTokenMap.put(createdReadWriteUser.id(), readWriteCreatedPermission.getToken()); - documentToReadWriteUserMap.put(createdDocument.getSelfLink(), createdReadWriteUser.getId()); + documentToReadWriteUserMap.put(createdDocument.selfLink(), createdReadWriteUser.id()); } } /** - * Read a document with a user having read permission + * READ a document with a user having read permission */ @Test(groups = "samples", timeOut = TIMEOUT) public void readDocumentThroughTokenResolver() throws Exception { AsyncDocumentClient asyncClientWithTokenResolver = null; try { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClientWithTokenResolver = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .withTokenResolver(getTokenResolverForRead()) .build(); List> capturedResponse = Collections .synchronizedList(new ArrayList<>()); for (String documentLink : documentToReadUserMap.keySet()) { - // Each document has one User who can only read it. Pass that User Id in the properties. + // Each document has one User who can only read it. Pass that User Id in the item. // The token resolver will resolve the token for that User based on 'userId'. ImmutableMap properties = ImmutableMap. builder() .put(USER_ID, documentToReadUserMap.get(documentLink)) @@ -186,25 +186,25 @@ public void readDocumentThroughTokenResolver() throws Exception { } /** - * Delete a document with a user having all permission + * DELETE a document with a user having all permission */ @Test(groups = "samples", timeOut = TIMEOUT, dependsOnMethods = {"readDocumentThroughTokenResolver"}) public void deleteDocumentThroughTokenResolver() throws Exception { AsyncDocumentClient asyncClientWithTokenResolver = null; try { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClientWithTokenResolver = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .withTokenResolver(getTokenResolverForReadWrite()) .build(); List> capturedResponse = Collections .synchronizedList(new ArrayList<>()); for (String documentLink : documentToReadWriteUserMap.keySet()) { - // Each document has one User who can read and write it. Pass that User Id in the properties. + // Each document has one User who can read and write it. Pass that User Id in the item. // The token resolver will resolve the token for that User based on 'userId'. ImmutableMap properties = ImmutableMap. builder() .put(USER_ID, documentToReadWriteUserMap.get(documentLink)) @@ -238,15 +238,15 @@ public void blockListUserThroughTokenResolver() throws Exception { try { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); asyncClientWithTokenResolver = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .withTokenResolver(getTokenResolverWithBlockList(blockListedUserId, errorMessage)) .build(); - // Read a document using a block listed user, passing the 'userId' in the properties. + // READ a document using a block listed user, passing the 'userId' in the item. // Token resolver will throw RuntimeException. RequestOptions options = new RequestOptions(); ImmutableMap properties = ImmutableMap. builder() @@ -254,7 +254,7 @@ public void blockListUserThroughTokenResolver() throws Exception { .build(); options.setProperties(properties); - Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.getSelfLink(), options); + Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); List capturedErrors = Collections .synchronizedList(new ArrayList<>()); readObservable.subscribe(response -> {}, throwable -> capturedErrors.add(throwable)); @@ -263,7 +263,7 @@ public void blockListUserThroughTokenResolver() throws Exception { assertThat(capturedErrors.get(0), instanceOf(RuntimeException.class)); assertThat(capturedErrors.get(0).getMessage(), equalTo(errorMessage)); - // Read a document using a valid user, passing the 'userId' in the properties. + // READ a document using a valid user, passing the 'userId' in the item. // Token resolver will pass on the correct token for authentication. String validUserId = userToReadWriteResourceTokenMap.keySet().iterator().next(); System.out.println(validUserId); @@ -271,13 +271,13 @@ public void blockListUserThroughTokenResolver() throws Exception { .put(USER_ID, validUserId) .build(); options.setProperties(properties); - readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.getSelfLink(), options); + readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); List capturedResponse = Collections .synchronizedList(new ArrayList<>()); readObservable.subscribe(resourceResponse -> capturedResponse.add(resourceResponse.getResource()), error -> error.printStackTrace()); Thread.sleep(2000); assertThat(capturedErrors, hasSize(1)); - assertThat(capturedResponse.get(0).getId(), equalTo(createdCollection.getId())); + assertThat(capturedResponse.get(0).id(), equalTo(createdCollection.id())); } finally { Utils.safeClose(asyncClientWithTokenResolver); } @@ -323,7 +323,7 @@ private TokenResolver getTokenResolverForReadWrite() { * For Reading DatabaseAccount on client initialization, use any User's token. * For subsequent Reads, get the correct read/write token based on 'userId', * only if user is not block listed. In this scenario, the block listed user id - * is compared to the current user's id, passed into the properties for the request. + * is compared to the current user's id, passed into the item for the request. */ private TokenResolver getTokenResolverWithBlockList(String blockListedUserId, String errorMessage) { return (String requestVerb, String resourceIdOrFullName, CosmosResourceType resourceType, Map properties) -> { diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/UniqueIndexAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java similarity index 75% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/UniqueIndexAsyncAPITest.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java index a1e8e3cdf4972..de891e6d020e7 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/UniqueIndexAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java @@ -20,21 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; +package com.azure.data.cosmos.rx.examples; +import com.azure.data.cosmos.*; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.UniqueKey; -import com.microsoft.azure.cosmosdb.UniqueKeyPolicy; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -58,16 +47,16 @@ public class UniqueIndexAsyncAPITest { @Test(groups = "samples", timeOut = TIMEOUT) public void uniqueIndex() { DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); - uniqueKey.setPaths(ImmutableList.of("/name", "/field")); - uniqueKeyPolicy.setUniqueKeys(Collections.singleton(uniqueKey)); + uniqueKey.paths(ImmutableList.of("/name", "/field")); + uniqueKeyPolicy.uniqueKeys(Collections.singleton(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); collectionDefinition.setPartitionKey(partitionKeyDef); DocumentCollection collection = client.createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single().getResource(); @@ -88,29 +77,29 @@ public void uniqueIndex() { docCreation.subscribe(subscriber); subscriber.awaitTerminalEvent(); - subscriber.assertError(DocumentClientException.class); + subscriber.assertError(CosmosClientException.class); assertThat(subscriber.getOnErrorEvents(), hasSize(1)); // error code for failure is conflict - assertThat(((DocumentClientException) subscriber.getOnErrorEvents().get(0)).getStatusCode(), equalTo(409)); + assertThat(((CosmosClientException) subscriber.getOnErrorEvents().get(0)).statusCode(), equalTo(409)); } @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { // Sets up the requirements for each test ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); client = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); - // Create database + // CREATE database createdDatabase = Utils.createDatabaseForTest(client); } @@ -121,10 +110,10 @@ public void shutdown() { } private String getCollectionLink(DocumentCollection collection) { - return "dbs/" + createdDatabase.getId() + "/colls/" + collection.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + collection.id(); } private String getDatabaseLink() { - return "dbs/" + createdDatabase.getId(); + return "dbs/" + createdDatabase.id(); } } diff --git a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/Utils.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java similarity index 82% rename from examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/Utils.java rename to examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java index 5e498bcc2e2a9..6f386435ac7e1 100644 --- a/examples/src/test/java/com/microsoft/azure/cosmosdb/rx/examples/Utils.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java @@ -21,19 +21,19 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.examples; - -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.RetryOptions; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +package com.azure.data.cosmos.rx.examples; + +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.RetryOptions; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.rx.TestConfigurations; import org.testng.annotations.AfterSuite; import rx.Observable; @@ -42,9 +42,9 @@ public class Utils { @AfterSuite(groups = "samples") public void cleanupStaleDatabase() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); RetryOptions options = new RetryOptions(); - connectionPolicy.setRetryOptions(options); + connectionPolicy.retryOptions(options); AsyncDocumentClient client = new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) @@ -54,7 +54,7 @@ public void cleanupStaleDatabase() { } public static String getCollectionLink(Database db, DocumentCollection collection) { - return "dbs/" + db.getId() + "/colls/" + collection; + return "dbs/" + db.id() + "/colls/" + collection; } public static Database createDatabaseForTest(AsyncDocumentClient client) { @@ -69,7 +69,7 @@ private static void safeCleanDatabases(AsyncDocumentClient client) { public static void safeClean(AsyncDocumentClient client, Database database) { if (database != null) { - safeClean(client, database.getId()); + safeClean(client, database.id()); } } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/DatabaseAccountManagerInternal.java b/gateway/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/DatabaseAccountManagerInternal.java rename to gateway/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java index 670153b186725..31e7242f868ee 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/DatabaseAccountManagerInternal.java +++ b/gateway/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import rx.Observable; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/ISessionContainer.java b/gateway/src/main/java/com/azure/data/cosmos/ISessionContainer.java similarity index 96% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/ISessionContainer.java rename to gateway/src/main/java/com/azure/data/cosmos/ISessionContainer.java index 24abe4825075d..d292dc869a93a 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/ISessionContainer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/ISessionContainer.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.internal.ISessionToken; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.ISessionToken; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import java.util.Map; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/WebExceptionUtility.java b/gateway/src/main/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtility.java similarity index 96% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/WebExceptionUtility.java rename to gateway/src/main/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtility.java index c90fdf1e1b470..bf3e24dadbfcf 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/WebExceptionUtility.java +++ b/gateway/src/main/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtility.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.Utils; import io.netty.channel.ChannelException; import io.reactivex.netty.client.PoolExhaustedException; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/AuthorizationTokenProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/AuthorizationTokenProvider.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java index 3aaa9f60dbc53..5e654336b6f05 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/AuthorizationTokenProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import java.util.Map; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/BackoffRetryUtility.java b/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/BackoffRetryUtility.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java index e5240e2fd0935..957589bd79f3d 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/BackoffRetryUtility.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java @@ -20,13 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.time.Duration; -import com.microsoft.azure.cosmosdb.internal.Quadruple; - import rx.Observable; import rx.Single; import rx.functions.Action1; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/BaseAuthorizationTokenProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java similarity index 98% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/BaseAuthorizationTokenProvider.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java index f04df192d7f4b..31051a2c88e45 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/BaseAuthorizationTokenProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import java.net.URI; import java.security.InvalidKeyException; @@ -37,11 +37,10 @@ import org.apache.commons.lang3.StringUtils; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.HttpUtils; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; +import com.azure.data.cosmos.directconnectivity.HttpUtils; /** - * This class is used internally by both client (for generating the auth header with master/system key) and by the Gateway when + * This class is used internally by both client (for generating the auth header with master/system key) and by the GATEWAY when * verifying the auth header in the Azure Cosmos DB database service. */ public class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider { diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/BaseDatabaseAccountConfigurationProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java similarity index 94% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/BaseDatabaseAccountConfigurationProvider.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java index a9faa3657514b..cea418c333536 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/BaseDatabaseAccountConfigurationProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DatabaseAccount; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.DatabaseAccount; /** * Used internally to provides functionality to work with database account configuration in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ClearingSessionContainerClientRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java similarity index 92% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ClearingSessionContainerClientRetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java index 0ba6bb83f53e7..0ef14e768b1f7 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ClearingSessionContainerClientRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java @@ -20,11 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.ISessionContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Single; @@ -66,7 +65,7 @@ public Single shouldRetry(Exception e) { if (!shouldRetryResult.shouldRetry && !this.hasTriggered) { - DocumentClientException clientException = Utils.as(e, DocumentClientException.class); + CosmosClientException clientException = Utils.as(e, CosmosClientException.class); if (this.request == null) { // someone didn't call OnBeforeSendRequest - nothing we can do diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ClientRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java similarity index 93% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ClientRetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java index a4297517e1a30..30a5fa0323939 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ClientRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java @@ -20,13 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.ClientSideRequestStatistics; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.RetryOptions; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.WebExceptionUtility; +import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.RetryOptions; +import com.azure.data.cosmos.directconnectivity.WebExceptionUtility; import org.apache.commons.collections4.list.UnmodifiableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,8 +65,8 @@ public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, RetryOptions retryOptions) { this.throttlingRetry = new ResourceThrottleRetryPolicy( - retryOptions.getMaxRetryAttemptsOnThrottledRequests(), - retryOptions.getMaxRetryWaitTimeInSeconds()); + retryOptions.maxRetryAttemptsOnThrottledRequests(), + retryOptions.maxRetryWaitTimeInSeconds()); this.rxNettyConnectionPoolExhaustedRetry = new ConnectionPoolExhaustedRetry(); this.globalEndpointManager = globalEndpointManager; this.failoverRetryCount = 0; @@ -92,9 +91,9 @@ public Single shouldRetry(Exception e) { this.retryContext = null; // Received 403.3 on write region, initiate the endpoint re-discovery - DocumentClientException clientException = Utils.as(e, DocumentClientException.class); - if (clientException != null && clientException.getClientSideRequestStatistics() != null) { - this.clientSideRequestStatistics = clientException.getClientSideRequestStatistics(); + CosmosClientException clientException = Utils.as(e, CosmosClientException.class); + if (clientException != null && clientException.clientSideRequestStatistics() != null) { + this.clientSideRequestStatistics = clientException.clientSideRequestStatistics(); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ConnectionPoolExhaustedRetry.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetry.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ConnectionPoolExhaustedRetry.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetry.java index 5f2e166e6ddbe..b44d37ba4e262 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ConnectionPoolExhaustedRetry.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetry.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import io.reactivex.netty.client.PoolExhaustedException; import org.slf4j.Logger; @@ -58,7 +58,7 @@ public Single shouldRetry(Exception e) { logger.error("PoolExhaustedException failure indicates" + " the load on the SDK is higher than what current connection pool size can support" + " either increase the connection pool size for the configured connection mode," + - " or distribute the load on more machines. All retries exhausted!"); + " or distribute the load on more machines. ALL retries exhausted!"); return Single.just(ShouldRetryResult.error(e)); } } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/DatabaseAccountConfigurationProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java similarity index 93% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/DatabaseAccountConfigurationProvider.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java index 15ef723956d9c..a82915676cb05 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/DatabaseAccountConfigurationProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.azure.data.cosmos.ConsistencyLevel; /** * Defines an interface to work with database account configuration in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/GlobalEndpointManager.java b/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java similarity index 93% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/GlobalEndpointManager.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java index 6e304f39b7a90..b098305b6c683 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/GlobalEndpointManager.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java @@ -21,14 +21,14 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.DatabaseAccount; -import com.microsoft.azure.cosmosdb.DatabaseAccountManagerInternal; -import com.microsoft.azure.cosmosdb.internal.routing.LocationCache; -import com.microsoft.azure.cosmosdb.rx.internal.routing.LocationHelper; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.internal.routing.LocationHelper; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.DatabaseAccount; +import com.azure.data.cosmos.DatabaseAccountManagerInternal; +import com.azure.data.cosmos.internal.routing.LocationCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; @@ -48,7 +48,6 @@ import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -73,12 +72,12 @@ public GlobalEndpointManager(DatabaseAccountManagerInternal owner, ConnectionPol this.backgroundRefreshLocationTimeIntervalInMS = configs.getUnavailableLocationsExpirationTimeInSeconds() * 1000; try { this.locationCache = new LocationCache( - new ArrayList<>(connectionPolicy.getPreferredLocations() != null ? - connectionPolicy.getPreferredLocations(): + new ArrayList<>(connectionPolicy.preferredLocations() != null ? + connectionPolicy.preferredLocations(): Collections.emptyList() ), owner.getServiceEndpoint().toURL(), - connectionPolicy.getEnableEndpointDiscovery(), + connectionPolicy.enableEndpointDiscovery(), BridgeInternal.getUseMultipleWriteLocations(connectionPolicy), configs); @@ -185,7 +184,7 @@ private Completable refreshLocationPrivateAsync(DatabaseAccount databaseAccount) Single databaseAccountObs = getDatabaseAccountFromAnyLocationsAsync( this.defaultEndpoint, - new ArrayList<>(this.connectionPolicy.getPreferredLocations()), + new ArrayList<>(this.connectionPolicy.preferredLocations()), url -> this.getDatabaseAccountAsync(url)); return databaseAccountObs.map(dbAccount -> { @@ -237,7 +236,7 @@ private Observable startRefreshLocationTimerAsync(boolean initialization) { } logger.debug("startRefreshLocationTimerAsync() - Invoking refresh, I was registered on [{}]", now); - Single databaseAccountObs = GlobalEndpointManager.getDatabaseAccountFromAnyLocationsAsync(this.defaultEndpoint, new ArrayList<>(this.connectionPolicy.getPreferredLocations()), + Single databaseAccountObs = GlobalEndpointManager.getDatabaseAccountFromAnyLocationsAsync(this.defaultEndpoint, new ArrayList<>(this.connectionPolicy.preferredLocations()), url -> this.getDatabaseAccountAsync(url)).toObservable().toSingle(); return databaseAccountObs.flatMapCompletable(dbAccount -> { diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IAuthorizationTokenProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java similarity index 93% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IAuthorizationTokenProvider.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java index d67b23f6bbe12..f7de0a86be903 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IAuthorizationTokenProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java @@ -20,12 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.util.Map; -import com.microsoft.azure.cosmosdb.internal.ResourceType; - public interface IAuthorizationTokenProvider { String getUserAuthorizationToken(String resourceAddress, ResourceType resourceType, diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ICollectionRoutingMapCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java similarity index 93% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ICollectionRoutingMapCache.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java index bd34d1b82d977..301805724c7fa 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ICollectionRoutingMapCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.internal.routing.CollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import rx.Single; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IDocumentClientRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java similarity index 98% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IDocumentClientRetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java index 7f78ad446cf54..efb7f03f0f246 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IDocumentClientRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import rx.Single; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IRetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java index 066e4f39509be..a282ad4950861 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java @@ -21,12 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.time.Duration; -import com.microsoft.azure.cosmosdb.internal.Quadruple; - import rx.Single; // TODO update documentation diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IRetryPolicyFactory.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java similarity index 96% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IRetryPolicyFactory.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java index 3c36fd5fa0c62..a13ba894372de 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IRetryPolicyFactory.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; /** * While this class is public, but it is not part of our published public APIs. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IRoutingMapProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java similarity index 93% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IRoutingMapProvider.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java index 34f270b493fc2..986a5296d3122 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/IRoutingMapProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.util.List; import java.util.Map; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.routing.Range; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.routing.Range; import rx.Single; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/InvalidPartitionException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java similarity index 84% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/InvalidPartitionException.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java index 2710eaf0cce58..6a046bcf434d0 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/InvalidPartitionException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java @@ -20,24 +20,22 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.HttpUtils; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.WFConstants; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.directconnectivity.HttpUtils; +import com.azure.data.cosmos.directconnectivity.WFConstants; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; -import java.net.URI; import java.util.Map; /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ -public class InvalidPartitionException extends DocumentClientException { +public class InvalidPartitionException extends CosmosClientException { private static final long serialVersionUID = 1L; @@ -83,7 +81,7 @@ public InvalidPartitionException(String message, } private void setSubStatus() { - this.getResponseHeaders().put( + this.responseHeaders().put( WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.NAME_CACHE_IS_STALE)); } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/InvalidPartitionExceptionRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java similarity index 86% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/InvalidPartitionExceptionRetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java index cdd7540ddb08f..01dfc640aa77b 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/InvalidPartitionExceptionRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java @@ -20,14 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.time.Duration; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.FeedOptions; import rx.Single; @@ -53,7 +52,7 @@ public InvalidPartitionExceptionRetryPolicy(RxCollectionCache collectionCache, this.nextPolicy = nextPolicy; // TODO the resource address should be inferred from exception - this.collectionLink = com.microsoft.azure.cosmosdb.internal.Utils.getCollectionName(resourceFullName); + this.collectionLink = com.azure.data.cosmos.internal.Utils.getCollectionName(resourceFullName); this.feedOptions = feedOptions; } @@ -64,7 +63,7 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { @Override public Single shouldRetry(Exception e) { - DocumentClientException clientException = Utils.as(e, DocumentClientException.class); + CosmosClientException clientException = Utils.as(e, CosmosClientException.class); if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.GONE) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.NAME_CACHE_IS_STALE)) { @@ -73,7 +72,7 @@ public Single shouldRetry(Exception e) { //this.clientCollectionCache.Refresh(clientException.ResourceAddress); // TODO: this is blocking. is that fine? if(this.feedOptions != null) { - this.clientCollectionCache.refresh(collectionLink,this.feedOptions.getProperties()); + this.clientCollectionCache.refresh(collectionLink,this.feedOptions.properties()); } else { this.clientCollectionCache.refresh(collectionLink,null); } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/NotFoundException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java similarity index 89% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/NotFoundException.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java index 3e949875c4d2b..67d40708440f0 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/NotFoundException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java @@ -20,13 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.HttpUtils; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.net.URI; @@ -36,7 +35,7 @@ * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ -public class NotFoundException extends DocumentClientException { +public class NotFoundException extends CosmosClientException { private static final long serialVersionUID = 1L; public NotFoundException() { diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ObservableHelper.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ObservableHelper.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java index 80bf892dedcdf..c5bb14f97fa05 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ObservableHelper.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import rx.Observable; import rx.Single; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionIsMigratingException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java similarity index 85% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionIsMigratingException.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java index adf2fe3217cc0..8b07a5c1fea45 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionIsMigratingException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java @@ -20,14 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.HttpUtils; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.WFConstants; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.directconnectivity.HttpUtils; +import com.azure.data.cosmos.directconnectivity.WFConstants; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.util.Map; @@ -36,7 +35,7 @@ * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ -public class PartitionIsMigratingException extends DocumentClientException { +public class PartitionIsMigratingException extends CosmosClientException { private static final long serialVersionUID = 1L; @@ -82,7 +81,7 @@ public PartitionIsMigratingException(String message, } private void setSubStatus() { - this.getResponseHeaders().put( + this.responseHeaders().put( WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.COMPLETING_PARTITION_MIGRATION)); } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionKeyMismatchRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java similarity index 87% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionKeyMismatchRetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java index 45dc11cc0d133..a13a01ed1210c 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionKeyMismatchRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java @@ -20,15 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxClientCollectionCache; +import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.RequestOptions; import rx.Single; @@ -63,7 +62,7 @@ public PartitionKeyMismatchRetryPolicy( this.nextRetryPolicy = nextRetryPolicy; // TODO: this should be retrievable from document client exception. - collectionLink = com.microsoft.azure.cosmosdb.internal.Utils.getCollectionName(resourceFullName); + collectionLink = com.azure.data.cosmos.internal.Utils.getCollectionName(resourceFullName); this.options = options; } @@ -75,7 +74,7 @@ public PartitionKeyMismatchRetryPolicy( /// /// True indicates caller should retry, False otherwise public Single shouldRetry(Exception exception) { - DocumentClientException clientException = Utils.as(exception, DocumentClientException.class) ; + CosmosClientException clientException = Utils.as(exception, CosmosClientException.class) ; if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.BADREQUEST) && @@ -101,7 +100,7 @@ public Single shouldRetry(Exception exception) { /* (non-Javadoc) - * @see com.microsoft.azure.cosmosdb.rx.internal.query.IDocumentClientRetryPolicy#onBeforeSendRequest(rx.Observable) + * @see com.azure.data.cosmos.internal.internal.query.IDocumentClientRetryPolicy#onBeforeSendRequest(rx.Observable) */ @Override public void onBeforeSendRequest(RxDocumentServiceRequest request) { diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionKeyRangeGoneRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java similarity index 83% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionKeyRangeGoneRetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java index 3a2c60a5de245..eaa826d076a66 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionKeyRangeGoneRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java @@ -20,19 +20,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.time.Duration; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.routing.CollectionRoutingMap; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxCollectionCache; -import com.microsoft.azure.cosmosdb.rx.internal.caches.IPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import rx.Observable; import rx.Single; @@ -71,7 +68,7 @@ public PartitionKeyRangeGoneRetryPolicy( /// /// True indicates caller should retry, False otherwise public Single shouldRetry(Exception exception) { - DocumentClientException clientException = Utils.as(exception, DocumentClientException.class); + CosmosClientException clientException = Utils.as(exception, CosmosClientException.class); if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.GONE) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { @@ -88,19 +85,19 @@ public Single shouldRetry(Exception exception) { // AuthorizationTokenType.PrimaryMasterKey) ); if (this.feedOptions != null) { - request.properties = this.feedOptions.getProperties(); + request.properties = this.feedOptions.properties(); } Single collectionObs = this.collectionCache.resolveCollectionAsync(request); Single retryTimeObservable = collectionObs.flatMap(collection -> { - Single routingMapObs = this.partitionKeyRangeCache.tryLookupAsync(collection.getResourceId(), null, request.properties); + Single routingMapObs = this.partitionKeyRangeCache.tryLookupAsync(collection.resourceId(), null, request.properties); Single refreshedRoutingMapObs = routingMapObs.flatMap(routingMap -> { if (routingMap != null) { // Force refresh. return this.partitionKeyRangeCache.tryLookupAsync( - collection.getResourceId(), + collection.resourceId(), routingMap, request.properties); } else { diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionKeyRangeIsSplittingException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java similarity index 85% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionKeyRangeIsSplittingException.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java index c3a564fa083f6..71e29bac82961 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/PartitionKeyRangeIsSplittingException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java @@ -20,14 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.HttpUtils; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.WFConstants; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.directconnectivity.HttpUtils; +import com.azure.data.cosmos.directconnectivity.WFConstants; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import java.util.Map; @@ -36,7 +35,7 @@ * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. */ -public class PartitionKeyRangeIsSplittingException extends DocumentClientException { +public class PartitionKeyRangeIsSplittingException extends CosmosClientException { private static final long serialVersionUID = 1L; @@ -82,7 +81,7 @@ public PartitionKeyRangeIsSplittingException(String message, } private void setSubStatus() { - this.getResponseHeaders().put( + this.responseHeaders().put( WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.COMPLETING_SPLIT)); } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RenameCollectionAwareClientRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java similarity index 90% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RenameCollectionAwareClientRetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java index 613bd70b07d57..cbc952f930104 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RenameCollectionAwareClientRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java @@ -20,13 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxClientCollectionCache; +import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.ISessionContainer; import org.apache.commons.lang3.StringUtils; @@ -64,7 +63,7 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { public Single shouldRetry(Exception e) { return this.retryPolicy.shouldRetry(e).flatMap(shouldRetryResult -> { if (!shouldRetryResult.shouldRetry && !this.hasTriggered) { - DocumentClientException clientException = Utils.as(e, DocumentClientException.class); + CosmosClientException clientException = Utils.as(e, CosmosClientException.class); if (this.request == null) { // someone didn't call OnBeforeSendRequest - nothing we can do @@ -92,7 +91,7 @@ public Single shouldRetry(Exception e) { return collectionObs.flatMap(collectionInfo -> { if (collectionInfo == null) { logger.warn("Can't recover from session unavailable exception because resolving collection name {} returned null", request.getResourceAddress()); - } else if (!StringUtils.isEmpty(oldCollectionRid) && !StringUtils.isEmpty(collectionInfo.getResourceId())) { + } else if (!StringUtils.isEmpty(oldCollectionRid) && !StringUtils.isEmpty(collectionInfo.resourceId())) { return Single.just(ShouldRetryResult.retryAfter(Duration.ZERO)); } return Single.just(shouldRetryResult); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ReplicatedResourceClientUtils.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java similarity index 94% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ReplicatedResourceClientUtils.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java index d1f4429cbe019..a75c5c83fab7b 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ReplicatedResourceClientUtils.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java @@ -20,10 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; +package com.azure.data.cosmos.internal; /** * While this class is public, but it is not part of our published public APIs. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ResetSessionTokenRetryPolicyFactory.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java similarity index 91% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ResetSessionTokenRetryPolicyFactory.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java index 1d6e888c61f52..89273b00427cf 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ResetSessionTokenRetryPolicyFactory.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxClientCollectionCache; +import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; +import com.azure.data.cosmos.ISessionContainer; public class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory { diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ResourceThrottleRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java similarity index 93% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ResourceThrottleRetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java index 8aeb8e037dfb6..e1252acf54c6a 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ResourceThrottleRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java @@ -20,16 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.time.Duration; +import com.azure.data.cosmos.CosmosClientException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; - import rx.Single; /** @@ -107,12 +105,12 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { private Duration checkIfRetryNeeded(Exception exception) { Duration retryDelay = Duration.ZERO; - DocumentClientException dce = Utils.as(exception, DocumentClientException.class); + CosmosClientException dce = Utils.as(exception, CosmosClientException.class); if (dce != null){ if (Exceptions.isStatusCode(dce, HttpConstants.StatusCodes.TOO_MANY_REQUESTS)) { - retryDelay = Duration.ofMillis(dce.getRetryAfterInMilliseconds()); + retryDelay = Duration.ofMillis(dce.retryAfterInMilliseconds()); if (this.backoffDelayFactor > 1) { retryDelay = Duration.ofNanos(retryDelay.toNanos() * this.backoffDelayFactor); } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java similarity index 87% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java index 9ac61a56f3311..713e9068eeda9 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.RetryOptions; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.RetryOptions; /** * While this class is public, but it is not part of our published public APIs. @@ -38,9 +38,9 @@ public class RetryPolicy implements IRetryPolicyFactory { private final RetryOptions retryOptions; public RetryPolicy(GlobalEndpointManager globalEndpointManager, ConnectionPolicy connectionPolicy) { - this.enableEndpointDiscovery = connectionPolicy.getEnableEndpointDiscovery(); + this.enableEndpointDiscovery = connectionPolicy.enableEndpointDiscovery(); this.globalEndpointManager = globalEndpointManager; - this.retryOptions = connectionPolicy.getRetryOptions(); + this.retryOptions = connectionPolicy.retryOptions(); } @Override diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RetryUtils.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RetryUtils.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java index 7432a3ebdef62..4fcf2e16b80c6 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RetryUtils.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.time.Duration; import java.util.concurrent.TimeUnit; @@ -29,9 +29,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.internal.Quadruple; -import com.microsoft.azure.cosmosdb.rx.internal.IRetryPolicy.ShouldRetryResult; - import rx.Observable; import rx.Single; import rx.functions.Func1; @@ -125,7 +122,7 @@ public Single call(Throwable t) { private static Single recurrsiveFunc( Func1, Single> callbackMethod, IRetryPolicy policy, Func1, Single> inBackoffAlternateCallbackMethod, - ShouldRetryResult shouldRetryResult, Duration minBackoffForInBackoffCallback) { + IRetryPolicy.ShouldRetryResult shouldRetryResult, Duration minBackoffForInBackoffCallback) { return callbackMethod.call(shouldRetryResult.policyArg).onErrorResumeNext(toRetryWithAlternateFunc( callbackMethod, policy, inBackoffAlternateCallbackMethod, minBackoffForInBackoffCallback)); @@ -134,7 +131,7 @@ private static Single recurrsiveFunc( private static Func1> recurrsiveWithAlternateFunc( Func1, Single> callbackMethod, IRetryPolicy policy, Func1, Single> inBackoffAlternateCallbackMethod, - ShouldRetryResult shouldRetryResult, StopWatch stopwatch, Duration minBackoffForInBackoffCallback) { + IRetryPolicy.ShouldRetryResult shouldRetryResult, StopWatch stopwatch, Duration minBackoffForInBackoffCallback) { return new Func1>() { @Override diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxGatewayStoreModel.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java similarity index 91% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxGatewayStoreModel.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java index 7de0b323f9d9e..7500a5249e3c4 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxGatewayStoreModel.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java @@ -20,23 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; - - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.PathsHelper; -import com.microsoft.azure.cosmosdb.internal.QueryCompatibilityMode; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.RuntimeConstants; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.HttpUtils; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreResponse; +package com.azure.data.cosmos.internal; + + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.directconnectivity.HttpUtils; +import com.azure.data.cosmos.directconnectivity.StoreResponse; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.HttpMethod; @@ -62,7 +52,6 @@ import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -70,7 +59,7 @@ * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. * - * Used internally to provide functionality to communicate and process response from Gateway in the Azure Cosmos DB database service. + * Used internally to provide functionality to communicate and process response from GATEWAY in the Azure Cosmos DB database service. */ class RxGatewayStoreModel implements RxStoreModel { @@ -398,10 +387,10 @@ private Observable toDocumentServiceResponse(Observab } Exception exception = (Exception) throwable; - if (!(exception instanceof DocumentClientException)) { - // wrap in DocumentClientException + if (!(exception instanceof CosmosClientException)) { + // wrap in CosmosClientException logger.error("Network failure", exception); - DocumentClientException dce = new DocumentClientException(0, exception); + CosmosClientException dce = new CosmosClientException(0, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); return Observable.error(dce); } @@ -412,7 +401,7 @@ private Observable toDocumentServiceResponse(Observab } private void validateOrThrow(RxDocumentServiceRequest request, HttpResponseStatus status, HttpResponseHeaders headers, String body, - InputStream inputStream) throws DocumentClientException { + InputStream inputStream) throws CosmosClientException { int statusCode = status.code(); @@ -422,7 +411,7 @@ private void validateOrThrow(RxDocumentServiceRequest request, HttpResponseStatu body = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { logger.error("Failed to get content from the http response", e); - DocumentClientException dce = new DocumentClientException(0, e); + CosmosClientException dce = new CosmosClientException(0, e); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); throw dce; } finally { @@ -439,7 +428,7 @@ private void validateOrThrow(RxDocumentServiceRequest request, HttpResponseStatu String.format("%s, StatusCode: %s", error.getMessage(), statusCodeString), error.getPartitionedQueryExecutionInfo()); - DocumentClientException dce = new DocumentClientException(statusCode, error, HttpUtils.asMap(headers)); + CosmosClientException dce = new CosmosClientException(statusCode, error, HttpUtils.asMap(headers)); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); throw dce; } @@ -482,7 +471,7 @@ public Observable processMessage(RxDocumentServiceReq return responseObs.onErrorResumeNext( e -> { - DocumentClientException dce = Utils.as(e, DocumentClientException.class); + CosmosClientException dce = Utils.as(e, CosmosClientException.class); if (dce == null) { logger.error("unexpected failure {}", e.getMessage(), e); @@ -490,13 +479,13 @@ public Observable processMessage(RxDocumentServiceReq } if ((!ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) && - (dce.getStatusCode() == HttpConstants.StatusCodes.PRECONDITION_FAILED || - dce.getStatusCode() == HttpConstants.StatusCodes.CONFLICT || + (dce.statusCode() == HttpConstants.StatusCodes.PRECONDITION_FAILED || + dce.statusCode() == HttpConstants.StatusCodes.CONFLICT || ( - dce.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND && + dce.statusCode() == HttpConstants.StatusCodes.NOTFOUND && !Exceptions.isSubStatusCode(dce, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)))) { - this.captureSessionToken(request, dce.getResponseHeaders()); + this.captureSessionToken(request, dce.responseHeaders()); } return Observable.error(dce); @@ -537,9 +526,9 @@ private void applySessionToken(RxDocumentServiceRequest request) { String requestConsistencyLevel = headers.get(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL); boolean sessionConsistency = - this.defaultConsistencyLevel == ConsistencyLevel.Session || + this.defaultConsistencyLevel == ConsistencyLevel.SESSION || (!Strings.isNullOrEmpty(requestConsistencyLevel) - && Strings.areEqual(requestConsistencyLevel, ConsistencyLevel.Session.name())); + && Strings.areEqual(requestConsistencyLevel, ConsistencyLevel.SESSION.name())); if (!sessionConsistency || ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) { return; // Only apply the session token in case of session consistency and when resource is not a master resource diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxStoreModel.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxStoreModel.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java index ca5184c221ed7..9cacda843d096 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxStoreModel.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import rx.Observable; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/SessionContainer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/SessionContainer.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java index 58e4ff4f65f18..04ced6a7c9138 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/SessionContainer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java @@ -21,13 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.rx.internal.ReplicatedResourceClientUtils; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.ISessionContainer; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,7 +35,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; -import static com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import static com.azure.data.cosmos.internal.Utils.ValueHolder; /** * Used internally to cache the collections' session tokens in the Azure Cosmos DB database service. @@ -47,7 +44,7 @@ public final class SessionContainer implements ISessionContainer { private final Logger logger = LoggerFactory.getLogger(SessionContainer.class); /** - * Session token cache that maps collection ResourceID to session tokens + * SESSION token cache that maps collection ResourceID to session tokens */ private final ConcurrentHashMap> collectionResourceIdToSessionTokens = new ConcurrentHashMap<>(); /** @@ -211,7 +208,7 @@ private void setSessionToken(ResourceId resourceId, String collectionName, Strin partitionKeyRangeId = tokenParts[0]; parsedSessionToken = SessionTokenHelper.parse(tokenParts[1]); - logger.trace("Update Session token {} {} {}", resourceId.getUniqueDocumentCollectionId(), collectionName, parsedSessionToken); + logger.trace("UPDATE SESSION token {} {} {}", resourceId.getUniqueDocumentCollectionId(), collectionName, parsedSessionToken); boolean isKnownCollection; @@ -258,7 +255,7 @@ private void addSessionToken(ResourceId resourceId, String partitionKeyRangeId, } return existingSessionTokens.merge(newSessionToken); - } catch (DocumentClientException e) { + } catch (CosmosClientException e) { throw new IllegalStateException(e); } }); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/SessionTokenHelper.java b/gateway/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java similarity index 92% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/SessionTokenHelper.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java index 5906ade34050b..4e4ca7a25406f 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/SessionTokenHelper.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java @@ -21,14 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; - -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.rx.internal.BadRequestException; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.ISessionContainer; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; @@ -38,7 +34,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import static com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import static com.azure.data.cosmos.internal.Utils.ValueHolder; /** * Used internally to provides helper functions to work with session tokens in the Azure Cosmos DB database service. @@ -57,9 +53,9 @@ public static void setOriginalSessionToken(RxDocumentServiceRequest request, Str } } - public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) throws DocumentClientException { + public static void setPartitionLocalSessionToken(RxDocumentServiceRequest request, ISessionContainer sessionContainer) throws CosmosClientException { String originalSessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); - String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); + String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.id(); if (Strings.isNullOrEmpty(partitionKeyRangeId)) { @@ -88,7 +84,7 @@ public static void setPartitionLocalSessionToken(RxDocumentServiceRequest reques private static ISessionToken getLocalSessionToken( RxDocumentServiceRequest request, String globalSessionToken, - String partitionKeyRangeId) throws DocumentClientException { + String partitionKeyRangeId) throws CosmosClientException { if (partitionKeyRangeId == null || partitionKeyRangeId.isEmpty()) { // AddressCache/address resolution didn't produce partition key range id. @@ -176,7 +172,7 @@ static boolean tryParse(String sessionToken, ValueHolder parsedSe } } - public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) throws DocumentClientException { + public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) throws CosmosClientException { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/UserAgentContainer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/UserAgentContainer.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java index 5f11ff50fe5f0..5266b26fba984 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/UserAgentContainer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; /** * Used internally. The user agent object, which is used to track the version of the Java SDK of the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/VectorSessionToken.java b/gateway/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/VectorSessionToken.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java index f3b04712dbda3..08f499f04813a 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/VectorSessionToken.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java @@ -21,13 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.CosmosClientException; import org.apache.commons.collections4.map.UnmodifiableMap; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; @@ -38,10 +35,10 @@ import java.util.Map; import java.util.stream.Collectors; -import static com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import static com.azure.data.cosmos.internal.Utils.ValueHolder; /** - * Models vector clock bases session token. Session token has the following format: + * Models vector clock bases session token. SESSION token has the following format: * {Version}#{GlobalLSN}#{RegionId1}={LocalLsn1}#{RegionId2}={LocalLsn2}....#{RegionIdN}={LocalLsnN} * 'Version' captures the configuration number of the partition which returned this session token. * 'Version' is incremented everytime topology of the partition is updated (say due to Add/Remove/Failover). @@ -134,7 +131,7 @@ public boolean equals(Object obj) { && this.areRegionProgressEqual(other.localLsnByRegion); } - public boolean isValid(ISessionToken otherSessionToken) throws DocumentClientException { + public boolean isValid(ISessionToken otherSessionToken) throws CosmosClientException { VectorSessionToken other = Utils.as(otherSessionToken, VectorSessionToken.class); if (other == null) { @@ -177,7 +174,7 @@ public boolean isValid(ISessionToken otherSessionToken) throws DocumentClientExc } // Merge is commutative operation, so a.Merge(b).Equals(b.Merge(a)) - public ISessionToken merge(ISessionToken obj) throws DocumentClientException { + public ISessionToken merge(ISessionToken obj) throws CosmosClientException { VectorSessionToken other = Utils.as(obj, VectorSessionToken.class); if (other == null) { @@ -258,7 +255,7 @@ private static boolean tryParseSessionToken( globalLsn.v = -1L; if (Strings.isNullOrEmpty(sessionToken)) { - logger.warn("Session token is empty"); + logger.warn("SESSION token is empty"); return false; } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/WebExceptionRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/WebExceptionRetryPolicy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java index 48f61b07ef9eb..b9dd3e52cd1b9 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/WebExceptionRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.WebExceptionUtility; +import com.azure.data.cosmos.directconnectivity.WebExceptionUtility; import org.apache.commons.lang3.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/AsyncCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java similarity index 98% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/AsyncCache.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java index 58ad25c7bd9d6..090b3c139fac8 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/AsyncCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.caches; +package com.azure.data.cosmos.internal.caches; import java.util.concurrent.ConcurrentHashMap; @@ -153,7 +153,7 @@ public void refresh( if (initialLazyValue != null && (initialLazyValue.isSucceeded() || initialLazyValue.isFaulted())) { AsyncLazy newLazyValue = new AsyncLazy<>(singleValueInitFunc); - // Update the new task in the cache, + // UPDATE the new task in the cache, values.merge(key, newLazyValue, (lazyValue1, lazyValu2) -> lazyValue1 == initialLazyValue ? lazyValu2 : lazyValue1); } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/AsyncLazy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/AsyncLazy.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java index 79a2c377b7a1f..ce303a8c88457 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/AsyncLazy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.caches; +package com.azure.data.cosmos.internal.caches; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/IEqualityComparer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/IEqualityComparer.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java index a9cd210edb5f7..3b77b00d96bbc 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/IEqualityComparer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.caches; +package com.azure.data.cosmos.internal.caches; interface IEqualityComparer { boolean areEqual(TValue v1, TValue v2); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/IPartitionKeyRangeCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java similarity index 84% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/IPartitionKeyRangeCache.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java index 1d92cf412dba8..28cc4742fda47 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/IPartitionKeyRangeCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java @@ -20,16 +20,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.caches; +package com.azure.data.cosmos.internal.caches; import java.util.List; import java.util.Map; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.routing.CollectionRoutingMap; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.internal.ICollectionRoutingMapCache; -import com.microsoft.azure.cosmosdb.rx.internal.IRoutingMapProvider; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; +import com.azure.data.cosmos.internal.IRoutingMapProvider; import rx.Single; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/RxClientCollectionCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java similarity index 80% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/RxClientCollectionCache.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java index 64fecf3166ef7..bdf003c8d58ad 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/RxClientCollectionCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java @@ -20,30 +20,30 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.caches; +package com.azure.data.cosmos.internal.caches; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.PathsHelper; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.rx.internal.AuthorizationTokenType; -import com.microsoft.azure.cosmosdb.rx.internal.ClearingSessionContainerClientRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.IDocumentClientRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.IRetryPolicyFactory; -import com.microsoft.azure.cosmosdb.rx.internal.ObservableHelper; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; -import com.microsoft.azure.cosmosdb.rx.internal.RxStoreModel; +import com.azure.data.cosmos.internal.AuthorizationTokenType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.ClearingSessionContainerClientRetryPolicy; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.IRetryPolicyFactory; +import com.azure.data.cosmos.internal.ObservableHelper; +import com.azure.data.cosmos.internal.RxStoreModel; import rx.Observable; import rx.Single; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/RxCollectionCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java similarity index 90% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/RxCollectionCache.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java index e634593434ae9..999c5e31848a6 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/RxCollectionCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java @@ -20,18 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.caches; +package com.azure.data.cosmos.internal.caches; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.StringUtils; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.internal.PathsHelper; -import com.microsoft.azure.cosmosdb.internal.ResourceId; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionException; -import com.microsoft.azure.cosmosdb.rx.internal.NotFoundException; -import com.microsoft.azure.cosmosdb.rx.internal.RMResources; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.ResourceId; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.NotFoundException; import rx.Completable; import rx.Single; @@ -88,10 +88,10 @@ public Single resolveCollectionAsync( // logger.debug( // "Mapped resourceName {} to resourceId {}.", // request.getResourceAddress(), - // collectionInfo.getResourceId()); + // collectionInfo.resourceId()); - request.setResourceId(collection.getResourceId()); - request.requestContext.resolvedCollectionRid = collection.getResourceId(); + request.setResourceId(collection.resourceId()); + request.requestContext.resolvedCollectionRid = collection.resourceId(); return Single.just(collection); }); @@ -125,7 +125,7 @@ public void refresh(String resourceAddress, Map properties) { () -> { Single collectionObs = this.getByNameAsync(resourceFullName, properties); return collectionObs.doOnSuccess(collection -> { - this.collectionInfoByIdCache.set(collection.getResourceId(), collection); + this.collectionInfoByIdCache.set(collection.resourceId(), collection); }); }); } @@ -176,7 +176,7 @@ private Single resolveByNameAsync( () -> { Single collectionObs = this.getByNameAsync(resourceFullName, properties); return collectionObs.doOnSuccess(collection -> { - this.collectionInfoByIdCache.set(collection.getResourceId(), collection); + this.collectionInfoByIdCache.set(collection.resourceId(), collection); }); }); } @@ -190,7 +190,7 @@ private Completable refreshAsync(RxDocumentServiceRequest request) { if (request.requestContext.resolvedCollectionRid != null) { // Here we will issue backend call only if cache wasn't already refreshed (if whatever is there corresponds to previously resolved collection rid). DocumentCollection obsoleteValue = new DocumentCollection(); - obsoleteValue.setResourceId(request.requestContext.resolvedCollectionRid); + obsoleteValue.resourceId(request.requestContext.resolvedCollectionRid); completable = this.collectionInfoByNameCache.getAsync( resourceFullName, @@ -198,7 +198,7 @@ private Completable refreshAsync(RxDocumentServiceRequest request) { () -> { Single collectionObs = this.getByNameAsync(resourceFullName, request.properties); return collectionObs.doOnSuccess(collection -> { - this.collectionInfoByIdCache.set(collection.getResourceId(), collection); + this.collectionInfoByIdCache.set(collection.resourceId(), collection); }); }).toCompletable(); } else { @@ -220,7 +220,7 @@ public boolean areEqual(DocumentCollection left, DocumentCollection right) { return false; } - return StringUtils.equals(left.getResourceId(), right.getResourceId()); + return StringUtils.equals(left.resourceId(), right.resourceId()); } } } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/AggregateDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java similarity index 79% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/AggregateDocumentQueryExecutionContext.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java index 8305732d9ff88..cce589007c151 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/AggregateDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.ArrayList; import java.util.Collection; @@ -31,22 +31,21 @@ import java.util.concurrent.ConcurrentMap; import java.util.function.Function; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.query.QueryItem; -import com.microsoft.azure.cosmosdb.internal.query.aggregation.AggregateOperator; -import com.microsoft.azure.cosmosdb.internal.query.aggregation.Aggregator; -import com.microsoft.azure.cosmosdb.internal.query.aggregation.AverageAggregator; -import com.microsoft.azure.cosmosdb.internal.query.aggregation.CountAggregator; -import com.microsoft.azure.cosmosdb.internal.query.aggregation.MaxAggregator; -import com.microsoft.azure.cosmosdb.internal.query.aggregation.MinAggregator; -import com.microsoft.azure.cosmosdb.internal.query.aggregation.SumAggregator; -import com.microsoft.azure.cosmosdb.QueryMetrics; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.query.aggregation.AggregateOperator; +import com.azure.data.cosmos.internal.query.aggregation.Aggregator; +import com.azure.data.cosmos.internal.query.aggregation.AverageAggregator; +import com.azure.data.cosmos.internal.query.aggregation.CountAggregator; +import com.azure.data.cosmos.internal.query.aggregation.MaxAggregator; +import com.azure.data.cosmos.internal.query.aggregation.MinAggregator; +import com.azure.data.cosmos.internal.query.aggregation.SumAggregator; +import com.azure.data.cosmos.QueryMetrics; import rx.Observable; @@ -98,22 +97,22 @@ public Observable> drainAsync(int maxPageSize) { for(FeedResponse page : superList) { - if (page.getResults().size() == 0) { + if (page.results().size() == 0) { headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, Double.toString(requestCharge)); FeedResponse frp = BridgeInternal.createFeedResponse(aggregateResults, headers); return (FeedResponse) frp; } - Document doc = ((Document)page.getResults().get(0)); - requestCharge += page.getRequestCharge(); + Document doc = ((Document)page.results().get(0)); + requestCharge += page.requestCharge(); QueryItem values = new QueryItem(doc.toJson()); this.aggregator.aggregate(values.getItem()); - for(String key : page.getQueryMetrics().keySet()) { + for(String key : page.queryMetrics().keySet()) { if (queryMetricsMap.containsKey(key)) { - QueryMetrics qm = page.getQueryMetrics().get(key); + QueryMetrics qm = page.queryMetrics().get(key); queryMetricsMap.get(key).add(qm); } else { - queryMetricsMap.put(key, page.getQueryMetrics().get(key)); + queryMetricsMap.put(key, page.queryMetrics().get(key)); } } } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/CompositeContinuationToken.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java similarity index 94% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/CompositeContinuationToken.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java index 050c24b23ab63..bf18b9a748636 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/CompositeContinuationToken.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; -import com.microsoft.azure.cosmosdb.JsonSerializable; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import com.azure.data.cosmos.JsonSerializable; +import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.internal.Utils.ValueHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DefaultDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java similarity index 78% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DefaultDocumentQueryExecutionContext.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java index b29ab978a577e..33af8d8b68699 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DefaultDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java @@ -20,40 +20,40 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.PathsHelper; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.internal.BackoffRetryUtility; -import com.microsoft.azure.cosmosdb.rx.internal.IDocumentClientRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.InvalidPartitionExceptionRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.PartitionKeyRangeGoneRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; -import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxCollectionCache; -import com.microsoft.azure.cosmosdb.rx.internal.caches.IPartitionKeyRangeCache; -import com.microsoft.azure.cosmosdb.internal.query.metrics.ClientSideMetrics; -import com.microsoft.azure.cosmosdb.internal.query.metrics.FetchExecutionRangeAccumulator; -import com.microsoft.azure.cosmosdb.QueryMetrics; -import com.microsoft.azure.cosmosdb.internal.query.metrics.SchedulingStopwatch; -import com.microsoft.azure.cosmosdb.internal.query.metrics.SchedulingTimeSpan; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.internal.BackoffRetryUtility; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.InvalidPartitionExceptionRetryPolicy; +import com.azure.data.cosmos.internal.PartitionKeyRangeGoneRetryPolicy; +import com.azure.data.cosmos.internal.Utils.ValueHolder; +import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; +import com.azure.data.cosmos.internal.query.metrics.FetchExecutionRangeAccumulator; +import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.internal.query.metrics.SchedulingStopwatch; +import com.azure.data.cosmos.internal.query.metrics.SchedulingTimeSpan; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -95,7 +95,7 @@ public DefaultDocumentQueryExecutionContext(IDocumentQueryClient client, Resourc } protected PartitionKeyInternal getPartitionKeyInternal() { - return this.feedOptions.getPartitionKey() == null ? null : feedOptions.getPartitionKey().getInternalPartitionKey(); + return this.feedOptions.partitionKey() == null ? null : feedOptions.partitionKey().getInternalPartitionKey(); } @Override @@ -112,15 +112,15 @@ public Observable> executeAsync() { // The workaround is to try and parse the continuation token as a composite continuation token. // If it is, then we send the query to the gateway with max degree of parallelism to force getting back the query plan - String originalContinuation = newFeedOptions.getRequestContinuation(); + String originalContinuation = newFeedOptions.requestContinuation(); if (isClientSideContinuationToken(originalContinuation)) { // At this point we know we want back a query plan - newFeedOptions.setRequestContinuation(null); - newFeedOptions.setMaxDegreeOfParallelism(Integer.MAX_VALUE); + newFeedOptions.requestContinuation(null); + newFeedOptions.maxDegreeOfParallelism(Integer.MAX_VALUE); } - int maxPageSize = newFeedOptions.getMaxItemCount() != null ? newFeedOptions.getMaxItemCount() : Constants.Properties.DEFAULT_MAX_PAGE_SIZE; + int maxPageSize = newFeedOptions.maxItemCount() != null ? newFeedOptions.maxItemCount() : Constants.Properties.DEFAULT_MAX_PAGE_SIZE; Func2 createRequestFunc = (continuationToken, pageSize) -> this.createRequestAsync(continuationToken, pageSize); @@ -165,20 +165,20 @@ protected Func1>> executeIn }, finalRetryPolicyInstance).toObservable() .map(tFeedResponse -> { this.fetchSchedulingMetrics.stop(); - this.fetchExecutionRangeAccumulator.endFetchRange(tFeedResponse.getActivityId(), - tFeedResponse.getResults().size(), + this.fetchExecutionRangeAccumulator.endFetchRange(tFeedResponse.activityId(), + tFeedResponse.results().size(), this.retries); ImmutablePair schedulingTimeSpanMap = new ImmutablePair<>(DEFAULT_PARTITION_KEY_RANGE_ID, this.fetchSchedulingMetrics.getElapsedTime()); - if (!StringUtils.isEmpty(tFeedResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS))) { + if (!StringUtils.isEmpty(tFeedResponse.responseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS))) { QueryMetrics qm = - BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(tFeedResponse.getResponseHeaders() + BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(tFeedResponse.responseHeaders() .get(HttpConstants.HttpHeaders.QUERY_METRICS), new ClientSideMetrics(this.retries, - tFeedResponse.getRequestCharge(), + tFeedResponse.requestCharge(), this.fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap)), - tFeedResponse.getActivityId()); + tFeedResponse.activityId()); BridgeInternal.putQueryMetricsIntoMap(tFeedResponse, DEFAULT_PARTITION_KEY_RANGE_ID, qm); } return tFeedResponse; @@ -193,7 +193,7 @@ private Single> executeOnceAsync(IDocumentClientRetryPolicy retr // The code leaves some temporary garbage in request (in RequestContext etc.), // which shold be erased during retries. - RxDocumentServiceRequest request = this.createRequestAsync(continuationToken, this.feedOptions.getMaxItemCount()); + RxDocumentServiceRequest request = this.createRequestAsync(continuationToken, this.feedOptions.maxItemCount()); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } @@ -237,8 +237,8 @@ public RxDocumentServiceRequest createRequestAsync(String continuationToken, Int this.query, this.getPartitionKeyInternal()); - if (!StringUtils.isEmpty(feedOptions.getPartitionKeyRangeIdInternal())) { - request.routeTo(new PartitionKeyRangeIdentity(feedOptions.getPartitionKeyRangeIdInternal())); + if (!StringUtils.isEmpty(feedOptions.partitionKeyRangeIdInternal())) { + request.routeTo(new PartitionKeyRangeIdentity(feedOptions.partitionKeyRangeIdInternal())); } return request; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentProducer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java similarity index 82% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentProducer.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java index 37303c96ad40b..0743397c3b2f3 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentProducer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.ArrayList; import java.util.Arrays; @@ -28,31 +28,24 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.IDocumentClientRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.ObservableHelper; -import com.microsoft.azure.cosmosdb.internal.query.metrics.ClientSideMetrics; -import com.microsoft.azure.cosmosdb.internal.query.metrics.FetchExecutionRangeAccumulator; -import com.microsoft.azure.cosmosdb.QueryMetrics; -import com.microsoft.azure.cosmosdb.QueryMetricsConstants; -import com.microsoft.azure.cosmosdb.internal.query.metrics.SchedulingStopwatch; -import com.microsoft.azure.cosmosdb.internal.query.metrics.SchedulingTimeSpan; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.internal.Exceptions; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.ObservableHelper; +import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; +import com.azure.data.cosmos.internal.query.metrics.FetchExecutionRangeAccumulator; +import com.azure.data.cosmos.internal.query.metrics.SchedulingStopwatch; +import com.azure.data.cosmos.internal.query.metrics.SchedulingTimeSpan; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.internal.Exceptions; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.internal.Utils; import rx.Observable; import rx.Single; @@ -86,19 +79,19 @@ class DocumentProducerFeedResponse { } void populatePartitionedQueryMetrics() { - String queryMetricsDelimitedString = pageResult.getResponseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); + String queryMetricsDelimitedString = pageResult.responseHeaders().get(HttpConstants.HttpHeaders.QUERY_METRICS); if (!StringUtils.isEmpty(queryMetricsDelimitedString)) { - queryMetricsDelimitedString += String.format(";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.getRequestCharge()); + queryMetricsDelimitedString += String.format(";%s=%.2f", QueryMetricsConstants.RequestCharge, pageResult.requestCharge()); ImmutablePair schedulingTimeSpanMap = - new ImmutablePair<>(targetRange.getId(), fetchSchedulingMetrics.getElapsedTime()); + new ImmutablePair<>(targetRange.id(), fetchSchedulingMetrics.getElapsedTime()); QueryMetrics qm =BridgeInternal.createQueryMetricsFromDelimitedStringAndClientSideMetrics(queryMetricsDelimitedString, new ClientSideMetrics(retries, - pageResult.getRequestCharge(), + pageResult.requestCharge(), fetchExecutionRangeAccumulator.getExecutionRanges(), Arrays.asList(schedulingTimeSpanMap) - ), pageResult.getActivityId()); - BridgeInternal.putQueryMetricsIntoMap(pageResult, targetRange.getId(), qm); + ), pageResult.activityId()); + BridgeInternal.putQueryMetricsIntoMap(pageResult, targetRange.id(), qm); } } } @@ -142,7 +135,7 @@ public DocumentProducer( this.fetchSchedulingMetrics = new SchedulingStopwatch(); this.fetchSchedulingMetrics.ready(); - this.fetchExecutionRangeAccumulator = new FetchExecutionRangeAccumulator(targetRange.getId()); + this.fetchExecutionRangeAccumulator = new FetchExecutionRangeAccumulator(targetRange.id()); this.executeRequestFuncWithRetries = request -> { retries = -1; @@ -163,7 +156,7 @@ public DocumentProducer( this.correlatedActivityId = correlatedActivityId; this.feedOptions = feedOptions != null ? feedOptions : new FeedOptions(); - this.feedOptions.setRequestContinuation(initialContinuationToken); + this.feedOptions.requestContinuation(initialContinuationToken); this.lastResponseContinuationToken = initialContinuationToken; this.resourceType = resourceType; this.targetRange = targetRange; @@ -185,9 +178,9 @@ public Observable produceAsync() { top, pageSize) .map(rsp -> { - lastResponseContinuationToken = rsp.getResponseContinuation(); - this.fetchExecutionRangeAccumulator.endFetchRange(rsp.getActivityId(), - rsp.getResults().size(), + lastResponseContinuationToken = rsp.continuationToken(); + this.fetchExecutionRangeAccumulator.endFetchRange(rsp.activityId(), + rsp.results().size(), this.retries); this.fetchSchedulingMetrics.stop(); return rsp;}); @@ -197,7 +190,7 @@ public Observable produceAsync() { private Observable splitProof(Observable sourceFeedResponseObservable) { return sourceFeedResponseObservable.onErrorResumeNext( t -> { - DocumentClientException dce = Utils.as(t, DocumentClientException.class); + CosmosClientException dce = Utils.as(t, CosmosClientException.class); if (dce == null || !isSplit(dce)) { logger.error("Unexpected failure", t); return Observable.error(t); @@ -261,10 +254,10 @@ protected DocumentProducer createChildDocumentProducerOnSplit( } private Single> getReplacementRanges(Range range) { - return client.getPartitionKeyRangeCache().tryGetOverlappingRangesAsync(collectionRid, range, true, feedOptions.getProperties()); + return client.getPartitionKeyRangeCache().tryGetOverlappingRangesAsync(collectionRid, range, true, feedOptions.properties()); } - private boolean isSplit(DocumentClientException e) { + private boolean isSplit(CosmosClientException e) { return Exceptions.isPartitionSplit(e); } } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentQueryExecutionContextBase.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java similarity index 81% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentQueryExecutionContextBase.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java index 3692ee46e0f13..23b4b6967ebbb 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentQueryExecutionContextBase.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java @@ -20,32 +20,32 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.SqlParameterCollection; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.RuntimeConstants.MediaTypes; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.rx.internal.ReplicatedResourceClientUtils; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.SqlParameterCollection; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RuntimeConstants.MediaTypes; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.ReplicatedResourceClientUtils; +import com.azure.data.cosmos.internal.Utils; import rx.Observable; import rx.Single; @@ -87,7 +87,7 @@ protected DocumentQueryExecutionContextBase(IDocumentQueryClient client, Resourc public String getPartitionKeyId() { // TODO Auto-generated method stub - return this.feedOptions.getPartitionKeyRangeIdInternal(); + return this.feedOptions.partitionKeyRangeIdInternal(); } public RxDocumentServiceRequest createDocumentServiceRequest(Map requestHeaders, @@ -135,8 +135,8 @@ protected Single> getFeedResponse(Single createCommonHeadersAsync(FeedOptions feedOptions) { ConsistencyLevel defaultConsistencyLevel = this.client.getDefaultConsistencyLevelAsync(); ConsistencyLevel desiredConsistencyLevel = this.client.getDesiredConsistencyLevelAsync(); - if (!Strings.isNullOrEmpty(feedOptions.getSessionToken()) + if (!Strings.isNullOrEmpty(feedOptions.sessionToken()) && !ReplicatedResourceClientUtils.isReadingFromMaster(this.resourceTypeEnum, OperationType.ReadFeed)) { - if (defaultConsistencyLevel == ConsistencyLevel.Session - || (desiredConsistencyLevel == ConsistencyLevel.Session)) { + if (defaultConsistencyLevel == ConsistencyLevel.SESSION + || (desiredConsistencyLevel == ConsistencyLevel.SESSION)) { // Query across partitions is not supported today. Master resources (for e.g., // database) // can span across partitions, whereas server resources (viz: collection, @@ -167,44 +167,44 @@ public Map createCommonHeadersAsync(FeedOptions feedOptions) { // irrespective of the chosen replica. // For server resources, which don't span partitions, specify the session token // for correct replica to be chosen for servicing the query result. - requestHeaders.put(HttpConstants.HttpHeaders.SESSION_TOKEN, feedOptions.getSessionToken()); + requestHeaders.put(HttpConstants.HttpHeaders.SESSION_TOKEN, feedOptions.sessionToken()); } } - requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, feedOptions.getRequestContinuation()); + requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, feedOptions.requestContinuation()); requestHeaders.put(HttpConstants.HttpHeaders.IS_QUERY, Strings.toString(true)); // Flow the pageSize only when we are not doing client eval - if (feedOptions.getMaxItemCount() != null && feedOptions.getMaxItemCount() > 0) { - requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Strings.toString(feedOptions.getMaxItemCount())); + if (feedOptions.maxItemCount() != null && feedOptions.maxItemCount() > 0) { + requestHeaders.put(HttpConstants.HttpHeaders.PAGE_SIZE, Strings.toString(feedOptions.maxItemCount())); } - if (feedOptions.getEnableCrossPartitionQuery() != null) { + if (feedOptions.enableCrossPartitionQuery() != null) { requestHeaders.put(HttpConstants.HttpHeaders.ENABLE_CROSS_PARTITION_QUERY, - Strings.toString(feedOptions.getEnableCrossPartitionQuery())); + Strings.toString(feedOptions.enableCrossPartitionQuery())); } - if (feedOptions.getMaxDegreeOfParallelism() != 0) { + if (feedOptions.maxDegreeOfParallelism() != 0) { requestHeaders.put(HttpConstants.HttpHeaders.PARALLELIZE_CROSS_PARTITION_QUERY, Strings.toString(true)); } - if (this.feedOptions.getEnableCrossPartitionQuery() != null) { + if (this.feedOptions.enableCrossPartitionQuery() != null) { requestHeaders.put(HttpConstants.HttpHeaders.ENABLE_SCAN_IN_QUERY, - Strings.toString(this.feedOptions.getEnableCrossPartitionQuery())); + Strings.toString(this.feedOptions.enableCrossPartitionQuery())); } - if (this.feedOptions.getResponseContinuationTokenLimitInKb() > 0) { + if (this.feedOptions.responseContinuationTokenLimitInKb() > 0) { requestHeaders.put(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, - Strings.toString(feedOptions.getResponseContinuationTokenLimitInKb())); + Strings.toString(feedOptions.responseContinuationTokenLimitInKb())); } if (desiredConsistencyLevel != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, desiredConsistencyLevel.name()); } - if(feedOptions.getPopulateQueryMetrics()){ - requestHeaders.put(HttpConstants.HttpHeaders.POPULATE_QUERY_METRICS, String.valueOf(feedOptions.getPopulateQueryMetrics())); + if(feedOptions.populateQueryMetrics()){ + requestHeaders.put(HttpConstants.HttpHeaders.POPULATE_QUERY_METRICS, String.valueOf(feedOptions.populateQueryMetrics())); } return requestHeaders; @@ -233,7 +233,7 @@ public void populatePartitionKeyRangeInfo(RxDocumentServiceRequest request, Part } if (this.resourceTypeEnum.isPartitioned()) { - request.routeTo(new PartitionKeyRangeIdentity(collectionRid, range.getId())); + request.routeTo(new PartitionKeyRangeIdentity(collectionRid, range.id())); } } @@ -244,7 +244,7 @@ private RxDocumentServiceRequest createQueryDocumentServiceRequest(Map 0, "query.parameters", "Unsupported argument in query compatibility mode '%s'", this.client.getQueryCompatibilityMode().toString()); @@ -255,7 +255,7 @@ private RxDocumentServiceRequest createQueryDocumentServiceRequest(Map resolveCollection(IDocumentQueryClient OperationType.Query, resourceTypeEnum, resourceLink, null - // TODO AuthorizationTokenType.Invalid) + // TODO AuthorizationTokenType.INVALID) ); //this request doesnt actually go to server return collectionCache.resolveCollectionAsync(request); } @@ -84,13 +82,13 @@ public static Observable> proxyQueryExecutionContext = collectionObs.flatMap(collection -> { - if (feedOptions != null && feedOptions.getPartitionKey() != null && feedOptions.getPartitionKey().equals(PartitionKey.None)) { - feedOptions.setPartitionKey(BridgeInternal.getPartitionKey(BridgeInternal.getNonePartitionKey(collection.getPartitionKey()))); + if (feedOptions != null && feedOptions.partitionKey() != null && feedOptions.partitionKey().equals(PartitionKey.None)) { + feedOptions.partitionKey(BridgeInternal.getPartitionKey(BridgeInternal.getNonePartitionKey(collection.getPartitionKey()))); } return ProxyDocumentQueryExecutionContext.createAsync( client, @@ -120,10 +118,10 @@ public static Observable 0, "MaxItemCount", "Invalid MaxItemCount %s", initialPageSize); + (initialPageSize > 0, "MaxItemCount", "INVALID MaxItemCount %s", initialPageSize); if (validationError != null) { return Observable.error(validationError); } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ExceptionHelper.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ExceptionHelper.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java index 1bf8481c9add2..b34c251fc7643 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ExceptionHelper.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.concurrent.ExecutionException; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/Fetcher.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java similarity index 88% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/Fetcher.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java index 07f5e6daad9fa..4f12105383908 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/Fetcher.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java @@ -21,17 +21,17 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.FeedOptionsBase; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.FeedOptionsBase; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; import rx.Observable; import rx.functions.Func1; @@ -60,7 +60,7 @@ public Fetcher(Func2 createRequestFun this.executeFunc = executeFunc; this.isChangeFeed = isChangeFeed; - this.continuationToken = options.getRequestContinuation(); + this.continuationToken = options.requestContinuation(); this.top = top; if (top == -1) { this.maxItemCount = maxItemCount; @@ -81,9 +81,9 @@ public Observable> nextPage() { } private void updateState(FeedResponse response) { - continuationToken = response.getResponseContinuation(); + continuationToken = response.continuationToken(); if (top != -1) { - top -= response.getResults().size(); + top -= response.results().size(); if (top < 0) { // this shouldn't happen // this means backend retrieved more items than requested @@ -108,7 +108,7 @@ private RxDocumentServiceRequest createRequest() { if (!shouldFetchMore) { // this should never happen logger.error("invalid state, trying to fetch more after completion"); - throw new IllegalStateException("Invalid state, trying to fetch more after completion"); + throw new IllegalStateException("INVALID state, trying to fetch more after completion"); } return createRequestFunc.call(continuationToken, maxItemCount); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/IDocumentQueryClient.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java similarity index 83% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/IDocumentQueryClient.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java index 3ac0164717307..99358069c2a8f 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/IDocumentQueryClient.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java @@ -20,14 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.rx.internal.IRetryPolicyFactory; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxCollectionCache; -import com.microsoft.azure.cosmosdb.rx.internal.caches.IPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.internal.IRetryPolicyFactory; import rx.Single; @@ -76,13 +76,13 @@ public interface IDocumentQueryClient { /// enum QueryCompatibilityMode { ///

- /// Default (latest) query format. + /// DEFAULT (latest) query format. /// Default, /// /// Query (application/query+json). - /// Default. + /// DEFAULT. /// Query, diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/IDocumentQueryExecutionComponent.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java similarity index 90% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/IDocumentQueryExecutionComponent.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java index b1a260e549112..21db3d2249cee 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/IDocumentQueryExecutionComponent.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Resource; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; import rx.Observable; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/IDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java similarity index 90% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/IDocumentQueryExecutionContext.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java index bb2cd7f1787a4..f26e61a9ca83c 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/IDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Resource; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; import rx.Observable; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ItemComparator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ItemComparator.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java index a3f35ee181f37..843e367d6906e 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ItemComparator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.Comparator; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ItemType.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java similarity index 96% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ItemType.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java index 508e8f7cdd9da..56b90491c7835 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ItemType.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query; +package com.azure.data.cosmos.internal.query; public enum ItemType { NoValue(0x0), Null(0x1), Boolean(0x2), Number(0x4), String(0x5); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ItemTypeHelper.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java similarity index 94% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ItemTypeHelper.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java index 9798739b6ea51..9daed7e1b118c 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/ItemTypeHelper.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query; +package com.azure.data.cosmos.internal.query; -import com.microsoft.azure.cosmosdb.Undefined; +import com.azure.data.cosmos.Undefined; public final class ItemTypeHelper { public static ItemType getOrderByItemType(Object obj) { diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByContinuationToken.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java similarity index 96% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByContinuationToken.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java index 79b04551db6b5..08f2c477ed6ec 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByContinuationToken.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.ArrayList; import java.util.List; @@ -31,9 +31,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; -import com.microsoft.azure.cosmosdb.JsonSerializable; -import com.microsoft.azure.cosmosdb.internal.query.QueryItem; -import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import com.azure.data.cosmos.JsonSerializable; +import com.azure.data.cosmos.internal.Utils.ValueHolder; /** * While this class is public, but it is not part of our published public APIs. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByDocumentProducer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java similarity index 84% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByDocumentProducer.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java index 8d36a6ce8f68c..1a656332fb45e 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByDocumentProducer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java @@ -20,27 +20,27 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.internal.query.orderbyquery.OrderByRowResult; -import com.microsoft.azure.cosmosdb.internal.query.orderbyquery.OrderbyRowComparer; -import com.microsoft.azure.cosmosdb.rx.internal.IDocumentClientRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; +import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.Utils; -import com.microsoft.azure.cosmosdb.QueryMetrics; +import com.azure.data.cosmos.QueryMetrics; import rx.Observable; import rx.functions.Func0; import rx.functions.Func1; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java similarity index 90% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByDocumentQueryExecutionContext.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java index 64edee55c03c4..a34ac6091ff22 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.ArrayList; import java.util.Collection; @@ -32,30 +32,20 @@ import java.util.concurrent.ConcurrentMap; import java.util.function.Function; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.tuple.ImmutablePair; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.query.PartitionedQueryExecutionInfo; -import com.microsoft.azure.cosmosdb.internal.query.QueryItem; -import com.microsoft.azure.cosmosdb.internal.query.SortOrder; -import com.microsoft.azure.cosmosdb.internal.query.orderbyquery.OrderByRowResult; -import com.microsoft.azure.cosmosdb.internal.query.orderbyquery.OrderbyRowComparer; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.internal.IDocumentClientRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; -import com.microsoft.azure.cosmosdb.QueryMetrics; -import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; +import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; +import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.Utils.ValueHolder; import rx.Observable; import rx.Observable.Transformer; @@ -135,10 +125,10 @@ public static Observable sortOrders, Collection orderByExpressions, int initialPageSize, - String continuationToken) throws DocumentClientException { + String continuationToken) throws CosmosClientException { if (continuationToken == null) { // First iteration so use null continuation tokens and "true" filters Map partitionKeyRangeToContinuationToken = new HashMap(); @@ -160,18 +150,18 @@ private void initialize( super.initialize(collectionRid, partitionKeyRangeToContinuationToken, initialPageSize, - new SqlQuerySpec(querySpec.getQueryText().replace(FormatPlaceHolder, + new SqlQuerySpec(querySpec.queryText().replace(FormatPlaceHolder, True), - querySpec.getParameters())); + querySpec.parameters())); } else { // Check to see if order by continuation token is a valid JSON. OrderByContinuationToken orderByContinuationToken; ValueHolder outOrderByContinuationToken = new ValueHolder(); if (!OrderByContinuationToken.tryParse(continuationToken, outOrderByContinuationToken)) { - String message = String.format("Invalid JSON in continuation token %s for OrderBy~Context", + String message = String.format("INVALID JSON in continuation token %s for OrderBy~Context", continuationToken); - throw new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + throw new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, message); } @@ -181,9 +171,9 @@ private void initialize( .getCompositeContinuationToken(); // Check to see if the ranges inside are valid if (compositeContinuationToken.getRange().isEmpty()) { - String message = String.format("Invalid Range in the continuation token %s for OrderBy~Context.", + String message = String.format("INVALID RANGE in the continuation token %s for OrderBy~Context.", continuationToken); - throw new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + throw new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, message); } @@ -251,16 +241,16 @@ private void initializeRangeWithContinuationTokenAndFilter( super.initialize(collectionRid, partitionKeyRangeToContinuationToken, initialPageSize, - new SqlQuerySpec(querySpec.getQueryText().replace(FormatPlaceHolder, + new SqlQuerySpec(querySpec.queryText().replace(FormatPlaceHolder, filter), - querySpec.getParameters())); + querySpec.parameters())); } private ImmutablePair GetFiltersForPartitions( OrderByContinuationToken orderByContinuationToken, List partitionKeyRanges, List sortOrders, - Collection orderByExpressions) throws DocumentClientException { + Collection orderByExpressions) throws CosmosClientException { // Find the partition key range we left off on int startIndex = this.FindTargetRangeAndExtractContinuationTokens(partitionKeyRanges, orderByContinuationToken.getCompositeContinuationToken().getRange()); @@ -319,9 +309,9 @@ private OrderByDocumentQueryExecutionContext.FormattedFilterInfo GetFormatted // Suppose the query is SELECT* FROM c ORDER BY c.string ASC // And we left off on partition N with the value "B" // Then - // All the partitions to the left will have finished reading "B" + // ALL the partitions to the left will have finished reading "B" // Partition N is still reading "B" - // All the partitions to the right have let to read a "B + // ALL the partitions to the right have let to read a "B // Therefore the filters should be // > "B" , >= "B", and >= "B" respectively // Repeat the same logic for DESC and you will get @@ -440,12 +430,12 @@ private static Map headerResponse( private FeedResponse> addOrderByContinuationToken( FeedResponse> page, String orderByContinuationToken) { - Map headers = new HashMap<>(page.getResponseHeaders()); + Map headers = new HashMap<>(page.responseHeaders()); headers.put(HttpConstants.HttpHeaders.CONTINUATION, orderByContinuationToken); - return BridgeInternal.createFeedResponseWithQueryMetrics(page.getResults(), + return BridgeInternal.createFeedResponseWithQueryMetrics(page.results(), headers, - page.getQueryMetrics()); + page.queryMetrics()); } @Override @@ -481,7 +471,7 @@ public Observable> call( return Observable.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(), null)); })) - // Create pairs from the stream to allow the observables downstream to "peek" + // CREATE pairs from the stream to allow the observables downstream to "peek" // 1, 2, 3, null -> (null, 1), (1, 2), (2, 3), (3, null) .map(orderByRowResults -> { ImmutablePair>, FeedResponse>> previousCurrent = new ImmutablePair>, FeedResponse>>( @@ -498,7 +488,7 @@ public Observable> call( FeedResponse> next = currentNext.right; FeedResponse> page; - if (next.getResults().size() == 0) { + if (next.results().size() == 0) { // No more pages no send current page with null continuation token page = current; page = this.addOrderByContinuationToken(page, @@ -507,7 +497,7 @@ public Observable> call( // Give the first page but use the first value in the next page to generate the // continuation token page = current; - List> results = next.getResults(); + List> results = next.results(); OrderByRowResult firstElementInNextPage = results.get(0); String orderByContinuationToken = this.orderByContinuationTokenCallback .apply(firstElementInNextPage); @@ -519,13 +509,13 @@ public Observable> call( }).map(feedOfOrderByRowResults -> { // FeedResponse> to FeedResponse List unwrappedResults = new ArrayList(); - for (OrderByRowResult orderByRowResult : feedOfOrderByRowResults.getResults()) { + for (OrderByRowResult orderByRowResult : feedOfOrderByRowResults.results()) { unwrappedResults.add(orderByRowResult.getPayload()); } return BridgeInternal.createFeedResponseWithQueryMetrics(unwrappedResults, - feedOfOrderByRowResults.getResponseHeaders(), - feedOfOrderByRowResults.getQueryMetrics()); + feedOfOrderByRowResults.responseHeaders(), + feedOfOrderByRowResults.queryMetrics()); }).switchIfEmpty(Observable.defer(() -> { // create an empty page if there is no result return Observable.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(), @@ -578,13 +568,13 @@ public Observable> drainAsync( @Override public Observable> executeAsync() { - return drainAsync(feedOptions.getMaxItemCount()); + return drainAsync(feedOptions.maxItemCount()); } private String getContinuationToken( OrderByRowResult orderByRowResult) { // rid - String rid = orderByRowResult.getResourceId(); + String rid = orderByRowResult.resourceId(); // CompositeContinuationToken String backendContinuationToken = orderByRowResult.getSourceBackendContinuationToken(); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByUtils.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java similarity index 89% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByUtils.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java index e7eb77377b7f1..614668acd8ea4 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/OrderByUtils.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java @@ -20,27 +20,24 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; +import com.azure.data.cosmos.internal.BadRequestException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.github.davidmoten.rx.Transformers; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.internal.ResourceId; -import com.microsoft.azure.cosmosdb.internal.query.ItemComparator; -import com.microsoft.azure.cosmosdb.internal.query.QueryItem; -import com.microsoft.azure.cosmosdb.internal.query.SortOrder; -import com.microsoft.azure.cosmosdb.internal.query.orderbyquery.OrderByRowResult; -import com.microsoft.azure.cosmosdb.internal.query.orderbyquery.OrderbyRowComparer; -import com.microsoft.azure.cosmosdb.QueryMetrics; - -import com.microsoft.azure.cosmosdb.rx.internal.BadRequestException; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.ResourceId; +import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; +import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; +import com.azure.data.cosmos.QueryMetrics; + import org.apache.commons.lang3.tuple.Pair; import rx.Observable; import rx.Observable.Transformer; @@ -92,20 +89,20 @@ public PageToItemTransformer(Class klass, RequestChargeTracker tracker, Map> call(Observable.DocumentProducerFeedResponse> source) { return source.flatMap(documentProducerFeedResponse -> { - for (String key : documentProducerFeedResponse.pageResult.getQueryMetrics().keySet()) { + for (String key : documentProducerFeedResponse.pageResult.queryMetrics().keySet()) { if (queryMetricsMap.containsKey(key)) { - QueryMetrics qm = documentProducerFeedResponse.pageResult.getQueryMetrics().get(key); + QueryMetrics qm = documentProducerFeedResponse.pageResult.queryMetrics().get(key); queryMetricsMap.get(key).add(qm); } else { - queryMetricsMap.put(key, documentProducerFeedResponse.pageResult.getQueryMetrics().get(key)); + queryMetricsMap.put(key, documentProducerFeedResponse.pageResult.queryMetrics().get(key)); } } - List results = documentProducerFeedResponse.pageResult.getResults(); - OrderByContinuationToken orderByContinuationToken = targetRangeToOrderByContinuationTokenMap.get(documentProducerFeedResponse.sourcePartitionKeyRange.getId()); + List results = documentProducerFeedResponse.pageResult.results(); + OrderByContinuationToken orderByContinuationToken = targetRangeToOrderByContinuationTokenMap.get(documentProducerFeedResponse.sourcePartitionKeyRange.id()); if (orderByContinuationToken != null) { Pair booleanResourceIdPair = ResourceId.tryParse(orderByContinuationToken.getRid()); if (!booleanResourceIdPair.getLeft()) { - return Observable.error(new BadRequestException(String.format("Invalid Rid in the continuation token %s for OrderBy~Context.", + return Observable.error(new BadRequestException(String.format("INVALID Rid in the continuation token %s for OrderBy~Context.", orderByContinuationToken.getCompositeContinuationToken().getToken()))); } ResourceId continuationTokenRid = booleanResourceIdPair.getRight(); @@ -141,7 +138,7 @@ public Observable> call(Observable.Docum // If there is a tie in the sort order the documents should be in _rid order in the same direction as the first order by field. // So if it's ORDER BY c.age ASC, c.name DESC the _rids are ASC // If ti's ORDER BY c.age DESC, c.name DESC the _rids are DESC - cmp = (continuationTokenRid.getDocument() - ResourceId.tryParse(tOrderByRowResult.getResourceId()).getRight().getDocument()); + cmp = (continuationTokenRid.getDocument() - ResourceId.tryParse(tOrderByRowResult.resourceId()).getRight().getDocument()); if (sortOrders.iterator().next().equals(SortOrder.Descending)) { cmp = -cmp; @@ -155,14 +152,14 @@ public Observable> call(Observable.Docum } - tracker.addCharge(documentProducerFeedResponse.pageResult.getRequestCharge()); + tracker.addCharge(documentProducerFeedResponse.pageResult.requestCharge()); Observable x = Observable.from(results); return x.map(r -> new OrderByRowResult( klass, r.toJson(), documentProducerFeedResponse.sourcePartitionKeyRange, - documentProducerFeedResponse.pageResult.getResponseContinuation())); + documentProducerFeedResponse.pageResult.continuationToken())); }, 1); } } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/Paginator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java similarity index 92% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/Paginator.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java index 45ec5692e769a..d042f7a8d0f1f 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/Paginator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java @@ -20,14 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedOptionsBase; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedOptionsBase; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ParallelDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java similarity index 88% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ParallelDocumentQueryExecutionContext.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java index f7fe88c344548..231edd075b6d7 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ParallelDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.ArrayList; import java.util.HashMap; @@ -29,23 +29,16 @@ import java.util.UUID; import java.util.stream.Collectors; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.tuple.ImmutablePair; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.RequestChargeTracker; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.query.PartitionedQueryExecutionInfo; -import com.microsoft.azure.cosmosdb.rx.internal.IDocumentClientRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; -import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.Utils.ValueHolder; import rx.Observable; import rx.Observable.Transformer; @@ -109,9 +102,9 @@ public static Observable targetRanges, int initialPageSize, - String continuationToken) throws DocumentClientException { + String continuationToken) throws CosmosClientException { // Generate the corresponding continuation token map. Map partitionKeyRangeToContinuationTokenMap = new HashMap(); if (continuationToken == null) { @@ -136,17 +129,17 @@ private void initialize( // If a continuation token is given then we need to figure out partition key // range it maps to // in order to filter the partition key ranges. - // For example if suppliedCompositeContinuationToken.Range.Min == - // partition3.Range.Min, + // For example if suppliedCompositeContinuationToken.RANGE.Min == + // partition3.RANGE.Min, // then we know that partitions 0, 1, 2 are fully drained. // Check to see if composite continuation token is a valid JSON. ValueHolder outCompositeContinuationToken = new ValueHolder(); if (!CompositeContinuationToken.tryParse(continuationToken, outCompositeContinuationToken)) { - String message = String.format("Invalid JSON in continuation token %s for Parallel~Context", + String message = String.format("INVALID JSON in continuation token %s for Parallel~Context", continuationToken); - throw new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + throw new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, message); } @@ -177,7 +170,7 @@ private void initialize( private List getPartitionKeyRangesForContinuation( CompositeContinuationToken compositeContinuationToken, - List partitionKeyRanges) throws DocumentClientException { + List partitionKeyRanges) throws CosmosClientException { // Find the partition key range we left off on int startIndex = this.FindTargetRangeAndExtractContinuationTokens(partitionKeyRanges, compositeContinuationToken.getRange()); @@ -210,14 +203,14 @@ private DocumentProducer.DocumentProducerFeedResponse plusCharge( DocumentProducer.DocumentProducerFeedResponse documentProducerFeedResponse, double charge) { FeedResponse page = documentProducerFeedResponse.pageResult; - Map headers = new HashMap<>(page.getResponseHeaders()); - double pageCharge = page.getRequestCharge(); + Map headers = new HashMap<>(page.responseHeaders()); + double pageCharge = page.requestCharge(); pageCharge += charge; headers.put(HttpConstants.HttpHeaders.REQUEST_CHARGE, String.valueOf(pageCharge)); - FeedResponse newPage = BridgeInternal.createFeedResponseWithQueryMetrics(page.getResults(), + FeedResponse newPage = BridgeInternal.createFeedResponseWithQueryMetrics(page.results(), headers, - page.getQueryMetrics()); + page.queryMetrics()); documentProducerFeedResponse.pageResult = newPage; return documentProducerFeedResponse; } @@ -226,12 +219,12 @@ private DocumentProducer.DocumentProducerFeedResponse addCompositeContinuatio DocumentProducer.DocumentProducerFeedResponse documentProducerFeedResponse, String compositeContinuationToken) { FeedResponse page = documentProducerFeedResponse.pageResult; - Map headers = new HashMap<>(page.getResponseHeaders()); + Map headers = new HashMap<>(page.responseHeaders()); headers.put(HttpConstants.HttpHeaders.CONTINUATION, compositeContinuationToken); - FeedResponse newPage = BridgeInternal.createFeedResponseWithQueryMetrics(page.getResults(), + FeedResponse newPage = BridgeInternal.createFeedResponseWithQueryMetrics(page.results(), headers, - page.getQueryMetrics()); + page.queryMetrics()); documentProducerFeedResponse.pageResult = newPage; return documentProducerFeedResponse; } @@ -246,9 +239,9 @@ private static Map headerResponse( public Observable> call( Observable.DocumentProducerFeedResponse> source) { return source.filter(documentProducerFeedResponse -> { - if (documentProducerFeedResponse.pageResult.getResults().isEmpty()) { + if (documentProducerFeedResponse.pageResult.results().isEmpty()) { // filter empty pages and accumulate charge - tracker.addCharge(documentProducerFeedResponse.pageResult.getRequestCharge()); + tracker.addCharge(documentProducerFeedResponse.pageResult.requestCharge()); return false; } return true; @@ -266,7 +259,7 @@ public Observable> call( // results. return Observable.just(null); })).map(documentProducerFeedResponse -> { - // Create pairs from the stream to allow the observables downstream to "peek" + // CREATE pairs from the stream to allow the observables downstream to "peek" // 1, 2, 3, null -> (null, 1), (1, 2), (2, 3), (3, null) ImmutablePair.DocumentProducerFeedResponse, DocumentProducer.DocumentProducerFeedResponse> previousCurrent = new ImmutablePair.DocumentProducerFeedResponse, DocumentProducer.DocumentProducerFeedResponse>( this.previousPage, @@ -280,7 +273,7 @@ public Observable> call( DocumentProducer.DocumentProducerFeedResponse next = currentNext.right; String compositeContinuationToken; - String backendContinuationToken = current.pageResult.getResponseContinuation(); + String backendContinuationToken = current.pageResult.continuationToken(); if (backendContinuationToken == null) { // We just finished reading the last document from a partition if (next == null) { @@ -338,7 +331,7 @@ public Observable> drainAsync( @Override public Observable> executeAsync() { - return this.drainAsync(feedOptions.getMaxItemCount()); + return this.drainAsync(feedOptions.maxItemCount()); } protected DocumentProducer createDocumentProducer( diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ParallelDocumentQueryExecutionContextBase.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java similarity index 87% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ParallelDocumentQueryExecutionContextBase.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java index 8ed4f7138b241..59ed7a63f95cb 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ParallelDocumentQueryExecutionContextBase.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.ArrayList; import java.util.HashMap; @@ -28,18 +28,18 @@ import java.util.Map; import java.util.UUID; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.internal.IDocumentClientRetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; import rx.Observable; import rx.functions.Func0; @@ -71,7 +71,7 @@ protected ParallelDocumentQueryExecutionContextBase(IDocumentQueryClient client, this.partitionKeyRanges = partitionKeyRanges; if (!Strings.isNullOrEmpty(rewrittenQuery)) { - this.querySpec = new SqlQuerySpec(rewrittenQuery, super.query.getParameters()); + this.querySpec = new SqlQuerySpec(rewrittenQuery, super.query.parameters()); } else { this.querySpec = super.query; } @@ -85,7 +85,7 @@ protected void initialize(String collectionRid, for (PartitionKeyRange targetRange : partitionKeyRangeToContinuationTokenMap.keySet()) { Func3 createRequestFunc = (partitionKeyRange, - continuationToken, pageSize) -> { + continuationToken, pageSize) -> { Map headers = new HashMap<>(commonRequestHeaders); headers.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, Strings.toString(pageSize)); @@ -106,7 +106,7 @@ protected void initialize(String collectionRid, } protected int FindTargetRangeAndExtractContinuationTokens( - List partitionKeyRanges, Range range) throws DocumentClientException { + List partitionKeyRanges, Range range) throws CosmosClientException { if (partitionKeyRanges == null) { throw new IllegalArgumentException("partitionKeyRanges can not be null."); } @@ -131,7 +131,7 @@ protected int FindTargetRangeAndExtractContinuationTokens( } if (minIndex == partitionKeyRanges.size()) { - throw new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + throw new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, String.format("Could not find partition key range for continuation token: {0}", needle)); } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ParallelQueryConfig.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java similarity index 96% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ParallelQueryConfig.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java index 608c8c22c7a90..6544f64583e84 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ParallelQueryConfig.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; /** * While this class is public, but it is not part of our published public APIs. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/PartitionedQueryExecutionInfo.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java similarity index 92% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/PartitionedQueryExecutionInfo.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java index 5bcf61ef9ba21..845cd62b8d522 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/PartitionedQueryExecutionInfo.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.List; -import com.microsoft.azure.cosmosdb.JsonSerializable; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.routing.Range; +import com.azure.data.cosmos.JsonSerializable; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.routing.Range; /** * Used internally to encapsulates execution information for a query in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/PartitionedQueryExecutionInfoInternal.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java similarity index 90% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/PartitionedQueryExecutionInfoInternal.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java index cd4e4d673ebc9..0a760d5206072 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/PartitionedQueryExecutionInfoInternal.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java @@ -21,16 +21,16 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; -import com.microsoft.azure.cosmosdb.JsonSerializable; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; -import com.microsoft.azure.cosmosdb.internal.routing.Range; +import com.azure.data.cosmos.JsonSerializable; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.internal.routing.Range; public final class PartitionedQueryExecutionInfoInternal extends JsonSerializable { static final String QUERY_INFO_PROPERTY = "queryInfo"; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/PipelinedDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java similarity index 87% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/PipelinedDocumentQueryExecutionContext.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java index ef0a0d3a88e51..eee88a441c474 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/PipelinedDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java @@ -20,22 +20,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.List; import java.util.UUID; import java.util.function.Function; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.query.PartitionedQueryExecutionInfo; -import com.microsoft.azure.cosmosdb.internal.query.QueryInfo; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.Utils; import rx.Observable; @@ -79,7 +76,7 @@ public static Observable { FeedOptions orderByFeedOptions = new FeedOptions(feedOptions); - orderByFeedOptions.setRequestContinuation(continuationToken); + orderByFeedOptions.requestContinuation(continuationToken); return OrderByDocumentQueryExecutionContext.createAsync(client, resourceTypeEnum, resourceType, expression, orderByFeedOptions, resourceLink, collectionRid, partitionedQueryExecutionInfo, targetRanges, initialPageSize, isContinuationExpected, getLazyFeedResponse, @@ -88,7 +85,7 @@ public static Observable { FeedOptions parallelFeedOptions = new FeedOptions(feedOptions); - parallelFeedOptions.setRequestContinuation(continuationToken); + parallelFeedOptions.requestContinuation(continuationToken); return ParallelDocumentQueryExecutionContext.createAsync(client, resourceTypeEnum, resourceType, expression, parallelFeedOptions, resourceLink, collectionRid, partitionedQueryExecutionInfo, targetRanges, initialPageSize, isContinuationExpected, getLazyFeedResponse, @@ -116,7 +113,7 @@ public static Observable Observable new PipelinedDocumentQueryExecutionContext<>(c, pageSize, correlatedActivityId)); } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ProxyDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java similarity index 85% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ProxyDocumentQueryExecutionContext.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java index 607b841521477..149c39de27526 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/ProxyDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java @@ -20,27 +20,26 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.lang.invoke.MethodHandles; import java.util.List; import java.util.UUID; +import com.azure.data.cosmos.internal.Exceptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.query.PartitionedQueryExecutionInfo; -import com.microsoft.azure.cosmosdb.rx.internal.Exceptions; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.Utils; import rx.Observable; import rx.Single; @@ -52,7 +51,7 @@ * * This class is used as a proxy to wrap the * DefaultDocumentQueryExecutionContext which is needed for sending the query to - * Gateway first and then uses PipelinedDocumentQueryExecutionContext after it + * GATEWAY first and then uses PipelinedDocumentQueryExecutionContext after it * gets the necessary info. */ public class ProxyDocumentQueryExecutionContext implements IDocumentQueryExecutionContext { @@ -115,17 +114,17 @@ public Observable> executeAsync() { // cross partition query construct pipeline - DocumentClientException dce = (DocumentClientException) t; + CosmosClientException dce = (CosmosClientException) t; PartitionedQueryExecutionInfo partitionedQueryExecutionInfo = new - PartitionedQueryExecutionInfo(dce.getError().getPartitionedQueryExecutionInfo()); + PartitionedQueryExecutionInfo(dce.error().getPartitionedQueryExecutionInfo()); logger.debug("Query Plan from gateway {}", partitionedQueryExecutionInfo); DefaultDocumentQueryExecutionContext queryExecutionContext = (DefaultDocumentQueryExecutionContext) this.innerExecutionContext; - Single> partitionKeyRanges = queryExecutionContext.getTargetPartitionKeyRanges(collection.getResourceId(), + Single> partitionKeyRanges = queryExecutionContext.getTargetPartitionKeyRanges(collection.resourceId(), partitionedQueryExecutionInfo.getQueryRanges()); Observable> exContext = partitionKeyRanges.toObservable() @@ -140,7 +139,7 @@ public Observable> executeAsync() { isContinuationExpected, partitionedQueryExecutionInfo, pkranges, - this.collection.getResourceId(), + this.collection.resourceId(), this.correlatedActivityId); }); @@ -152,7 +151,7 @@ public Observable> executeAsync() { private boolean isCrossPartitionQuery(Exception exception) { - DocumentClientException clientException = Utils.as(exception, DocumentClientException.class); + CosmosClientException clientException = Utils.as(exception, CosmosClientException.class); if (clientException == null) { return false; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/QueryInfo.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java similarity index 94% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/QueryInfo.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java index 666011b837da9..3fe617fa279a9 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/QueryInfo.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java @@ -21,15 +21,15 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.Collection; import java.util.List; import org.apache.commons.lang3.StringUtils; -import com.microsoft.azure.cosmosdb.JsonSerializable; -import com.microsoft.azure.cosmosdb.internal.query.aggregation.AggregateOperator; +import com.azure.data.cosmos.JsonSerializable; +import com.azure.data.cosmos.internal.query.aggregation.AggregateOperator; /** * Used internally to encapsulates a query's information in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/QueryItem.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java similarity index 91% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/QueryItem.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java index e9756aa551610..c23c468078131 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/QueryItem.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java @@ -22,10 +22,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query; +package com.azure.data.cosmos.internal.query; -import com.microsoft.azure.cosmosdb.JsonSerializable; -import com.microsoft.azure.cosmosdb.Undefined; +import com.azure.data.cosmos.JsonSerializable; +import com.azure.data.cosmos.Undefined; /** * Used internally for query in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/SortOrder.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/SortOrder.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java index af02ac9530ab6..cbd6fccb8e613 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/SortOrder.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query; +package com.azure.data.cosmos.internal.query; /** * Sort order in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/TakeContinuationToken.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/TakeContinuationToken.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java index e8a60c2967cd5..0c4723593c54d 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/TakeContinuationToken.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; -import com.microsoft.azure.cosmosdb.JsonSerializable; -import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import com.azure.data.cosmos.JsonSerializable; +import com.azure.data.cosmos.internal.Utils.ValueHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/TopDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java similarity index 82% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/TopDocumentQueryExecutionContext.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java index afa80ca43d3c8..0ced4bfbe3de2 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/query/TopDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java @@ -21,18 +21,18 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import java.util.HashMap; import java.util.Map; import java.util.function.Function; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Utils.ValueHolder; import rx.Observable; import rx.functions.Func1; @@ -57,9 +57,9 @@ public static Observable outTakeContinuationToken = new ValueHolder(); if (!TakeContinuationToken.tryParse(topContinuationToken, outTakeContinuationToken)) { - String message = String.format("Invalid JSON in continuation token %s for Top~Context", + String message = String.format("INVALID JSON in continuation token %s for Top~Context", topContinuationToken); - DocumentClientException dce = new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + CosmosClientException dce = new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, message); return Observable.error(dce); } @@ -71,7 +71,7 @@ public static Observable> drainAsync(int maxPageSize) { @Override public Boolean call(FeedResponse frp) { - fetchedItems += frp.getResults().size(); + fetchedItems += frp.results().size(); // take until we have at least top many elements fetched return fetchedItems >= top; @@ -113,13 +113,13 @@ public Boolean call(FeedResponse frp) { @Override public FeedResponse call(FeedResponse t) { - if (collectedItems + t.getResults().size() <= top) { - collectedItems += t.getResults().size(); + if (collectedItems + t.results().size() <= top) { + collectedItems += t.results().size(); - Map headers = new HashMap<>(t.getResponseHeaders()); + Map headers = new HashMap<>(t.responseHeaders()); if (top != collectedItems) { // Add Take Continuation Token - String sourceContinuationToken = t.getResponseContinuation(); + String sourceContinuationToken = t.continuationToken(); TakeContinuationToken takeContinuationToken = new TakeContinuationToken(top - collectedItems, sourceContinuationToken); headers.put(HttpConstants.HttpHeaders.CONTINUATION, takeContinuationToken.toJson()); @@ -128,8 +128,8 @@ public FeedResponse call(FeedResponse t) { headers.put(HttpConstants.HttpHeaders.CONTINUATION, null); } - return BridgeInternal.createFeedResponseWithQueryMetrics(t.getResults(), headers, - t.getQueryMetrics()); + return BridgeInternal.createFeedResponseWithQueryMetrics(t.results(), headers, + t.queryMetrics()); } else { assert lastPage == false; lastPage = true; @@ -137,11 +137,11 @@ public FeedResponse call(FeedResponse t) { collectedItems += lastPageSize; // Null out the continuation token - Map headers = new HashMap<>(t.getResponseHeaders()); + Map headers = new HashMap<>(t.responseHeaders()); headers.put(HttpConstants.HttpHeaders.CONTINUATION, null); - return BridgeInternal.createFeedResponseWithQueryMetrics(t.getResults().subList(0, lastPageSize), - headers, t.getQueryMetrics()); + return BridgeInternal.createFeedResponseWithQueryMetrics(t.results().subList(0, lastPageSize), + headers, t.queryMetrics()); } } }); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/AggregateOperator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/AggregateOperator.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java index 18b9b7edeb8bf..b84421411f04c 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/AggregateOperator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.aggregation; +package com.azure.data.cosmos.internal.query.aggregation; public enum AggregateOperator { Average, diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/Aggregator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/Aggregator.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java index ea4ad348f5ece..82a6301bc8d3c 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/Aggregator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.aggregation; +package com.azure.data.cosmos.internal.query.aggregation; public interface Aggregator { void aggregate(Object item); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/AverageAggregator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java similarity index 93% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/AverageAggregator.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java index d2b66dd608264..535f6ba1d681d 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/AverageAggregator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.aggregation; +package com.azure.data.cosmos.internal.query.aggregation; import java.io.IOException; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.internal.Utils; +import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Utils; public class AverageAggregator implements Aggregator { private AverageInfo averageInfo; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/CountAggregator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/CountAggregator.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java index 2589f0699006a..bb18db582ed57 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/CountAggregator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java @@ -22,7 +22,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.aggregation; +package com.azure.data.cosmos.internal.query.aggregation; public class CountAggregator implements Aggregator { private long value; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/MaxAggregator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java similarity index 90% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/MaxAggregator.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java index fc3ba6d86094c..523b9f776fb51 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/MaxAggregator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.aggregation; +package com.azure.data.cosmos.internal.query.aggregation; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.internal.query.ItemComparator; +import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.query.ItemComparator; public class MaxAggregator implements Aggregator { private Object value; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/MinAggregator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java similarity index 90% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/MinAggregator.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java index 344b24f3ba80e..ebad5582c5a7a 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/MinAggregator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.aggregation; +package com.azure.data.cosmos.internal.query.aggregation; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.internal.query.ItemComparator; +import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.query.ItemComparator; public class MinAggregator implements Aggregator { private Object value; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/SumAggregator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java similarity index 93% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/SumAggregator.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java index ebf2b23437e06..100c56119c4ec 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/aggregation/SumAggregator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.aggregation; +package com.azure.data.cosmos.internal.query.aggregation; -import com.microsoft.azure.cosmosdb.Undefined; +import com.azure.data.cosmos.Undefined; public class SumAggregator implements Aggregator { private Double sum; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/orderbyquery/OrderByRowResult.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java similarity index 91% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/orderbyquery/OrderByRowResult.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java index 18a0ffa102d01..851988e86538d 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/orderbyquery/OrderByRowResult.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.orderbyquery; +package com.azure.data.cosmos.internal.query.orderbyquery; import java.util.List; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.query.QueryItem; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.query.QueryItem; /** * Represents the result of a query in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/orderbyquery/OrderbyRowComparer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java similarity index 92% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/orderbyquery/OrderbyRowComparer.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java index 7606c72629494..4b0682cde9171 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/query/orderbyquery/OrderbyRowComparer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.query.orderbyquery; +package com.azure.data.cosmos.internal.query.orderbyquery; import java.util.ArrayList; import java.util.Collection; @@ -31,11 +31,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.internal.query.ItemComparator; -import com.microsoft.azure.cosmosdb.internal.query.ItemType; -import com.microsoft.azure.cosmosdb.internal.query.ItemTypeHelper; -import com.microsoft.azure.cosmosdb.internal.query.QueryItem; -import com.microsoft.azure.cosmosdb.internal.query.SortOrder; +import com.azure.data.cosmos.internal.query.ItemComparator; +import com.azure.data.cosmos.internal.query.ItemType; +import com.azure.data.cosmos.internal.query.ItemTypeHelper; +import com.azure.data.cosmos.internal.query.QueryItem; +import com.azure.data.cosmos.internal.query.SortOrder; public final class OrderbyRowComparer implements Comparator> { private static final Logger logger = LoggerFactory.getLogger(OrderbyRowComparer.class); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/CaseInsensitiveHashMap.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java similarity index 98% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/CaseInsensitiveHashMap.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java index 0865084695327..dc000cd04c1ad 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/CaseInsensitiveHashMap.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.util.HashMap; import java.util.Map; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/CollectionRoutingMap.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/CollectionRoutingMap.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java index 5cc477ac46949..38b6080b5f414 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/CollectionRoutingMap.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.util.Collection; import java.util.List; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import com.azure.data.cosmos.PartitionKeyRange; import org.apache.commons.lang3.tuple.ImmutablePair; /** diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/IServerIdentity.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java similarity index 95% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/IServerIdentity.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java index ca5a849739e8b..2ebb41e349f17 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/IServerIdentity.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; public interface IServerIdentity { } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/InMemoryCollectionRoutingMap.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java similarity index 96% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/InMemoryCollectionRoutingMap.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java index b17205ddd6e82..ae67c6570239b 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/InMemoryCollectionRoutingMap.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.util.ArrayList; import java.util.Collection; @@ -38,7 +38,7 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import com.azure.data.cosmos.PartitionKeyRange; import org.apache.commons.lang3.tuple.Pair; /** @@ -78,7 +78,7 @@ public static InMemoryCollectionRoutingMap tryCreateCompleteRoutingMap( new HashMap<>(); for (ImmutablePair range: ranges) { - rangeById.put(range.left.getId(), range); + rangeById.put(range.left.id(), range); } List> sortedRanges = new ArrayList<>(rangeById.values()); @@ -236,11 +236,11 @@ public CollectionRoutingMap tryCombine( newGoneRanges.addAll(this.goneRanges); Map> newRangeById = - this.rangeById.values().stream().filter(tuple -> !newGoneRanges.contains(tuple.left.getId())).collect(Collectors. - toMap(tuple -> tuple.left.getId(), tuple -> tuple)); + this.rangeById.values().stream().filter(tuple -> !newGoneRanges.contains(tuple.left.id())).collect(Collectors. + toMap(tuple -> tuple.left.id(), tuple -> tuple)); - for (ImmutablePair tuple : ranges.stream().filter(tuple -> !newGoneRanges.contains(tuple.getLeft().getId())).collect(Collectors.toList())) { - newRangeById.put(tuple.getLeft().getId(), tuple); + for (ImmutablePair tuple : ranges.stream().filter(tuple -> !newGoneRanges.contains(tuple.getLeft().id())).collect(Collectors.toList())) { + newRangeById.put(tuple.getLeft().id(), tuple); } List> sortedRanges = newRangeById.values().stream().collect(Collectors.toList()); diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/LocationCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/LocationCache.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java index d730343526abf..2af8746a7236f 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/LocationCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java @@ -21,16 +21,16 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DatabaseAccount; -import com.microsoft.azure.cosmosdb.DatabaseAccountLocation; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Strings; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +package com.azure.data.cosmos.internal.routing; + +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.DatabaseAccount; +import com.azure.data.cosmos.DatabaseAccountLocation; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.Utils; import org.apache.commons.collections4.map.CaseInsensitiveMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -134,7 +134,7 @@ public void markEndpointUnavailableForWrite(URL endpoint) { /** * Invoked when {@link DatabaseAccount} is read - * @param databaseAccount Read DatabaseAccount + * @param databaseAccount READ DatabaseAccount */ public void onDatabaseAccountRead(DatabaseAccount databaseAccount) { this.updateLocationCache( @@ -485,7 +485,7 @@ public boolean canUseMultipleWriteLocations(RxDocumentServiceRequest request) { return this.canUseMultipleWriteLocations() && (request.getResourceType() == ResourceType.Document || (request.getResourceType() == ResourceType.StoredProcedure && request.getOperationType() == - com.microsoft.azure.cosmosdb.internal.OperationType.ExecuteJavaScript)); + com.azure.data.cosmos.internal.OperationType.ExecuteJavaScript)); } diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/routing/LocationHelper.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/routing/LocationHelper.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java index 9cc5fd08442fa..857da425275f5 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/routing/LocationHelper.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.routing; +package com.azure.data.cosmos.internal.routing; import org.apache.commons.lang3.StringUtils; diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/RoutingMapProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java similarity index 93% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/RoutingMapProvider.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java index ce7be3bdf86c5..d0b996534f5ac 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/RoutingMapProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.util.Collection; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import com.azure.data.cosmos.PartitionKeyRange; /** * Used internally in request routing in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/RoutingMapProviderHelper.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java similarity index 97% rename from gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/RoutingMapProviderHelper.java rename to gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java index ef4311699fa34..e8e0ba56148fa 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/routing/RoutingMapProviderHelper.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java @@ -21,13 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import com.azure.data.cosmos.PartitionKeyRange; /** * Provide utility functionality to route request in direct connectivity mode in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/RetryPolicy.java b/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/RetryPolicy.java index 9b1b5eec63127..4f65575443ffd 100644 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/RetryPolicy.java +++ b/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/RetryPolicy.java @@ -23,13 +23,14 @@ package com.microsoft.azure.cosmosdb.internal; -import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.azure.data.cosmos.CosmosClientException; /** - * Used internally to define the interface for retry policy in the Azure Cosmos DB database service Java SDK. + * Used internally to define the interface for retry policy in the Azure Cosmos + * DB database service Java SDK. */ public interface RetryPolicy { - boolean shouldRetry(DocumentClientException exception) ; + boolean shouldRetry(CosmosClientException exception); long getRetryAfterInMilliseconds(); } diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/GatewayTestUtils.java b/gateway/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java similarity index 97% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/GatewayTestUtils.java rename to gateway/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java index 8292a4c0f3993..5d931bf37c846 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/GatewayTestUtils.java +++ b/gateway/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb; +package com.azure.data.cosmos; import java.util.List; diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ClientRetryPolicyTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java similarity index 96% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ClientRetryPolicyTest.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java index b6c6157fb9af6..e5e91d9611539 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ClientRetryPolicyTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java @@ -21,11 +21,9 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.RetryOptions; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; +import com.azure.data.cosmos.RetryOptions; import io.netty.handler.timeout.ReadTimeoutException; import org.mockito.Mockito; import org.testng.annotations.Test; diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConfigsTests.java b/gateway/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java similarity index 92% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConfigsTests.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java index 5ff8c28e33b08..0e935f5ee40bc 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConfigsTests.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import static org.assertj.core.api.Assertions.assertThat; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.directconnectivity.Protocol; import org.testng.annotations.Test; public class ConfigsTests { @@ -45,7 +45,7 @@ public void maxHttpBodyLength() { @Test(groups = { "unit" }) public void getProtocol() { Configs config = new Configs(); - assertThat(config.getProtocol()).isEqualTo(Protocol.valueOf(System.getProperty("COSMOS.PROTOCOL", "Https"))); + assertThat(config.getProtocol()).isEqualTo(Protocol.valueOf(System.getProperty("COSMOS.PROTOCOL", "HTTPS"))); } @Test(groups = { "unit" }) diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/LocationHelperTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java similarity index 84% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/LocationHelperTest.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java index 5bc606e29c25b..c24e244a1452a 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/LocationHelperTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java @@ -1,6 +1,6 @@ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.rx.internal.routing.LocationHelper; +import com.azure.data.cosmos.internal.routing.LocationHelper; import org.testng.annotations.Test; import java.net.URI; diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RenameCollectionAwareClientRetryPolicyTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java similarity index 89% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RenameCollectionAwareClientRetryPolicyTest.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java index bfb362d7b93cc..d12ad50fc6257 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RenameCollectionAwareClientRetryPolicyTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java @@ -20,23 +20,20 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.WFConstants; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxClientCollectionCache; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import io.netty.handler.timeout.ReadTimeoutException; import org.mockito.Mockito; import org.testng.annotations.Test; import rx.Completable; import rx.Single; -import static com.microsoft.azure.cosmosdb.rx.internal.ClientRetryPolicyTest.validateSuccess; +import static com.azure.data.cosmos.internal.ClientRetryPolicyTest.validateSuccess; import static org.assertj.core.api.Assertions.assertThat; public class RenameCollectionAwareClientRetryPolicyTest { @@ -48,7 +45,7 @@ public void onBeforeSendRequestNotInvoked() { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); - IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.GetDefault()); + IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.defaultPolicy()); RxClientCollectionCache rxClientCollectionCache = Mockito.mock(RxClientCollectionCache.class); ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class); @@ -75,7 +72,7 @@ public void onBeforeSendRequestNotInvoked() { public void shouldRetryWithNotFoundStatusCode() { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); - IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.GetDefault()); + IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.defaultPolicy()); RxClientCollectionCache rxClientCollectionCache = Mockito.mock(RxClientCollectionCache.class); ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class); @@ -101,7 +98,7 @@ public void shouldRetryWithNotFoundStatusCode() { public void shouldRetryWithNotFoundStatusCodeAndReadSessionNotAvailableSubStatusCode() { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); - IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.GetDefault()); + IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.defaultPolicy()); RxClientCollectionCache rxClientCollectionCache = Mockito.mock(RxClientCollectionCache.class); ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class); @@ -115,11 +112,11 @@ public void shouldRetryWithNotFoundStatusCodeAndReadSessionNotAvailableSubStatus renameCollectionAwareClientRetryPolicy.onBeforeSendRequest(request); NotFoundException notFoundException = new NotFoundException(); - notFoundException.getResponseHeaders().put(WFConstants.BackendHeaders.SUB_STATUS, + notFoundException.responseHeaders().put(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)); DocumentCollection documentCollection = new DocumentCollection(); - documentCollection.setResourceId("rid_1"); + documentCollection.resourceId("rid_1"); Mockito.when(rxClientCollectionCache.resolveCollectionAsync(request)).thenReturn(Single.just(documentCollection)); @@ -138,7 +135,7 @@ public void shouldRetryWithNotFoundStatusCodeAndReadSessionNotAvailableSubStatus public void shouldRetryWithGenericException() { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); - IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.GetDefault()); + IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.defaultPolicy()); RxClientCollectionCache rxClientCollectionCache = Mockito.mock(RxClientCollectionCache.class); ISessionContainer sessionContainer = Mockito.mock(ISessionContainer.class); diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RxGatewayStoreModelTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java similarity index 87% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RxGatewayStoreModelTest.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java index e4a5505130107..72fd41fe534da 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RxGatewayStoreModelTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java @@ -21,16 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.QueryCompatibilityMode; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.rx.FailureValidator; import io.netty.buffer.ByteBuf; import io.netty.handler.timeout.ReadTimeoutException; import io.reactivex.netty.client.RxClient; @@ -63,7 +59,7 @@ public void readTimeout() throws Exception { RxGatewayStoreModel storeModel = new RxGatewayStoreModel( sessionContainer, - ConsistencyLevel.Session, + ConsistencyLevel.SESSION, queryCompatibilityMode, userAgentContainer, globalEndpointManager, @@ -76,7 +72,7 @@ public void readTimeout() throws Exception { Observable resp = storeModel.processMessage(dsr); validateFailure(resp, FailureValidator.builder() - .instanceOf(DocumentClientException.class) + .instanceOf(CosmosClientException.class) .causeInstanceOf(ReadTimeoutException.class) .documentClientExceptionHeaderRequestContainsEntry("key", "value") .statusCode(0).build()); diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/SessionContainerTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java similarity index 98% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/SessionContainerTest.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java index a66625dbf8909..7c74f302ffa55 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/SessionContainerTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java @@ -21,15 +21,12 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.microsoft.azure.cosmosdb.GatewayTestUtils; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.rx.internal.DocumentServiceRequestContext; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.GatewayTestUtils; +import com.azure.data.cosmos.PartitionKeyRange; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; @@ -83,12 +80,12 @@ public void sessionContainer() throws Exception { DocumentServiceRequestContext dsrContext = new DocumentServiceRequestContext(); PartitionKeyRange resolvedPKRange = new PartitionKeyRange(); - resolvedPKRange.setId("range_" + (numPartitionKeyRangeIds + 10)); + resolvedPKRange.id("range_" + (numPartitionKeyRangeIds + 10)); GatewayTestUtils.setParent(resolvedPKRange, ImmutableList.of("range_2", "range_x")); dsrContext.resolvedPartitionKeyRange = resolvedPKRange; request.requestContext = dsrContext; - sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, resolvedPKRange.getId()); + sessionToken = sessionContainer.resolvePartitionLocalSessionToken(request, resolvedPKRange.id()); assertThat(sessionToken.getLSN()).isEqualTo(2); } diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/SessionTokenTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java similarity index 98% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/SessionTokenTest.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java index 15b46fdf006d6..db1645fadcf42 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/SessionTokenTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal; +package com.azure.data.cosmos.internal; import org.testng.annotations.Test; -import static com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; +import static com.azure.data.cosmos.internal.Utils.ValueHolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ShouldRetryValidator.java b/gateway/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java similarity index 97% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ShouldRetryValidator.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java index 1701c371dbf20..8b506df50f8e3 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ShouldRetryValidator.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; +import com.azure.data.cosmos.rx.FailureValidator; import java.time.Duration; import java.util.ArrayList; diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/caches/AsyncCacheTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java similarity index 98% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/caches/AsyncCacheTest.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java index b6992f3b97b7a..bf7e6ee2c0ad5 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/caches/AsyncCacheTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.caches; +package com.azure.data.cosmos.internal.caches; import static org.assertj.core.api.Assertions.assertThat; diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/InMemoryCollectionRoutingMapTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java similarity index 94% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/InMemoryCollectionRoutingMapTest.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java index 6ae8eedd6a6f0..9b3dbc0dd9259 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/InMemoryCollectionRoutingMapTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import static org.assertj.core.api.Assertions.assertThat; @@ -35,7 +35,7 @@ import org.apache.commons.lang3.tuple.ImmutablePair; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import com.azure.data.cosmos.PartitionKeyRange; public class InMemoryCollectionRoutingMapTest { @@ -64,20 +64,20 @@ public void collectionRoutingMap() { ServerIdentityImp.of(3))), StringUtils.EMPTY); - assertThat("0").isEqualTo(routingMap.getOrderedPartitionKeyRanges().get(0).getId()); - assertThat("1").isEqualTo(routingMap.getOrderedPartitionKeyRanges().get(1).getId()); - assertThat("2").isEqualTo(routingMap.getOrderedPartitionKeyRanges().get(2).getId()); - assertThat("3").isEqualTo(routingMap.getOrderedPartitionKeyRanges().get(3).getId()); + assertThat("0").isEqualTo(routingMap.getOrderedPartitionKeyRanges().get(0).id()); + assertThat("1").isEqualTo(routingMap.getOrderedPartitionKeyRanges().get(1).id()); + assertThat("2").isEqualTo(routingMap.getOrderedPartitionKeyRanges().get(2).id()); + assertThat("3").isEqualTo(routingMap.getOrderedPartitionKeyRanges().get(3).id()); - assertThat("0").isEqualTo(routingMap.getRangeByEffectivePartitionKey("").getId()); - assertThat("0").isEqualTo(routingMap.getRangeByEffectivePartitionKey("0000000000").getId()); - assertThat("1").isEqualTo(routingMap.getRangeByEffectivePartitionKey("0000000030").getId()); - assertThat("1").isEqualTo(routingMap.getRangeByEffectivePartitionKey("0000000031").getId()); - assertThat("3").isEqualTo(routingMap.getRangeByEffectivePartitionKey("0000000071").getId()); + assertThat("0").isEqualTo(routingMap.getRangeByEffectivePartitionKey("").id()); + assertThat("0").isEqualTo(routingMap.getRangeByEffectivePartitionKey("0000000000").id()); + assertThat("1").isEqualTo(routingMap.getRangeByEffectivePartitionKey("0000000030").id()); + assertThat("1").isEqualTo(routingMap.getRangeByEffectivePartitionKey("0000000031").id()); + assertThat("3").isEqualTo(routingMap.getRangeByEffectivePartitionKey("0000000071").id()); - assertThat("0").isEqualTo(routingMap.getRangeByPartitionKeyRangeId("0").getId()); - assertThat("1").isEqualTo(routingMap.getRangeByPartitionKeyRangeId("1").getId()); + assertThat("0").isEqualTo(routingMap.getRangeByPartitionKeyRangeId("0").id()); + assertThat("1").isEqualTo(routingMap.getRangeByPartitionKeyRangeId("1").id()); assertThat(4).isEqualTo( routingMap @@ -95,7 +95,7 @@ public void collectionRoutingMap() { assertThat(1).isEqualTo(partitionKeyRanges.size()); Iterator iterator = partitionKeyRanges.iterator(); - assertThat("1").isEqualTo(iterator.next().getId()); + assertThat("1").isEqualTo(iterator.next().id()); Collection partitionKeyRanges1 = routingMap .getOverlappingRanges(Arrays.asList(new Range("0000000040", "0000000045", true, true), @@ -104,8 +104,8 @@ public void collectionRoutingMap() { assertThat(2).isEqualTo(partitionKeyRanges1.size()); Iterator iterator1 = partitionKeyRanges1.iterator(); - assertThat("1").isEqualTo(iterator1.next().getId()); - assertThat("2").isEqualTo(iterator1.next().getId()); + assertThat("1").isEqualTo(iterator1.next().id()); + assertThat("2").isEqualTo(iterator1.next().id()); } @Test(groups = { "unit" }, expectedExceptions = IllegalStateException.class) diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/LocationCacheTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java similarity index 95% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/LocationCacheTest.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java index bb2d519a7fd75..dad666bda1b6c 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/LocationCacheTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java @@ -21,22 +21,22 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.BridgeUtils; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.DatabaseAccount; -import com.microsoft.azure.cosmosdb.DatabaseAccountLocation; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.internal.GlobalEndpointManager; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.DatabaseAccountManagerInternal; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.BridgeUtils; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.DatabaseAccount; +import com.azure.data.cosmos.DatabaseAccountLocation; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.GlobalEndpointManager; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.DatabaseAccountManagerInternal; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; import org.apache.commons.collections4.list.UnmodifiableList; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -59,7 +59,7 @@ import java.util.stream.Stream; import java.util.stream.StreamSupport; -import static com.microsoft.azure.cosmosdb.BridgeUtils.createDatabaseAccountLocation; +import static com.azure.data.cosmos.BridgeUtils.createDatabaseAccountLocation; import static org.assertj.core.api.Assertions.assertThat; /** @@ -167,9 +167,9 @@ private void initialize( this.cache.onDatabaseAccountRead(this.databaseAccount); ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setEnableEndpointDiscovery(enableEndpointDiscovery); + connectionPolicy.enableEndpointDiscovery(enableEndpointDiscovery); BridgeInternal.setUseMultipleWriteLocations(connectionPolicy, useMultipleWriteLocations); - connectionPolicy.setPreferredLocations(this.preferredLocations); + connectionPolicy.preferredLocations(this.preferredLocations); this.endpointManager = new GlobalEndpointManager(mockedClient, connectionPolicy, configs); } @@ -398,7 +398,7 @@ private void validateRequestEndpointResolution( createUrl(Iterables.get(this.databaseAccount.getWritableLocations(), 1).getEndpoint()); // If current write endpoint is unavailable, write endpoints order doesn't change - // All write requests flip-flop between current write and alternate write endpoint + // ALL write requests flip-flop between current write and alternate write endpoint UnmodifiableList writeEndpoints = this.cache.getWriteEndpoints(); assertThat(firstAvailableWriteEndpoint).isEqualTo(writeEndpoints.get(0)); diff --git a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/RoutingMapProviderHelperTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java similarity index 97% rename from gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/RoutingMapProviderHelperTest.java rename to gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java index c0b105b5b6bbc..e5d3016706e11 100644 --- a/gateway/src/test/java/com/microsoft/azure/cosmosdb/internal/routing/RoutingMapProviderHelperTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.routing; +package com.azure.data.cosmos.internal.routing; import static org.assertj.core.api.Assertions.assertThat; @@ -37,7 +37,7 @@ import org.apache.commons.lang3.tuple.ImmutablePair; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import com.azure.data.cosmos.PartitionKeyRange; public class RoutingMapProviderHelperTest { private static final MockRoutingMapProvider ROUTING_MAP_PROVIDER = new MockRoutingMapProvider( @@ -105,7 +105,7 @@ public void getOverlappingRanges() { Function func = new Function() { @Override public String apply(PartitionKeyRange range) { - return range.getId(); + return range.id(); } }; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/AsyncDocumentClient.java b/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java similarity index 86% rename from sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/AsyncDocumentClient.java rename to sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java index 513baf9a1b7c6..bc70d8771aded 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/AsyncDocumentClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java @@ -20,40 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos; -import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.List; -import com.microsoft.azure.cosmosdb.Attachment; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.Conflict; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseAccount; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.MediaOptions; -import com.microsoft.azure.cosmosdb.MediaResponse; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.StoredProcedureResponse; -import com.microsoft.azure.cosmosdb.TokenResolver; -import com.microsoft.azure.cosmosdb.Trigger; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientImpl; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.RxDocumentClientImpl; import rx.Observable; @@ -76,12 +50,12 @@ *
  * {@code
  * ConnectionPolicy connectionPolicy = new ConnectionPolicy();
- * connectionPolicy.setConnectionMode(ConnectionMode.Direct);
+ * connectionPolicy.connectionMode(ConnectionMode.DIRECT);
  * AsyncDocumentClient client = new AsyncDocumentClient.Builder()
  *         .withServiceEndpoint(serviceEndpoint)
  *         .withMasterKeyOrResourceToken(masterKey)
  *         .withConnectionPolicy(connectionPolicy)
- *         .withConsistencyLevel(ConsistencyLevel.Session)
+ *         .withConsistencyLevel(ConsistencyLevel.SESSION)
  *         .build();
  * }
  * 
@@ -95,12 +69,12 @@ public interface AsyncDocumentClient { *
      * {@code
      * ConnectionPolicy connectionPolicy = new ConnectionPolicy();
-     * connectionPolicy.setConnectionMode(ConnectionMode.Direct);
+     * connectionPolicy.connectionMode(ConnectionMode.DIRECT);
      * AsyncDocumentClient client = new AsyncDocumentClient.Builder()
      *         .withServiceEndpoint(serviceEndpoint)
      *         .withMasterKeyOrResourceToken(masterKey)
      *         .withConnectionPolicy(connectionPolicy)
-     *         .withConsistencyLevel(ConsistencyLevel.Session)
+     *         .withConsistencyLevel(ConsistencyLevel.SESSION)
      *         .build();
      * }
      * 
@@ -179,18 +153,18 @@ public Builder withConnectionPolicy(ConnectionPolicy connectionPolicy) { /** * This method will accept tokenResolver which is rx function, it takes arguments
- * T1 requestVerb(String),
- * T2 resourceIdOrFullName(String),
- * T3 resourceType(com.microsoft.azure.cosmosdb.internal.ResourceType),
- * T4 request headers(Map)
+ * T1 requestVerb(STRING),
+ * T2 resourceIdOrFullName(STRING),
+ * T3 resourceType(com.azure.data.cosmos.internal.ResourceType),
+ * T4 request headers(Map)
*
* and return
- * R authenticationToken(String)
+ * R authenticationToken(STRING)
* * @param tokenResolver tokenResolver function for authentication. * @return current Builder. */ - /*public Builder withTokenResolver(Func4, String> tokenResolver) { + /*public Builder withTokenResolver(Func4, STRING> tokenResolver) { this.tokenResolver = tokenResolver; return this; }*/ @@ -696,7 +670,7 @@ Observable> upsertStoredProcedure(String colle Observable> deleteStoredProcedure(String storedProcedureLink, RequestOptions options); /** - * Read a stored procedure by the stored procedure link. + * READ a stored procedure by the stored procedure link. *

* After subscription the operation will be performed. * The {@link Observable} upon successful completion will contain a single resource response with the read stored procedure. @@ -943,7 +917,7 @@ Observable> upsertUserDefinedFunction(Stri Observable> deleteUserDefinedFunction(String udfLink, RequestOptions options); /** - * Read a user defined function. + * READ a user defined function. *

* After subscription the operation will be performed. * The {@link Observable} upon successful completion will contain a single resource response for the read user defined function. @@ -998,163 +972,6 @@ Observable> queryUserDefinedFunctions(String c Observable> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, FeedOptions options); - /** - * Creates an attachment. - *

- * After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the created attachment. - * In case of failure the {@link Observable} will error. - * - * @param documentLink the document link. - * @param attachment the attachment to create. - * @param options the request options. - * @return an {@link Observable} containing the single resource response with the created attachment or an error. - */ - Observable> createAttachment(String documentLink, Attachment attachment, RequestOptions options); - - /** - * Upserts an attachment. - *

- * After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the upserted attachment. - * In case of failure the {@link Observable} will error. - * - * @param documentLink the document link. - * @param attachment the attachment to upsert. - * @param options the request options. - * @return an {@link Observable} containing the single resource response with the upserted attachment or an error. - */ - Observable> upsertAttachment(String documentLink, Attachment attachment, RequestOptions options); - - /** - * Replaces an attachment. - *

- * After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the replaced attachment. - * In case of failure the {@link Observable} will error. - * - * @param attachment the attachment to use. - * @param options the request options. - * @return an {@link Observable} containing the single resource response with the replaced attachment or an error. - */ - Observable> replaceAttachment(Attachment attachment, RequestOptions options); - - /** - * Deletes an attachment. - *

- * After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the deleted attachment. - * In case of failure the {@link Observable} will error. - * - * @param attachmentLink the attachment link. - * @param options the request options. - * @return an {@link Observable} containing the single resource response for the deleted attachment or an error. - */ - Observable> deleteAttachment(String attachmentLink, RequestOptions options); - - /** - * Reads an attachment. - *

- * After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the read attachment. - * In case of failure the {@link Observable} will error. - * - * @param attachmentLink the attachment link. - * @param options the request options. - * @return an {@link Observable} containing the single resource response with the read attachment or an error. - */ - Observable> readAttachment(String attachmentLink, RequestOptions options); - - /** - * Reads all attachments in a document. - *

- * After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the read attachments. - * In case of failure the {@link Observable} will error. - * - * @param documentLink the document link. - * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the read attachments or an error. - */ - Observable> readAttachments(String documentLink, FeedOptions options); - - - /** - * Reads a media by the media link. - * - * @param mediaLink the media link. - * @return the media response. - */ - Observable readMedia(String mediaLink); - - /** - * Updates a media by the media link. - * - * @param mediaLink the media link. - * @param mediaStream the media stream to upload. - * @param options the media options. - * @return the media response. - */ - Observable updateMedia(String mediaLink, InputStream mediaStream, MediaOptions options); - - /** - * Query for attachments. - *

- * After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained attachments. - * In case of failure the {@link Observable} will error. - * - * @param documentLink the document link. - * @param query the query. - * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained attachments or an error. - */ - Observable> queryAttachments(String documentLink, String query, FeedOptions options); - - /** - * Query for attachments. - *

- * After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained attachments. - * In case of failure the {@link Observable} will error. - * - * @param documentLink the document link. - * @param querySpec the SQL query specification. - * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained attachments or an error. - */ - Observable> queryAttachments(String documentLink, SqlQuerySpec querySpec, FeedOptions options); - - /** - * Creates an attachment. - *

- * After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the created attachment. - * In case of failure the {@link Observable} will error. - * - * @param documentLink the document link. - * @param mediaStream the media stream for creating the attachment. - * @param options the media options. - * @param requestOptions the request options - * @return an {@link Observable} containing the single resource response with the created attachment or an error. - */ - Observable> createAttachment(String documentLink, InputStream mediaStream, MediaOptions options, RequestOptions requestOptions); - - /** - * Upserts an attachment to the media stream - *

- * After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the upserted attachment. - * In case of failure the {@link Observable} will error. - * - * @param documentLink the document link. - * @param mediaStream the media stream for upserting the attachment. - * @param options the media options. - * @param requestOptions the request options - * @return an {@link Observable} containing the single resource response with the upserted attachment or an error. - */ - Observable> upsertAttachment(String documentLink, InputStream mediaStream, MediaOptions options, RequestOptions requestOptions); - /** * Reads a conflict. *

diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserver.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserver.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserver.java rename to sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserver.java index f6ef4557cb8e3..e2e0b638454af 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserver.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; import java.util.List; @@ -49,5 +49,5 @@ public interface ChangeFeedObserver { * @param context the context specifying partition for this observer, etc. * @param docs the documents changed. */ - void processChanges(ChangeFeedObserverContext context, List docs); + void processChanges(ChangeFeedObserverContext context, List docs); } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverCloseReason.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverCloseReason.java similarity index 98% rename from sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverCloseReason.java rename to sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverCloseReason.java index d46dbd63428c2..1bd720fef5ffb 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverCloseReason.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverCloseReason.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; /** * The reason for the {@link ChangeFeedObserver} to close. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverContext.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverContext.java similarity index 93% rename from sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverContext.java rename to sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverContext.java index b7a146c1dfd83..0614d06aed4e6 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverContext.java @@ -20,9 +20,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.FeedResponse; import reactor.core.publisher.Mono; /** @@ -42,7 +41,7 @@ public interface ChangeFeedObserverContext { * * @return the response from the underlying call. */ - FeedResponse getFeedResponse(); + FeedResponse getFeedResponse(); /** * Checkpoints progress of a stream. This method is valid only if manual checkpoint was configured. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverFactory.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverFactory.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverFactory.java index 5dccf15d5c69c..4574b4c409054 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedObserverFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverFactory.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; /** * Factory class used to create instance(s) of {@link ChangeFeedObserver}. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessor.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java similarity index 92% rename from sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessor.java rename to sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java index 499283928a9ce..8ce56f5a86c69 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java @@ -20,17 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmos.changefeed.HealthMonitor; -import com.microsoft.azure.cosmos.changefeed.LeaseStoreManager; -import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancingStrategy; -import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; -import com.microsoft.azure.cosmos.changefeed.PartitionProcessorFactory; -import com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedProcessorBuilderImpl; +import com.azure.data.cosmos.changefeed.internal.ChangeFeedProcessorBuilderImpl; import reactor.core.publisher.Mono; -import java.util.concurrent.ExecutorService; /** * Simple host for distributing change feed events across observers and thus allowing these observers scale. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessorOptions.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java similarity index 81% rename from sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessorOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java index 7d47de793d416..d6a592e643781 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/ChangeFeedProcessorOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java @@ -20,14 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmos.changefeed.CheckpointFrequency; +import com.azure.data.cosmos.changefeed.CheckpointFrequency; import java.time.Duration; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.Date; +import java.time.OffsetDateTime; import java.util.concurrent.ExecutorService; public class ChangeFeedProcessorOptions { @@ -46,7 +44,7 @@ public class ChangeFeedProcessorOptions { private String leasePrefix; private int maxItemCount; private String startContinuation; - private ZonedDateTime startTime; + private OffsetDateTime startTime; private boolean startFromBeginning; private String sessionToken; private int minPartitionCount; @@ -75,7 +73,7 @@ public ChangeFeedProcessorOptions() { * * @return the renew interval for all leases for partitions. */ - public Duration getLeaseRenewInterval() { + public Duration leaseRenewInterval() { return this.leaseRenewInterval; } @@ -85,7 +83,7 @@ public Duration getLeaseRenewInterval() { * @param leaseRenewInterval the renew interval for all leases for partitions currently held by {@link ChangeFeedProcessor} instance. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withLeaseRenewInterval(Duration leaseRenewInterval) { + public ChangeFeedProcessorOptions leaseRenewInterval(Duration leaseRenewInterval) { this.leaseRenewInterval = leaseRenewInterval; return this; } @@ -95,7 +93,7 @@ public ChangeFeedProcessorOptions withLeaseRenewInterval(Duration leaseRenewInte * * @return the interval to kick off a task to compute if partitions are distributed evenly among known host instances. */ - public Duration getLeaseAcquireInterval() { + public Duration leaseAcquireInterval() { return this.leaseAcquireInterval; } @@ -104,7 +102,7 @@ public Duration getLeaseAcquireInterval() { * @param leaseAcquireInterval he interval to kick off a task to compute if partitions are distributed evenly among known host instances. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withLeaseAcquireInterval(Duration leaseAcquireInterval) { + public ChangeFeedProcessorOptions leaseAcquireInterval(Duration leaseAcquireInterval) { this.leaseAcquireInterval = leaseAcquireInterval; return this; } @@ -118,7 +116,7 @@ public ChangeFeedProcessorOptions withLeaseAcquireInterval(Duration leaseAcquire * * @return the interval for which the lease is taken on a lease representing a partition. */ - public Duration getLeaseExpirationInterval() { + public Duration leaseExpirationInterval() { return this.leaseExpirationInterval; } @@ -132,7 +130,7 @@ public Duration getLeaseExpirationInterval() { * @param leaseExpirationInterval the interval for which the lease is taken on a lease representing a partition. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withLeaseExpirationInterval(Duration leaseExpirationInterval) { + public ChangeFeedProcessorOptions leaseExpirationInterval(Duration leaseExpirationInterval) { this.leaseExpirationInterval = leaseExpirationInterval; return this; } @@ -142,7 +140,7 @@ public ChangeFeedProcessorOptions withLeaseExpirationInterval(Duration leaseExpi * * @return the delay in between polling a partition for new changes on the feed. */ - public Duration getFeedPollDelay() { + public Duration feedPollDelay() { return this.feedPollDelay; } @@ -152,7 +150,7 @@ public Duration getFeedPollDelay() { * @param feedPollDelay the delay in between polling a partition for new changes on the feed, after all current changes are drained. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withFeedPollDelay(Duration feedPollDelay) { + public ChangeFeedProcessorOptions feedPollDelay(Duration feedPollDelay) { this.feedPollDelay = feedPollDelay; return this; } @@ -162,7 +160,7 @@ public ChangeFeedProcessorOptions withFeedPollDelay(Duration feedPollDelay) { * * @return the frequency how often to checkpoint leases. */ - public CheckpointFrequency getCheckpointFrequency() { + public CheckpointFrequency checkpointFrequency() { return this.checkpointFrequency; } @@ -172,7 +170,7 @@ public CheckpointFrequency getCheckpointFrequency() { * @param checkpointFrequency the frequency how often to checkpoint leases. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withCheckpointFrequency(CheckpointFrequency checkpointFrequency) { + public ChangeFeedProcessorOptions checkpointFrequency(CheckpointFrequency checkpointFrequency) { this.checkpointFrequency = checkpointFrequency; return this; } @@ -185,7 +183,7 @@ public ChangeFeedProcessorOptions withCheckpointFrequency(CheckpointFrequency ch * * @return a prefix to be used as part of the lease ID. */ - public String getLeasePrefix() { + public String leasePrefix() { return this.leasePrefix; } @@ -195,7 +193,7 @@ public String getLeasePrefix() { * @param leasePrefix a prefix to be used as part of the lease ID. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withLeasePrefix(String leasePrefix) { + public ChangeFeedProcessorOptions leasePrefix(String leasePrefix) { this.leasePrefix = leasePrefix; return this; } @@ -205,7 +203,7 @@ public ChangeFeedProcessorOptions withLeasePrefix(String leasePrefix) { * * @return the maximum number of items to be returned in the enumeration operation in the Azure Cosmos DB service. */ - public int getMaxItemCount() { + public int maxItemCount() { return this.maxItemCount; } @@ -215,7 +213,7 @@ public int getMaxItemCount() { * @param maxItemCount the maximum number of items to be returned in the enumeration operation. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withMaxItemCount(int maxItemCount) { + public ChangeFeedProcessorOptions maxItemCount(int maxItemCount) { this.maxItemCount = maxItemCount; return this; } @@ -228,7 +226,7 @@ public ChangeFeedProcessorOptions withMaxItemCount(int maxItemCount) { * * @return the start request continuation token to start looking for changes after. */ - public String getStartContinuation() { + public String startContinuation() { return this.startContinuation; } @@ -241,7 +239,7 @@ public String getStartContinuation() { * @param startContinuation the start request continuation token to start looking for changes after. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withStartContinuation(String startContinuation) { + public ChangeFeedProcessorOptions startContinuation(String startContinuation) { this.startContinuation= startContinuation; return this; } @@ -256,7 +254,7 @@ public ChangeFeedProcessorOptions withStartContinuation(String startContinuation * * @return the time (exclusive) to start looking for changes after. */ - public ZonedDateTime getStartTime() { + public OffsetDateTime startTime() { return this.startTime; } @@ -271,27 +269,11 @@ public ZonedDateTime getStartTime() { * @param startTime the time (exclusive) to start looking for changes after. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withStartTime(ZonedDateTime startTime) { + public ChangeFeedProcessorOptions startTime(OffsetDateTime startTime) { this.startTime = startTime; return this; } - /** - * Sets the time (exclusive) to start looking for changes after. - *

- * This is only used when: - * (1) Lease store is not initialized and is ignored if a lease for partition exists and has continuation token. - * (2) StartContinuation is not specified. - * If this is specified, StartFromBeginning is ignored. - * - * @param startTime the time (exclusive) to start looking for changes after. - * @return the current ChangeFeedProcessorOptions instance. - */ - public ChangeFeedProcessorOptions withStartTime(Date startTime) { - this.startTime = ZonedDateTime.ofInstant(startTime.toInstant(), ZoneId.of("UTC")); - return this; - } - /** * Gets a value indicating whether change feed in the Azure Cosmos DB service should start from beginning (true) * or from current (false). By default it's start from current (false). @@ -303,7 +285,7 @@ public ChangeFeedProcessorOptions withStartTime(Date startTime) { * * @return a value indicating whether change feed in the Azure Cosmos DB service should start from. */ - public boolean isStartFromBeginning() { + public boolean startFromBeginning() { return this.startFromBeginning; } @@ -315,10 +297,11 @@ public boolean isStartFromBeginning() { * (2) StartContinuation is not specified. * (3) StartTime is not specified. * + * @param startFromBeginning Indicates to start from beginning if true * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withStartFromBeginning() { - this.startFromBeginning = true; + public ChangeFeedProcessorOptions startFromBeginning(boolean startFromBeginning) { + this.startFromBeginning = startFromBeginning; return this; } @@ -342,7 +325,7 @@ public ChangeFeedProcessorOptions withoutStartFromBeginning() { * * @return the session token for use with session consistency in the Azure Cosmos DB service. */ - public String getSessionToken() { + public String sessionToken() { return this.sessionToken; } @@ -352,7 +335,7 @@ public String getSessionToken() { * @param sessionToken the session token for use with session consistency in the Azure Cosmos DB service. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withSessionToken(String sessionToken) { + public ChangeFeedProcessorOptions sessionToken(String sessionToken) { this.sessionToken = sessionToken; return this; } @@ -365,7 +348,7 @@ public ChangeFeedProcessorOptions withSessionToken(String sessionToken) { * * @return the minimum partition count for the host. */ - public int getMinPartitionCount() { + public int minPartitionCount() { return this.minPartitionCount; } @@ -378,7 +361,7 @@ public int getMinPartitionCount() { * @param minPartitionCount the minimum partition count for the host. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withMinPartitionCount(int minPartitionCount) { + public ChangeFeedProcessorOptions minPartitionCount(int minPartitionCount) { this.minPartitionCount = minPartitionCount; return this; } @@ -387,11 +370,11 @@ public ChangeFeedProcessorOptions withMinPartitionCount(int minPartitionCount) { * Gets the maximum number of partitions the host can serve. *

* This can be used property to limit the number of partitions for the host and thus override equal distribution - * (which is the default) of leases between hosts. Default is 0 (unlimited). + * (which is the default) of leases between hosts. DEFAULT is 0 (unlimited). * * @return the maximum number of partitions the host can serve. */ - public int getMaxPartitionCount() { + public int maxPartitionCount() { return this.maxPartitionCount; } @@ -401,7 +384,7 @@ public int getMaxPartitionCount() { * @param maxPartitionCount the maximum number of partitions the host can serve. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withMaxPartitionCount(int maxPartitionCount) { + public ChangeFeedProcessorOptions maxPartitionCount(int maxPartitionCount) { this.maxPartitionCount = maxPartitionCount; return this; } @@ -412,7 +395,7 @@ public ChangeFeedProcessorOptions withMaxPartitionCount(int maxPartitionCount) { * * @return a value indicating whether on start of the host all existing leases should be deleted and the host should start from scratch. */ - public boolean isDiscardExistingLeases() { + public boolean discardExistingLeases() { return this.discardExistingLeases; } @@ -420,21 +403,11 @@ public boolean isDiscardExistingLeases() { * Sets a value indicating whether on start of the host all existing leases should be deleted and the host * should start from scratch. * + * @param discardExistingLeases Indicates whether to discard all existing leases if true * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withDiscardExistingLeases() { - this.discardExistingLeases = true; - return this; - } - - /** - * Sets a value indicating whether on start of the host all existing leases should be deleted and the host - * should start from scratch. - * - * @return the current ChangeFeedProcessorOptions instance. - */ - public ChangeFeedProcessorOptions withoutDiscardExistingLeases() { - this.discardExistingLeases = false; + public ChangeFeedProcessorOptions discardExistingLeases(boolean discardExistingLeases) { + this.discardExistingLeases = discardExistingLeases; return this; } @@ -443,7 +416,7 @@ public ChangeFeedProcessorOptions withoutDiscardExistingLeases() { * * @return the Batch size of query partitions API. */ - public int getQueryPartitionsMaxBatchSize() { + public int queryPartitionsMaxBatchSize() { return this.queryPartitionsMaxBatchSize; } @@ -453,7 +426,7 @@ public int getQueryPartitionsMaxBatchSize() { * @param queryPartitionsMaxBatchSize the Batch size of query partitions API. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withQueryPartitionsMaxBatchSize(int queryPartitionsMaxBatchSize) { + public ChangeFeedProcessorOptions queryPartitionsMaxBatchSize(int queryPartitionsMaxBatchSize) { this.queryPartitionsMaxBatchSize = queryPartitionsMaxBatchSize; return this; } @@ -463,7 +436,7 @@ public ChangeFeedProcessorOptions withQueryPartitionsMaxBatchSize(int queryParti * * @return maximum number of tasks to use for auxiliary calls. */ - public int getDegreeOfParallelism() { + public int degreeOfParallelism() { return this.degreeOfParallelism; } @@ -473,7 +446,7 @@ public int getDegreeOfParallelism() { * @param defaultQueryPartitionsMaxBatchSize maximum number of tasks to use for auxiliary calls. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withDegreeOfParallelism(int defaultQueryPartitionsMaxBatchSize) { + public ChangeFeedProcessorOptions degreeOfParallelism(int defaultQueryPartitionsMaxBatchSize) { this.queryPartitionsMaxBatchSize = queryPartitionsMaxBatchSize; return this; } @@ -483,7 +456,7 @@ public ChangeFeedProcessorOptions withDegreeOfParallelism(int defaultQueryPartit * * @return current ExecutorService instance. */ - public ExecutorService getExecutorService() { + public ExecutorService executorService() { return this.executorService; } @@ -493,7 +466,7 @@ public ExecutorService getExecutorService() { * @param executorService The instance of {@link ExecutorService} to use. * @return current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions withExecutorService(ExecutorService executorService) { + public ChangeFeedProcessorOptions executorService(ExecutorService executorService) { this.executorService = executorService; return this; } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java similarity index 88% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java index 5ce31ded234ba..a1875b6c54f10 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java @@ -20,22 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseAccount; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.TokenResolver; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Configs; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; @@ -157,7 +145,7 @@ public TokenResolver getTokenResolver() { } /** - * Create a Database if it does not already exist on the service + * CREATE a Database if it does not already exist on the service * * The {@link Mono} upon successful completion will contain a single cosmos database response with the * created or existing database. @@ -166,11 +154,11 @@ public TokenResolver getTokenResolver() { * an error. */ public Mono createDatabaseIfNotExists(CosmosDatabaseSettings databaseSettings) { - return createDatabaseIfNotExistsInternal(getDatabase(databaseSettings.getId())); + return createDatabaseIfNotExistsInternal(getDatabase(databaseSettings.id())); } /** - * Create a Database if it does not already exist on the service + * CREATE a Database if it does not already exist on the service * The {@link Mono} upon successful completion will contain a single cosmos database response with the * created or existing database. * @param id the id of the database @@ -183,10 +171,10 @@ public Mono createDatabaseIfNotExists(String id) { private Mono createDatabaseIfNotExistsInternal(CosmosDatabase database){ return database.read().onErrorResume(exception -> { - if (exception instanceof DocumentClientException) { - DocumentClientException documentClientException = (DocumentClientException) exception; - if (documentClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { - return createDatabase(new CosmosDatabaseSettings(database.getId()), new CosmosDatabaseRequestOptions()); + if (exception instanceof CosmosClientException) { + CosmosClientException cosmosClientException = (CosmosClientException) exception; + if (cosmosClientException.statusCode() == HttpConstants.StatusCodes.NOTFOUND) { + return createDatabase(new CosmosDatabaseSettings(database.id()), new CosmosDatabaseRequestOptions()); } } return Mono.error(exception); @@ -211,7 +199,7 @@ public Mono createDatabase(CosmosDatabaseSettings databa options = new CosmosDatabaseRequestOptions(); } Database wrappedDatabase = new Database(); - wrappedDatabase.setId(databaseSettings.getId()); + wrappedDatabase.id(databaseSettings.id()); return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(asyncDocumentClient.createDatabase(wrappedDatabase, options.toRequestOptions()).map(databaseResourceResponse -> new CosmosDatabaseResponse(databaseResourceResponse, this)).toSingle())); } @@ -258,8 +246,8 @@ public Mono createDatabase(String id) { */ public Flux> listDatabases(FeedOptions options) { return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().readDatabases(options) - .map(response-> BridgeInternal.createFeedResponse(CosmosDatabaseSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response-> BridgeInternal.createFeedResponse(CosmosDatabaseSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -305,8 +293,8 @@ public Flux> queryDatabases(String query, F public Flux> queryDatabases(SqlQuerySpec querySpec, FeedOptions options){ return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().queryDatabases(querySpec, options) .map(response-> BridgeInternal.createFeedResponse( - CosmosDatabaseSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + CosmosDatabaseSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } Mono getDatabaseAccount() { diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java similarity index 92% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java index 34143019f2f3d..64a37b8f77a50 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosClientBuilder.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java @@ -20,13 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.TokenResolver; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; +import com.azure.data.cosmos.internal.Configs; import java.util.List; @@ -37,12 +33,12 @@ *

  * {@code
  * ConnectionPolicy connectionPolicy = new ConnectionPolicy();
- * connectionPolicy.setConnectionMode(ConnectionMode.Direct);
+ * connectionPolicy.connectionMode(ConnectionMode.DIRECT);
  * CosmonsClient client = new CosmosClient.builder()
  *         .endpoint(serviceEndpoint)
  *         .key(key)
  *         .connectionPolicy(connectionPolicy)
- *         .consistencyLevel(ConsistencyLevel.Session)
+ *         .consistencyLevel(ConsistencyLevel.SESSION)
  *         .build();
  * }
  * 
diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java similarity index 91% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index 68bb673a1255e..3f91daed14afb 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -20,24 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.Trigger; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.Paths; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; +package com.azure.data.cosmos; + +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Paths; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; @@ -230,7 +216,7 @@ public Mono createItem(Object item, CosmosItemRequestOptions return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() .createDocument(getLink(), - CosmosItemSettings.fromObject(item), + CosmosItemProperties.fromObject(item), requestOptions, true) .map(response -> new CosmosItemResponse(response, @@ -306,7 +292,7 @@ public Mono upsertItem(Object item, CosmosItemRequestOptions * * @return an {@link Flux} containing one or several feed response pages of the read cosmos items or an error. */ - public Flux> listItems() { + public Flux> listItems() { return listItems(new FeedOptions()); } @@ -320,12 +306,12 @@ public Flux> listItems() { * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the read cosmos items or an error. */ - public Flux> listItems(FeedOptions options) { + public Flux> listItems(FeedOptions options) { return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(getDatabase().getDocClientWrapper() .readDocuments(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosItemSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response-> BridgeInternal.createFeedResponse(CosmosItemProperties.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -339,7 +325,7 @@ public Flux> listItems(FeedOptions options) { * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. */ - public Flux> queryItems(String query, FeedOptions options){ + public Flux> queryItems(String query, FeedOptions options){ return queryItems(new SqlQuerySpec(query), options); } @@ -354,15 +340,15 @@ public Flux> queryItems(String query, FeedOptio * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. */ - public Flux> queryItems(SqlQuerySpec querySpec, FeedOptions options){ + public Flux> queryItems(SqlQuerySpec querySpec, FeedOptions options){ return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(getDatabase() .getDocClientWrapper() .queryDocuments(getLink(), querySpec, options) .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( - CosmosItemSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders(), - response.getQueryMetrics())))); + CosmosItemProperties.getFromV2Results(response.results()), + response.responseHeaders(), + response.queryMetrics())))); } /** @@ -375,14 +361,14 @@ public Flux> queryItems(SqlQuerySpec querySpec, * @param changeFeedOptions the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. */ - public Flux> queryChangeFeedItems(ChangeFeedOptions changeFeedOptions){ + public Flux> queryChangeFeedItems(ChangeFeedOptions changeFeedOptions){ return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(getDatabase() .getDocClientWrapper() .queryDocumentChangeFeed(getLink(), changeFeedOptions) .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( - CosmosItemSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders(), response.getQueryMetrics())))); + CosmosItemProperties.getFromV2Results(response.results()), + response.responseHeaders(), response.queryMetrics())))); } /** @@ -431,8 +417,8 @@ public Mono createStoredProcedure(CosmosStoredPro options = new CosmosStoredProcedureRequestOptions(); } StoredProcedure sProc = new StoredProcedure(); - sProc.setId(settings.getId()); - sProc.setBody(settings.getBody()); + sProc.id(settings.id()); + sProc.setBody(settings.body()); return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() .createStoredProcedure(getLink(), sProc, options.toRequestOptions()) @@ -455,8 +441,8 @@ public Flux> listStoredProcedures(Fe return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(database.getDocClientWrapper() .readStoredProcedures(getLink(), options) - .map(response -> BridgeInternal.createFeedResponse(CosmosStoredProcedureSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response -> BridgeInternal.createFeedResponse(CosmosStoredProcedureSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -493,8 +479,8 @@ public Flux> queryStoredProcedures(S return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(database.getDocClientWrapper() .queryStoredProcedures(getLink(), querySpec,options) - .map(response -> BridgeInternal.createFeedResponse( CosmosStoredProcedureSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response -> BridgeInternal.createFeedResponse( CosmosStoredProcedureSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -523,8 +509,8 @@ public CosmosStoredProcedure getStoredProcedure(String id){ public Mono createUserDefinedFunction(CosmosUserDefinedFunctionSettings settings, CosmosRequestOptions options){ UserDefinedFunction udf = new UserDefinedFunction(); - udf.setId(settings.getId()); - udf.setBody(settings.getBody()); + udf.id(settings.id()); + udf.setBody(settings.body()); if(options == null){ options = new CosmosRequestOptions(); } @@ -548,8 +534,8 @@ public Flux> listUserDefinedFunc return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(database.getDocClientWrapper() .readUserDefinedFunctions(getLink(), options) - .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -584,8 +570,8 @@ public Flux> queryUserDefinedFun return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(database.getDocClientWrapper() .queryUserDefinedFunctions(getLink(),querySpec, options) - .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -636,8 +622,8 @@ public Flux> listTriggers(FeedOptions option return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(database.getDocClientWrapper() .readTriggers(getLink(), options) - .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -671,8 +657,8 @@ public Flux> queryTriggers(SqlQuerySpec quer return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(database.getDocClientWrapper() .queryTriggers(getLink(), querySpec, options) - .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -695,18 +681,18 @@ public Mono readProvisionedThroughput(){ RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + - cosmosContainerResponse.getResourceSettings().getResourceId() + cosmosContainerResponse.resourceSettings().resourceId() + "'", new FeedOptions()).toSingle())) .flatMap(offerFeedResponse -> { - if(offerFeedResponse.getResults().isEmpty()){ - return Mono.error(new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + if(offerFeedResponse.results().isEmpty()){ + return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() - .readOffer(offerFeedResponse.getResults() + .readOffer(offerFeedResponse.results() .get(0) - .getSelfLink()).toSingle())); + .selfLink()).toSingle())); }) .map(cosmosOfferResponse -> cosmosOfferResponse .getResource() @@ -725,14 +711,14 @@ public Mono replaceProvisionedThroughputAsync(int requestUnitsPerSecond RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + - cosmosContainerResponse.getResourceSettings().getResourceId() + cosmosContainerResponse.resourceSettings().resourceId() + "'", new FeedOptions()).toSingle())) .flatMap(offerFeedResponse -> { - if(offerFeedResponse.getResults().isEmpty()){ - return Mono.error(new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + if(offerFeedResponse.results().isEmpty()){ + return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } - Offer offer = offerFeedResponse.getResults().get(0); + Offer offer = offerFeedResponse.results().get(0); offer.setThroughput(requestUnitsPerSecond); return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(database.getDocClientWrapper() @@ -750,12 +736,12 @@ public CosmosDatabase getDatabase() { } @Override - protected String getURIPathSegment() { + protected String URIPathSegment() { return Paths.COLLECTIONS_PATH_SEGMENT; } @Override - protected String getParentLink() { + protected String parentLink() { return database.getLink(); } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java similarity index 66% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java index c3fdee76c9421..f2d33fd0c612b 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosContainerResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java @@ -20,10 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; +package com.azure.data.cosmos; public class CosmosContainerResponse extends CosmosResponse { @@ -32,26 +29,44 @@ public class CosmosContainerResponse extends CosmosResponse response, CosmosDatabase database) { super(response); if(response.getResource() == null){ - super.setResourceSettings(null); + super.resourceSettings(null); }else{ - super.setResourceSettings(new CosmosContainerSettings(response)); - container = new CosmosContainer(getResourceSettings().getId(), database); + super.resourceSettings(new CosmosContainerSettings(response)); + container = new CosmosContainer(resourceSettings().id(), database); } } + /** + * Gets the progress of an index transformation, if one is underway. + * + * @return the progress of an index transformation. + */ + public long indexTransformationProgress() { + return resourceResponseWrapper.getIndexTransformationProgress(); + } + + /** + * Gets the progress of lazy indexing. + * + * @return the progress of lazy indexing. + */ + public long lazyIndexingProgress() { + return resourceResponseWrapper.getLazyIndexingProgress(); + } + /** * Gets the container settings * @return the cosmos container settings */ - public CosmosContainerSettings getCosmosContainerSettings() { - return getResourceSettings(); + public CosmosContainerSettings settings() { + return resourceSettings(); } /** * Gets the Container object * @return the Cosmos container object */ - public CosmosContainer getContainer() { + public CosmosContainer container() { return container; } } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java similarity index 90% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java index 3afbe6953f7dd..cd029919fd2fc 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabase.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java @@ -20,18 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.Paths; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +package com.azure.data.cosmos; + +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Paths; import hu.akarnokd.rxjava.interop.RxJavaInterop; import org.apache.commons.lang3.StringUtils; @@ -176,7 +168,7 @@ public Mono createContainer(String id, String partition * an error. */ public Mono createContainerIfNotExists(CosmosContainerSettings containerSettings) { - CosmosContainer container = getContainer(containerSettings.getId()); + CosmosContainer container = getContainer(containerSettings.id()); return createContainerIfNotExistsInternal(containerSettings, container); } @@ -200,9 +192,9 @@ public Mono createContainerIfNotExists(String id, Strin private Mono createContainerIfNotExistsInternal(CosmosContainerSettings containerSettings, CosmosContainer container) { return container.read().onErrorResume(exception -> { - if (exception instanceof DocumentClientException) { - DocumentClientException documentClientException = (DocumentClientException) exception; - if (documentClientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { + if (exception instanceof CosmosClientException) { + CosmosClientException cosmosClientException = (CosmosClientException) exception; + if (cosmosClientException.statusCode() == HttpConstants.StatusCodes.NOTFOUND) { return createContainer(containerSettings); } } @@ -224,8 +216,8 @@ private Mono createContainerIfNotExistsInternal(CosmosC public Flux> listContainers(FeedOptions options) { //TODO: return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().readCollections(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosContainerSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response-> BridgeInternal.createFeedResponse(CosmosContainerSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -271,8 +263,8 @@ public Flux> queryContainers(SqlQuerySpec return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response-> BridgeInternal.createFeedResponse( - CosmosContainerSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + CosmosContainerSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -344,8 +336,8 @@ public Flux> listUsers(FeedOptions options){ return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(getDocClientWrapper() .readUsers(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosUserSettings.getFromV2Results(response.getResults(),this), - response.getResponseHeaders())))); + .map(response-> BridgeInternal.createFeedResponse(CosmosUserSettings.getFromV2Results(response.results(),this), + response.responseHeaders())))); } public Flux> queryUsers(String query, FeedOptions options){ @@ -368,8 +360,8 @@ public Flux> queryUsers(SqlQuerySpec querySpec, RxJavaInterop.toV2Flowable(getDocClientWrapper() .queryUsers(getLink(), querySpec, options) .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( - CosmosUserSettings.getFromV2Results(response.getResults(), this), - response.getResponseHeaders(), response.getQueryMetrics())))); + CosmosUserSettings.getFromV2Results(response.results(), this), + response.responseHeaders(), response.queryMetrics())))); } public CosmosUser getUser(String id) { @@ -386,18 +378,18 @@ public Mono readProvisionedThroughput(){ .flatMap(cosmosDatabaseResponse -> RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(getDocClientWrapper().queryOffers("select * from c where c.offerResourceId = '" + - cosmosDatabaseResponse.getResourceSettings().getResourceId() + cosmosDatabaseResponse.resourceSettings().resourceId() + "'", new FeedOptions()).toSingle())) .flatMap(offerFeedResponse -> { - if(offerFeedResponse.getResults().isEmpty()){ - return Mono.error(new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + if(offerFeedResponse.results().isEmpty()){ + return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(getDocClientWrapper() - .readOffer(offerFeedResponse.getResults() + .readOffer(offerFeedResponse.results() .get(0) - .getSelfLink()).toSingle())); + .selfLink()).toSingle())); }) .map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() @@ -416,14 +408,14 @@ public Mono replaceProvisionedThroughputAsync(int requestUnitsPerSecond RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + - cosmosDatabaseResponse.getResourceSettings().getResourceId() + cosmosDatabaseResponse.resourceSettings().resourceId() + "'", new FeedOptions()).toSingle())) .flatMap(offerFeedResponse -> { - if(offerFeedResponse.getResults().isEmpty()){ - return Mono.error(new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, + if(offerFeedResponse.results().isEmpty()){ + return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } - Offer offer = offerFeedResponse.getResults().get(0); + Offer offer = offerFeedResponse.results().get(0); offer.setThroughput(requestUnitsPerSecond); return RxJava2Adapter.singleToMono( RxJavaInterop.toV2Single(this.getDocClientWrapper() @@ -440,12 +432,12 @@ AsyncDocumentClient getDocClientWrapper(){ } @Override - protected String getURIPathSegment() { + protected String URIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } @Override - protected String getParentLink() { + protected String parentLink() { return StringUtils.EMPTY; } } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java similarity index 78% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java index bf3690aeade9c..aa37cf5ce3500 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosDatabaseResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java @@ -20,10 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.ResourceResponse; +package com.azure.data.cosmos; public class CosmosDatabaseResponse extends CosmosResponse{ private CosmosDatabase database; @@ -31,10 +28,10 @@ public class CosmosDatabaseResponse extends CosmosResponse response, CosmosClient client) { super(response); if(response.getResource() == null){ - super.setResourceSettings(null); + super.resourceSettings(null); }else{ - super.setResourceSettings(new CosmosDatabaseSettings(response)); - database = new CosmosDatabase(getResourceSettings().getId(), client); + super.resourceSettings(new CosmosDatabaseSettings(response)); + database = new CosmosDatabase(resourceSettings().id(), client); } } @@ -43,7 +40,7 @@ public class CosmosDatabaseResponse extends CosmosResponse read() { - return read(new CosmosItemRequestOptions(partitionKey)); - } - - /** - * Reads an item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos item response with the read item - * In case of failure the {@link Mono} will error. - * - * @param options the request comosItemRequestOptions - * @return an {@link Mono} containing the cosmos item response with the read item or an error - */ - public Mono read(CosmosItemRequestOptions options) { - if (options == null) { - options = new CosmosItemRequestOptions(); - } - RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase().getDocClientWrapper() - .readDocument(getLink(), requestOptions) - .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) - .toSingle())); - } - - /** - * Replaces an item with the passed in item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. - * In case of failure the {@link Mono} will error. - * - * @param item the item to replace (containing the document id). - * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. - */ - public Mono replace(Object item){ - return replace(item, new CosmosItemRequestOptions(partitionKey)); - } - - /** - * Replaces an item with the passed in item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. - * In case of failure the {@link Mono} will error. - * - * @param item the item to replace (containing the document id). - * @param options the request comosItemRequestOptions - * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. - */ - public Mono replace(Object item, CosmosItemRequestOptions options){ - Document doc = CosmosItemSettings.fromObject(item); - if (options == null) { - options = new CosmosItemRequestOptions(); - } - RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase() - .getDocClientWrapper() - .replaceDocument(getLink(), doc, requestOptions) - .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) - .toSingle())); - } - - /** - * Deletes the item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. - * In case of failure the {@link Mono} will error. - * @return an {@link Mono} containing the cosmos item resource response. - */ - public Mono delete() { - return delete(new CosmosItemRequestOptions(partitionKey)); - } - - /** - * Deletes the item. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. - * In case of failure the {@link Mono} will error. - * - * @param options the request options - * @return an {@link Mono} containing the cosmos item resource response. - */ - public Mono delete(CosmosItemRequestOptions options){ - if (options == null) { - options = new CosmosItemRequestOptions(); - } - RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(container.getDatabase() - .getDocClientWrapper() - .deleteDocument(getLink(), requestOptions) - .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) - .toSingle())); - } - - void setContainer(CosmosContainer container) { - this.container = container; - } - - @Override - protected String getURIPathSegment() { - return Paths.DOCUMENTS_PATH_SEGMENT; - } - - @Override - protected String getParentLink() { - return this.container.getLink(); - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +import com.azure.data.cosmos.internal.Paths; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Mono; + +public class CosmosItem extends CosmosResource{ + private Object partitionKey; + private CosmosContainer container; + + CosmosItem(String id, Object partitionKey, CosmosContainer container) { + super(id); + this.partitionKey = partitionKey; + this.container = container; + } + + /** + * Reads an item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos item response with the read item + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the cosmos item response with the read item or an error + */ + public Mono read() { + return read(new CosmosItemRequestOptions(partitionKey)); + } + + /** + * Reads an item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos item response with the read item + * In case of failure the {@link Mono} will error. + * + * @param options the request comosItemRequestOptions + * @return an {@link Mono} containing the cosmos item response with the read item or an error + */ + public Mono read(CosmosItemRequestOptions options) { + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase().getDocClientWrapper() + .readDocument(getLink(), requestOptions) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) + .toSingle())); + } + + /** + * Replaces an item with the passed in item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * + * @param item the item to replace (containing the document id). + * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. + */ + public Mono replace(Object item){ + return replace(item, new CosmosItemRequestOptions(partitionKey)); + } + + /** + * Replaces an item with the passed in item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * + * @param item the item to replace (containing the document id). + * @param options the request comosItemRequestOptions + * @return an {@link Mono} containing the cosmos item resource response with the replaced item or an error. + */ + public Mono replace(Object item, CosmosItemRequestOptions options){ + Document doc = CosmosItemProperties.fromObject(item); + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .replaceDocument(getLink(), doc, requestOptions) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) + .toSingle())); + } + + /** + * Deletes the item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * @return an {@link Mono} containing the cosmos item resource response. + */ + public Mono delete() { + return delete(new CosmosItemRequestOptions(partitionKey)); + } + + /** + * Deletes the item. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos item response with the replaced item. + * In case of failure the {@link Mono} will error. + * + * @param options the request options + * @return an {@link Mono} containing the cosmos item resource response. + */ + public Mono delete(CosmosItemRequestOptions options){ + if (options == null) { + options = new CosmosItemRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); + return RxJava2Adapter.singleToMono( + RxJavaInterop.toV2Single(container.getDatabase() + .getDocClientWrapper() + .deleteDocument(getLink(), requestOptions) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) + .toSingle())); + } + + void setContainer(CosmosContainer container) { + this.container = container; + } + + @Override + protected String URIPathSegment() { + return Paths.DOCUMENTS_PATH_SEGMENT; + } + + @Override + protected String parentLink() { + return this.container.getLink(); + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java similarity index 68% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java index 5d4024d6bc004..7d1ec05e614e7 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosItemResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java @@ -1,65 +1,53 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.ResourceResponse; - -public class CosmosItemResponse extends CosmosResponse{ - private CosmosItem itemClient; - - CosmosItemResponse(ResourceResponse response, PartitionKey partitionKey, CosmosContainer container) { - super(response); - if(response.getResource() == null){ - super.setResourceSettings(null); - }else{ - super.setResourceSettings(new CosmosItemSettings(response.getResource().toJson())); - itemClient = new CosmosItem(response.getResource().getId(),partitionKey, container); - } - } - - /** - * Gets the itemSettings - * @return the itemSettings - */ - public CosmosItemSettings getCosmosItemSettings() { - return getResourceSettings(); - } - - /** - * Gets the CosmosItem - * @return the cosmos item - */ - public CosmosItem getItem() { - return itemClient; - } - - /** - * Gets the CosmosItem - * @return the cosmos item - */ - public CosmosItem getCosmosItem() { - return itemClient; - } +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +public class CosmosItemResponse extends CosmosResponse{ + private CosmosItem itemClient; + + CosmosItemResponse(ResourceResponse response, PartitionKey partitionKey, CosmosContainer container) { + super(response); + if(response.getResource() == null){ + super.resourceSettings(null); + }else{ + super.resourceSettings(new CosmosItemProperties(response.getResource().toJson())); + itemClient = new CosmosItem(response.getResource().id(),partitionKey, container); + } + } + + /** + * Gets the itemSettings + * @return the itemSettings + */ + public CosmosItemProperties properties() { + return resourceSettings(); + } + + /** + * Gets the CosmosItem + * @return the cosmos item + */ + public CosmosItem item() { + return itemClient; + } } \ No newline at end of file diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermission.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java similarity index 95% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermission.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java index 995dcff0dfef3..72e2b845ff334 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermission.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java @@ -20,10 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.internal.Paths; +import com.azure.data.cosmos.internal.Paths; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Mono; @@ -98,12 +97,12 @@ public Mono delete(CosmosPermissionsRequestOptions opt } @Override - protected String getURIPathSegment() { + protected String URIPathSegment() { return Paths.PERMISSIONS_PATH_SEGMENT; } @Override - protected String getParentLink() { + protected String parentLink() { return cosmosUser.getLink(); } } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java similarity index 83% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java index 1724654dfe51f..319b32a187afd 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosPermissionResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java @@ -20,10 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.ResourceResponse; +package com.azure.data.cosmos; public class CosmosPermissionResponse extends CosmosResponse { CosmosPermission permissionClient; @@ -31,10 +28,10 @@ public class CosmosPermissionResponse extends CosmosResponse response, CosmosUser cosmosUser) { super(response); if(response.getResource() == null){ - super.setResourceSettings(null); + super.resourceSettings(null); }else{ - super.setResourceSettings(new CosmosPermissionSettings(response.getResource().toJson())); - permissionClient = new CosmosPermission(response.getResource().getId(), cosmosUser); + super.resourceSettings(new CosmosPermissionSettings(response.getResource().toJson())); + permissionClient = new CosmosPermission(response.getResource().id(), cosmosUser); } } @@ -43,7 +40,7 @@ public class CosmosPermissionResponse extends CosmosResponse * After subscription the operation will be performed. * The {@link Mono} upon successful completion will contain a single resource response with the read stored diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java similarity index 78% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java index 757c659992f57..b547d5f3895e8 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosStoredProcedureResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java @@ -20,11 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.StoredProcedureResponse; +package com.azure.data.cosmos; public class CosmosStoredProcedureResponse extends CosmosResponse { @@ -34,8 +30,8 @@ public class CosmosStoredProcedureResponse extends CosmosResponse response, CosmosContainer cosmosContainer) { super(response); if(response.getResource() != null){ - super.setResourceSettings(new CosmosStoredProcedureSettings(response)); - storedProcedure = new CosmosStoredProcedure(getResourceSettings().getId(), cosmosContainer); + super.resourceSettings(new CosmosStoredProcedureSettings(response)); + storedProcedure = new CosmosStoredProcedure(resourceSettings().id(), cosmosContainer); } } @@ -48,15 +44,15 @@ public class CosmosStoredProcedureResponse extends CosmosResponse { @@ -33,9 +30,9 @@ public class CosmosTriggerResponse extends CosmosResponse CosmosTriggerResponse(ResourceResponse response, CosmosContainer container) { super(response); if(response.getResource() != null) { - super.setResourceSettings(new CosmosTriggerSettings(response)); + super.resourceSettings(new CosmosTriggerSettings(response)); cosmosTriggerSettings = new CosmosTriggerSettings(response); - cosmosTrigger = new CosmosTrigger(cosmosTriggerSettings.getId(), container); + cosmosTrigger = new CosmosTrigger(cosmosTriggerSettings.id(), container); } } @@ -44,7 +41,7 @@ public class CosmosTriggerResponse extends CosmosResponse * * @return {@link CosmosTriggerSettings} */ - public CosmosTriggerSettings getCosmosTriggerSettings() { + public CosmosTriggerSettings settings() { return cosmosTriggerSettings; } @@ -53,7 +50,7 @@ public CosmosTriggerSettings getCosmosTriggerSettings() { * * @return {@link CosmosTrigger} */ - public CosmosTrigger getCosmosTrigger() { + public CosmosTrigger trigger() { return cosmosTrigger; } } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java similarity index 87% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java index 8d9af78a0c29f..0a04703beef9c 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUser.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java @@ -1,11 +1,6 @@ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.internal.Paths; +import com.azure.data.cosmos.internal.Paths; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; @@ -13,7 +8,7 @@ public class CosmosUser extends CosmosResource { CosmosDatabase database; - public CosmosUser(String id, CosmosDatabase database) { + CosmosUser(String id, CosmosDatabase database) { super(id); this.database = database; } @@ -38,7 +33,7 @@ public Mono read(RequestOptions options) { } /** - * Replace a cosmos user + * REPLACE a cosmos user * * @param userSettings the user settings to use * @param options the request options @@ -51,7 +46,7 @@ public Mono replace(CosmosUserSettings userSettings, Request } /** - * Delete a cosmos user + * DELETE a cosmos user * * @param options the request options * @return a {@link Mono} containing the single resource response with the deleted user or an error. @@ -121,8 +116,8 @@ public Flux> listPermissions(FeedOptions return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(getDatabase().getDocClientWrapper() .readPermissions(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } /** @@ -140,21 +135,21 @@ public Flux> queryPermissions(String quer return RxJava2Adapter.flowableToFlux( RxJavaInterop.toV2Flowable(getDatabase().getDocClientWrapper() .queryPermissions(getLink(), query, options) - .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionSettings.getFromV2Results(response.getResults()), - response.getResponseHeaders())))); + .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionSettings.getFromV2Results(response.results()), + response.responseHeaders())))); } @Override - protected String getURIPathSegment() { + protected String URIPathSegment() { return Paths.USERS_PATH_SEGMENT; } @Override - protected String getParentLink() { + protected String parentLink() { return database.getLink() ; } - CosmosDatabase getDatabase() { + public CosmosDatabase getDatabase() { return database; } } \ No newline at end of file diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunction.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java similarity index 93% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunction.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java index 0519674e96686..5c8e9ca89bddb 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunction.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java @@ -20,11 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import com.microsoft.azure.cosmosdb.internal.Paths; +import com.azure.data.cosmos.internal.Paths; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Mono; @@ -39,7 +37,7 @@ public class CosmosUserDefinedFunction extends CosmosResource{ } /** - * Read a user defined function. + * READ a user defined function. *

* After subscription the operation will be performed. * The {@link Mono} upon successful completion will contain a single resource response for the read user defined @@ -98,12 +96,12 @@ public Mono delete(CosmosRequestOptions options){ } @Override - protected String getURIPathSegment() { + protected String URIPathSegment() { return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT; } @Override - protected String getParentLink() { + protected String parentLink() { return container.getLink(); } } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java similarity index 80% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java index 59251a9f93c12..ce58d4c5d5272 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserDefinedFunctionResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java @@ -1,57 +1,54 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; - -public class CosmosUserDefinedFunctionResponse extends CosmosResponse { - - private CosmosUserDefinedFunctionSettings cosmosUserDefinedFunctionSettings; - private CosmosUserDefinedFunction cosmosUserDefinedFunction; - - CosmosUserDefinedFunctionResponse(ResourceResponse response, CosmosContainer container) { - super(response); - if(response.getResource() != null) { - super.setResourceSettings(new CosmosUserDefinedFunctionSettings(response)); - cosmosUserDefinedFunctionSettings = new CosmosUserDefinedFunctionSettings(response); - cosmosUserDefinedFunction = new CosmosUserDefinedFunction(cosmosUserDefinedFunctionSettings.getId(), container); - } - } - - /** - * Gets the cosmos user defined function settings - * @return the cosmos user defined function settings - */ - public CosmosUserDefinedFunctionSettings getCosmosUserDefinedFunctionSettings() { - return cosmosUserDefinedFunctionSettings; - } - - /** - * Gets the cosmos user defined function object - * @return the cosmos user defined function object - */ - public CosmosUserDefinedFunction getCosmosUserDefinedFunction() { - return cosmosUserDefinedFunction; - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +public class CosmosUserDefinedFunctionResponse extends CosmosResponse { + + private CosmosUserDefinedFunctionSettings cosmosUserDefinedFunctionSettings; + private CosmosUserDefinedFunction cosmosUserDefinedFunction; + + CosmosUserDefinedFunctionResponse(ResourceResponse response, CosmosContainer container) { + super(response); + if(response.getResource() != null) { + super.resourceSettings(new CosmosUserDefinedFunctionSettings(response)); + cosmosUserDefinedFunctionSettings = new CosmosUserDefinedFunctionSettings(response); + cosmosUserDefinedFunction = new CosmosUserDefinedFunction(cosmosUserDefinedFunctionSettings.id(), container); + } + } + + /** + * Gets the cosmos user defined function settings + * @return the cosmos user defined function settings + */ + public CosmosUserDefinedFunctionSettings settings() { + return cosmosUserDefinedFunctionSettings; + } + + /** + * Gets the cosmos user defined function object + * @return the cosmos user defined function object + */ + public CosmosUserDefinedFunction userDefinedFunction() { + return cosmosUserDefinedFunction; + } +} diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java similarity index 52% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java index 6b9f8b9a36ef8..897dc22b4c7ca 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java @@ -1,7 +1,4 @@ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.User; +package com.azure.data.cosmos; public class CosmosUserResponse extends CosmosResponse { private CosmosUser user; @@ -9,10 +6,10 @@ public class CosmosUserResponse extends CosmosResponse { CosmosUserResponse(ResourceResponse response, CosmosDatabase database) { super(response); if(response.getResource() == null){ - super.setResourceSettings(null); + super.resourceSettings(null); }else{ - super.setResourceSettings(new CosmosUserSettings(response)); - this.user = new CosmosUser(getResourceSettings().getId(), database); + super.resourceSettings(new CosmosUserSettings(response)); + this.user = new CosmosUser(resourceSettings().id(), database); } } @@ -21,7 +18,7 @@ public class CosmosUserResponse extends CosmosResponse { * * @return {@link CosmosUser} */ - public CosmosUser getUser() { + public CosmosUser user() { return user; } @@ -30,9 +27,7 @@ public CosmosUser getUser() { * * @return {@link CosmosUserSettings} */ - public CosmosUserSettings getCosmosUserSettings(){ - return getResourceSettings(); + public CosmosUserSettings settings(){ + return resourceSettings(); } - - } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java similarity index 80% rename from sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java index 5459fe1751f47..ad1efea18e057 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/CosmosUserSettings.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java @@ -1,9 +1,6 @@ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.internal.Constants; +import com.azure.data.cosmos.internal.Constants; import java.util.List; import java.util.stream.Collectors; @@ -42,8 +39,8 @@ static List getFromV2Results(List results, CosmosDatab * * @return the permissions link. */ - public String getPermissionsLink() { - String selfLink = this.getSelfLink(); + public String permissionsLink() { + String selfLink = this.selfLink(); if (selfLink.endsWith("/")) { return selfLink + super.getString(Constants.Properties.PERMISSIONS_LINK); } else { diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Bootstrapper.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/Bootstrapper.java similarity index 96% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Bootstrapper.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/Bootstrapper.java index 28ed213f731c9..eb8531657596f 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Bootstrapper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/Bootstrapper.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationToken.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationToken.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationToken.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationToken.java index 7d169c8cc4dd2..da39c5af6069b 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationToken.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationToken.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; /** * Propagates notification that operations should be canceled.. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationTokenSource.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationTokenSource.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationTokenSource.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationTokenSource.java index 587b9fa92f576..964196cdceded 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CancellationTokenSource.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationTokenSource.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import java.io.Closeable; import java.io.IOException; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ChangeFeedContextClient.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ChangeFeedContextClient.java similarity index 83% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ChangeFeedContextClient.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/ChangeFeedContextClient.java index 6ce5e488a79f3..b7d2dbfe39083 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ChangeFeedContextClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ChangeFeedContextClient.java @@ -20,25 +20,24 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; - -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerResponse; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseRequestOptions; -import com.microsoft.azure.cosmos.CosmosDatabaseResponse; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemResponse; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; +package com.azure.data.cosmos.changefeed; + +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosContainerResponse; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseRequestOptions; +import com.azure.data.cosmos.CosmosDatabaseResponse; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.CosmosItemResponse; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.SqlQuerySpec; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -64,7 +63,7 @@ public interface ChangeFeedContextClient { * @param feedOptions The options for processing the query results feed. * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. */ - Flux> createDocumentChangeFeedQuery(CosmosContainer collectionLink, ChangeFeedOptions feedOptions); + Flux> createDocumentChangeFeedQuery(CosmosContainer collectionLink, ChangeFeedOptions feedOptions); /** * Reads a database. @@ -97,7 +96,7 @@ Mono createItem(CosmosContainer containerLink, Object docume boolean disableAutomaticIdGeneration); /** - * Delete a {@link CosmosItem}. + * DELETE a {@link CosmosItem}. * * @param itemLink the item reference. * @param options the request options. @@ -132,7 +131,7 @@ Mono createItem(CosmosContainer containerLink, Object docume * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. */ - Flux> queryItems(CosmosContainer containerLink, SqlQuerySpec querySpec, FeedOptions options); + Flux> queryItems(CosmosContainer containerLink, SqlQuerySpec querySpec, FeedOptions options); /** * @return the Cosmos client's service endpoint. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CheckpointFrequency.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/CheckpointFrequency.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CheckpointFrequency.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/CheckpointFrequency.java index d48e738bdf41e..4d19665fade2f 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/CheckpointFrequency.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/CheckpointFrequency.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import java.time.Duration; @@ -34,7 +34,7 @@ public class CheckpointFrequency { public CheckpointFrequency() { this.explicitCheckpoint = false; - // Default to always checkpoint after processing each feed batch. + // DEFAULT to always checkpoint after processing each feed batch. processedDocumentCount = 0; timeInterval = null; } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ContainerConnectionInfo.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ContainerConnectionInfo.java similarity index 95% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ContainerConnectionInfo.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/ContainerConnectionInfo.java index c7fd1be36b01c..6ce60b11999d1 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ContainerConnectionInfo.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ContainerConnectionInfo.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; import java.net.URI; import java.net.URISyntaxException; @@ -44,7 +44,7 @@ public class ContainerConnectionInfo { */ public ContainerConnectionInfo() { this.connectionPolicy = new ConnectionPolicy(); - this.consistencyLevel = ConsistencyLevel.Session; + this.consistencyLevel = ConsistencyLevel.SESSION; } /** @@ -71,7 +71,7 @@ public ConnectionPolicy getConnectionPolicy() { } /** - * Gets the consistency level; default is "Session". + * Gets the consistency level; default is "SESSION". * @return the consistency level. */ public ConsistencyLevel getConsistencyLevel() { diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitor.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitor.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitor.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitor.java index a3a91971529b7..6afae75c7cdc3 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitor.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitoringRecord.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitoringRecord.java similarity index 98% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitoringRecord.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitoringRecord.java index 971ff55664541..a875cfcd5ddbf 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/HealthMonitoringRecord.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitoringRecord.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; /** * A record used in the health monitoring. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Lease.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/Lease.java similarity index 86% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Lease.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/Lease.java index 1a3841915c636..3b10675c61dd7 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/Lease.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/Lease.java @@ -20,20 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import com.microsoft.azure.cosmos.ChangeFeedProcessor; +import com.azure.data.cosmos.ChangeFeedProcessor; -import java.time.ZoneId; import java.time.ZonedDateTime; -import java.util.Date; import java.util.Map; /** * Represents a lease that is persisted as a document in the lease collection. *

* Leases are used to: - * Keep track of the {@link ChangeFeedProcessor} progress for a particular Partition Key Range. + * Keep track of the {@link ChangeFeedProcessor} progress for a particular Partition Key RANGE. * Distribute load between different instances of {@link ChangeFeedProcessor}. * Ensure reliable recovery for cases when an instance of {@link ChangeFeedProcessor} gets disconnected, hangs or crashes. */ @@ -49,7 +47,7 @@ public interface Lease { * Gets the host name owner of the lease. * *

- * The Owner keeps track which {@link ChangeFeedProcessor} is currently processing that Partition Key Range. + * The Owner keeps track which {@link ChangeFeedProcessor} is currently processing that Partition Key RANGE. * * @return the host name owner of the lease. */ @@ -92,9 +90,9 @@ public interface Lease { String getConcurrencyToken(); /** - * Gets the custom lease properties which can be managed from {@link PartitionLoadBalancingStrategy}. + * Gets the custom lease item which can be managed from {@link PartitionLoadBalancingStrategy}. * - * @return the custom lease properties. + * @return the custom lease item. */ Map getProperties(); @@ -102,7 +100,7 @@ public interface Lease { * Sets the host name owner of the lease. * *

- * The Owner keeps track which {@link ChangeFeedProcessor} is currently processing that Partition Key Range. + * The Owner keeps track which {@link ChangeFeedProcessor} is currently processing that Partition Key RANGE. * * @param owner the host name owner of the lease. */ @@ -135,10 +133,10 @@ public interface Lease { void setConcurrencyToken(String concurrencyToken); /** - * Sets the custom lease properties which can be managed from {@link PartitionLoadBalancingStrategy}. + * Sets the custom lease item which can be managed from {@link PartitionLoadBalancingStrategy}. * * - * @param properties the custom lease properties. + * @param properties the custom lease item. */ void setProperties(Map properties); } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseCheckpointer.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseCheckpointer.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseCheckpointer.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseCheckpointer.java index 8484aa40f6b2e..501595f13f1ff 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseCheckpointer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseCheckpointer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseContainer.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseContainer.java similarity index 96% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseContainer.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseContainer.java index 62a8daa321245..0af0613e4810c 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseContainer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Flux; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseManager.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseManager.java similarity index 91% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseManager.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseManager.java index b1c658b8931a8..44c85186b8bb1 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseManager.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseManager.java @@ -20,11 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import com.microsoft.azure.cosmos.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; -import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** @@ -76,10 +75,10 @@ public interface LeaseManager { Mono renew(Lease lease); /** - * Replace properties from the specified lease. + * REPLACE item from the specified lease. * It can throw {@link LeaseLostException} if other host acquired the lease. * - * @param leaseToUpdatePropertiesFrom the new properties. + * @param leaseToUpdatePropertiesFrom the new item. * @return updated lease. */ Mono updateProperties(Lease leaseToUpdatePropertiesFrom); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseRenewer.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseRenewer.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseRenewer.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseRenewer.java index 41b618518f417..1eca3a46aa61a 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseRenewer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseRenewer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStore.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStore.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStore.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStore.java index adee8dffef66f..e656044cdb910 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStore.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStore.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManager.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManager.java similarity index 94% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManager.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManager.java index e9139961083e5..d11e3e8866e10 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManager.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManager.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.changefeed.internal.LeaseStoreManagerImpl; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.changefeed.internal.LeaseStoreManagerImpl; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -76,7 +76,7 @@ static LeaseStoreManagerBuilderDefinition Builder() { Mono createLeaseIfNotExist(String leaseToken, String continuationToken); /** - * Delete the lease. + * DELETE the lease. * * @param lease the lease to remove. * @return a representation of the deferred computation of this call. @@ -108,9 +108,9 @@ static LeaseStoreManagerBuilderDefinition Builder() { Mono renew(Lease lease); /** - * Replace properties from the specified lease. + * REPLACE item from the specified lease. * - * @param leaseToUpdatePropertiesFrom the Lease containing new properties. + * @param leaseToUpdatePropertiesFrom the Lease containing new item. * @return the updated lease. */ Mono updateProperties(Lease leaseToUpdatePropertiesFrom); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManagerSettings.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManagerSettings.java similarity index 95% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManagerSettings.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManagerSettings.java index 6c474db4755ee..d2e2f9da56c5e 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/LeaseStoreManagerSettings.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManagerSettings.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import com.microsoft.azure.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainer; /** * Captures LeaseStoreManager settings. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionCheckpointer.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionCheckpointer.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionCheckpointer.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionCheckpointer.java index 4982f8eed93da..298fd5956f8c9 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionCheckpointer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionCheckpointer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionController.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionController.java similarity index 95% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionController.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionController.java index 3b434e9830fb0..1c9871a2fc0d5 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionController.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionController.java @@ -20,9 +20,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancer.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancer.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancer.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancer.java index ea467404242ae..e10d6320640d1 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancingStrategy.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancingStrategy.java similarity index 87% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancingStrategy.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancingStrategy.java index 6fac50cc661bd..865c034e28bea 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionLoadBalancingStrategy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancingStrategy.java @@ -20,26 +20,26 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import com.microsoft.azure.cosmos.ChangeFeedProcessorOptions; +import com.azure.data.cosmos.ChangeFeedProcessorOptions; import java.util.List; /** * A strategy defines which leases should be taken by the current host in a certain moment. *

- * It can set new {@link Lease} getProperties() for all returned leases if needed, including currently owned leases. + * It can set new {@link Lease} properties() for all returned leases if needed, including currently owned leases. * Example *

  * {@code
  *  public class CustomStrategy : PartitionLoadBalancingStrategy
  *  {
- *      private String hostName;
- *      private String hostVersion;
+ *      private STRING hostName;
+ *      private STRING hostVersion;
  *      private Duration leaseExpirationInterval;
  *
- *      private final String VersionPropertyKey = "version";
+ *      private final STRING VersionPropertyKey = "version";
  *
  *      public List selectLeasesToTake(List allLeases)
  *      {
@@ -88,9 +88,9 @@
 public interface PartitionLoadBalancingStrategy {
     /**
      * Select leases that should be taken for processing.
-     * This method will be called periodically with {@link ChangeFeedProcessorOptions} getLeaseAcquireInterval().
+     * This method will be called periodically with {@link ChangeFeedProcessorOptions} leaseAcquireInterval().
 
-     * @param allLeases All leases.
+     * @param allLeases ALL leases.
      * @return Leases that should be taken for processing by this host.
      */
     List selectLeasesToTake(List allLeases);
diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionManager.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionManager.java
similarity index 97%
rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionManager.java
rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionManager.java
index 7552e4d87d7bf..adcbb26bf439d 100644
--- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionManager.java
+++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionManager.java
@@ -20,7 +20,7 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */
-package com.microsoft.azure.cosmos.changefeed;
+package com.azure.data.cosmos.changefeed;
 
 import reactor.core.publisher.Mono;
 
diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessor.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessor.java
similarity index 90%
rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessor.java
rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessor.java
index 6661a50359c45..fcbac93e50e50 100644
--- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessor.java
+++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessor.java
@@ -20,10 +20,10 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */
-package com.microsoft.azure.cosmos.changefeed;
+package com.azure.data.cosmos.changefeed;
 
-import com.microsoft.azure.cosmos.ChangeFeedObserver;
-import com.microsoft.azure.cosmos.ChangeFeedObserverContext;
+import com.azure.data.cosmos.ChangeFeedObserver;
+import com.azure.data.cosmos.ChangeFeedObserverContext;
 import reactor.core.publisher.Mono;
 
 /**
@@ -31,7 +31,7 @@
  * 

* Created by {@link PartitionProcessorFactory}.create() after some lease is acquired by the current host. * Processing can perform the following tasks in a loop: - * 1. Read some data from the resource partition. + * 1. READ some data from the resource partition. * 2. Handle possible problems with the read. * 3. Pass the obtained data to an observer by calling {@link ChangeFeedObserver}.processChangesAsync{} with the context {@link ChangeFeedObserverContext}. */ diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessorFactory.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessorFactory.java similarity index 94% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessorFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessorFactory.java index eca114f1e4d9a..c7194df7972a2 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionProcessorFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessorFactory.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import com.microsoft.azure.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.ChangeFeedObserver; /** * Factory class used to create instance(s) of {@link PartitionProcessor}. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisor.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisor.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisor.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisor.java index 863636ae7a78c..442a34182bf64 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisor.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisorFactory.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisorFactory.java similarity index 96% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisorFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisorFactory.java index dd17035a5bcb7..a15763e00e85f 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSupervisorFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisorFactory.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; /** * Interface for the partition supervisor factory. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSynchronizer.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSynchronizer.java similarity index 93% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSynchronizer.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSynchronizer.java index 3dac20d777a32..89173d1fae0f0 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/PartitionSynchronizer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSynchronizer.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** - * Read DocDB partitions and create leases if they do not exist. + * READ DocDB partitions and create leases if they do not exist. */ public interface PartitionSynchronizer { /** diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ProcessorSettings.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ProcessorSettings.java similarity index 88% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ProcessorSettings.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/ProcessorSettings.java index 4b3dd5a009594..ad0f04e5bccb2 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ProcessorSettings.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ProcessorSettings.java @@ -20,12 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import com.microsoft.azure.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainer; import java.time.Duration; -import java.time.ZonedDateTime; +import java.time.OffsetDateTime; /** * Implementation for the partition processor settings. @@ -36,8 +36,8 @@ public class ProcessorSettings { private Integer maxItemCount; private Duration feedPollDelay; private String startContinuation; - private ZonedDateTime startTime; -// private String sessionToken; + private OffsetDateTime startTime; +// private STRING sessionToken; public CosmosContainer getCollectionSelfLink() { return this.collectionSelfLink; @@ -95,21 +95,21 @@ public ProcessorSettings withStartFromBeginning(boolean startFromBeginning) { return this; } - public ZonedDateTime getStartTime() { + public OffsetDateTime getStartTime() { return this.startTime; } - public ProcessorSettings withStartTime(ZonedDateTime startTime) { + public ProcessorSettings withStartTime(OffsetDateTime startTime) { this.startTime = startTime; return this; } // This is not currently supported in Java implementation. -// public String getSessionToken() { +// public STRING sessionToken() { // return this.sessionToken; // } // -// public ProcessorSettings withSessionToken(String sessionToken) { +// public ProcessorSettings sessionToken(STRING sessionToken) { // this.sessionToken = sessionToken; // return this; // } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingPartitionWork.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingPartitionWork.java similarity index 96% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingPartitionWork.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingPartitionWork.java index c40341a47fa1c..4c325534bcc69 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingPartitionWork.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingPartitionWork.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; /** * Interface for remaining partition work. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingWorkEstimator.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingWorkEstimator.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingWorkEstimator.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingWorkEstimator.java index f5d02380ef26b..c7ecc032ca8f4 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RemainingWorkEstimator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingWorkEstimator.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RequestOptionsFactory.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/RequestOptionsFactory.java similarity index 87% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RequestOptionsFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/RequestOptionsFactory.java index 09abe1efcc80a..fcdbe03d69192 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/RequestOptionsFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/RequestOptionsFactory.java @@ -20,11 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.RequestOptions; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.FeedOptions; /** * Defines request options for lease requests to use with {@link LeaseStoreManager}. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLease.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLease.java similarity index 92% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLease.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLease.java index 5f802baed0812..dd15a593b153a 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLease.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLease.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmos.changefeed.internal.Constants; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.changefeed.internal.Constants; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -40,7 +40,7 @@ public class ServiceItemLease implements Lease { private static final ZonedDateTime UNIX_START_TIME = ZonedDateTime.parse("1970-01-01T00:00:00.0Z[UTC]"); - // TODO: add JSON annotations and rename the properties. + // TODO: add JSON annotations and rename the item. private String id; private String _etag; private String LeaseToken; @@ -211,18 +211,18 @@ public String getConcurrencyToken() { public static ServiceItemLease fromDocument(Document document) { return new ServiceItemLease() - .withId(document.getId()) - .withEtag(document.getETag()) + .withId(document.id()) + .withEtag(document.etag()) .withTs(document.getString(Constants.Properties.LAST_MODIFIED)) .withOwner(document.getString("Owner")) .withLeaseToken(document.getString("LeaseToken")) .withContinuationToken(document.getString("ContinuationToken")); } - public static ServiceItemLease fromDocument(CosmosItemSettings document) { + public static ServiceItemLease fromDocument(CosmosItemProperties document) { return new ServiceItemLease() - .withId(document.getId()) - .withEtag(document.getETag()) + .withId(document.id()) + .withEtag(document.etag()) .withTs(document.getString(Constants.Properties.LAST_MODIFIED)) .withOwner(document.getString("Owner")) .withLeaseToken(document.getString("LeaseToken")) diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLeaseUpdater.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLeaseUpdater.java similarity index 87% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLeaseUpdater.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLeaseUpdater.java index 32f2141193904..bca52fbdd9fd2 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/ServiceItemLeaseUpdater.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLeaseUpdater.java @@ -20,11 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed; +package com.azure.data.cosmos.changefeed; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmosdb.RequestOptions; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemRequestOptions; import reactor.core.publisher.Mono; import java.util.function.Function; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/LeaseLostException.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/LeaseLostException.java similarity index 96% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/LeaseLostException.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/LeaseLostException.java index ff9b536605e3d..61bf59ee18ced 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/LeaseLostException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/LeaseLostException.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.changefeed.exceptions; -import com.microsoft.azure.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.Lease; /** * Exception occurred when lease is lost, that would typically happen when it is taken by another host. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/ObserverException.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/ObserverException.java similarity index 96% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/ObserverException.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/ObserverException.java index c10b1cc403eb6..225cff2039389 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/ObserverException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/ObserverException.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.changefeed.exceptions; /** * Exception occurred when an operation in a ChangeFeedObserver is running and throws by user code. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionException.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionException.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionException.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionException.java index 137e55e15f06e..a0d890d8062e2 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionException.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.changefeed.exceptions; /** * General exception occurred during partition processing. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionNotFoundException.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionNotFoundException.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionNotFoundException.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionNotFoundException.java index c0d95bc0bbad2..d9b8206ae157d 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionNotFoundException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionNotFoundException.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.changefeed.exceptions; /** * Exception occurred when partition wasn't found. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionSplitException.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionSplitException.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionSplitException.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionSplitException.java index 6a0d29bba56bd..424e8d09f6381 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/PartitionSplitException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionSplitException.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.changefeed.exceptions; /** * Exception occurred during partition split. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/TaskCancelledException.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/TaskCancelledException.java similarity index 96% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/TaskCancelledException.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/TaskCancelledException.java index 0bcb50636f4ad..626aa3f4246c0 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/exceptions/TaskCancelledException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/TaskCancelledException.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.changefeed.exceptions; /** * Exception occurred when an operation in a ChangeFeedObserver was canceled. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/AutoCheckpointer.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/AutoCheckpointer.java similarity index 88% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/AutoCheckpointer.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/AutoCheckpointer.java index e55a18a2d62f8..c7b0df8f5d996 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/AutoCheckpointer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/AutoCheckpointer.java @@ -20,14 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.ChangeFeedObserver; -import com.microsoft.azure.cosmos.ChangeFeedObserverCloseReason; -import com.microsoft.azure.cosmos.ChangeFeedObserverContext; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.changefeed.CheckpointFrequency; +import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.ChangeFeedObserverCloseReason; +import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.changefeed.CheckpointFrequency; import java.time.Duration; import java.time.ZoneId; @@ -63,7 +62,7 @@ public void close(ChangeFeedObserverContext context, ChangeFeedObserverCloseReas } @Override - public void processChanges(ChangeFeedObserverContext context, List docs) { + public void processChanges(ChangeFeedObserverContext context, List docs) { this.observer.processChanges(context, docs); this.processedDocCount ++; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/BootstrapperImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/BootstrapperImpl.java similarity index 94% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/BootstrapperImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/BootstrapperImpl.java index cbe42f6234422..c3fd5af65f63d 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/BootstrapperImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/BootstrapperImpl.java @@ -20,11 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.changefeed.Bootstrapper; -import com.microsoft.azure.cosmos.changefeed.LeaseStore; -import com.microsoft.azure.cosmos.changefeed.PartitionSynchronizer; +import com.azure.data.cosmos.changefeed.Bootstrapper; +import com.azure.data.cosmos.changefeed.LeaseStore; +import com.azure.data.cosmos.changefeed.PartitionSynchronizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java similarity index 79% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java index 91d57143f7248..b09968c6de410 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java @@ -20,28 +20,26 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; - -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerResponse; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseRequestOptions; -import com.microsoft.azure.cosmos.CosmosDatabaseResponse; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemResponse; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +package com.azure.data.cosmos.changefeed.internal; + +import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosContainerResponse; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseRequestOptions; +import com.azure.data.cosmos.CosmosDatabaseResponse; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.CosmosItemResponse; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.AsyncDocumentClient; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; @@ -100,7 +98,7 @@ public Flux> readPartitionKeyRangeFeed(String pa } @Override - public Flux> createDocumentChangeFeedQuery(CosmosContainer collectionLink, ChangeFeedOptions feedOptions) { + public Flux> createDocumentChangeFeedQuery(CosmosContainer collectionLink, ChangeFeedOptions feedOptions) { return collectionLink.queryChangeFeedItems(feedOptions) .subscribeOn(this.rxScheduler); } @@ -142,7 +140,7 @@ public Mono readItem(CosmosItem itemLink, CosmosItemRequestO } @Override - public Flux> queryItems(CosmosContainer containerLink, SqlQuerySpec querySpec, FeedOptions options) { + public Flux> queryItems(CosmosContainer containerLink, SqlQuerySpec querySpec, FeedOptions options) { return containerLink.queryItems(querySpec, options) .subscribeOn(this.rxScheduler); } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedHelper.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedHelper.java similarity index 87% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedHelper.java index 4935852e667fc..7639ec6b6b705 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedHelper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedHelper.java @@ -20,14 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerResponse; -import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; -import com.microsoft.azure.cosmos.changefeed.ContainerConnectionInfo; -import reactor.core.publisher.Mono; +import com.azure.data.cosmos.changefeed.ContainerConnectionInfo; import java.net.MalformedURLException; import java.net.URI; @@ -35,9 +30,9 @@ import java.net.URL; import java.util.Map; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.Paths.COLLECTIONS_PATH_SEGMENT; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.Paths.DATABASES_ROOT; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.Paths.DOCUMENTS_PATH_SEGMENT; +import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.Paths.COLLECTIONS_PATH_SEGMENT; +import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.Paths.DATABASES_ROOT; +import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.Paths.DOCUMENTS_PATH_SEGMENT; /** * Implement static methods used for various simple transformations and tasks. @@ -58,10 +53,10 @@ public static ContainerConnectionInfo canonicalize(ContainerConnectionInfo lease if (leaseCollectionLocation == null || leaseCollectionLocation.getConnectionPolicy() == null) { throw new IllegalArgumentException("leaseCollectionLocation"); } - if (leaseCollectionLocation.getConnectionPolicy().getUserAgentSuffix() == null - || leaseCollectionLocation.getConnectionPolicy().getUserAgentSuffix().isEmpty()) { + if (leaseCollectionLocation.getConnectionPolicy().userAgentSuffix() == null + || leaseCollectionLocation.getConnectionPolicy().userAgentSuffix().isEmpty()) { result = new ContainerConnectionInfo(leaseCollectionLocation); - result.getConnectionPolicy().setUserAgentSuffix(DEFAULT_USER_AGENT_SUFFIX); + result.getConnectionPolicy().userAgentSuffix(DEFAULT_USER_AGENT_SUFFIX); } return result; @@ -139,7 +134,7 @@ public static String getUrlPath(String path) { } /** - * Copied from com.microsoft.azure.cosmosdb.internal.Paths. + * Copied from com.azure.data.cosmos.internal.Paths. */ public static class Paths { static final String ROOT = "/"; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java similarity index 81% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java index 1dac68a5df7fb..5d917c11a54d8 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java @@ -20,14 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.ChangeFeedObserverContext; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.changefeed.PartitionCheckpointer; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.changefeed.PartitionCheckpointer; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Mono; /** @@ -36,7 +35,7 @@ public class ChangeFeedObserverContextImpl implements ChangeFeedObserverContext { private final PartitionCheckpointer checkpointer; private final String partitionKeyRangeId; - private final FeedResponse feedResponse; + private final FeedResponse feedResponse; private String responseContinuation; public ChangeFeedObserverContextImpl(String leaseToken) { @@ -45,7 +44,7 @@ public ChangeFeedObserverContextImpl(String leaseToken) { this.feedResponse = null; } - public ChangeFeedObserverContextImpl(String leaseToken, FeedResponse feedResponse, PartitionCheckpointer checkpointer) + public ChangeFeedObserverContextImpl(String leaseToken, FeedResponse feedResponse, PartitionCheckpointer checkpointer) { this.partitionKeyRangeId = leaseToken; this.feedResponse = feedResponse; @@ -63,7 +62,7 @@ public ChangeFeedObserverContextImpl(String leaseToken, FeedResponse checkpoint() { - this.responseContinuation = this.feedResponse.getResponseContinuation(); + this.responseContinuation = this.feedResponse.continuationToken(); return this.checkpointer.checkpointPartition(this.responseContinuation); } @@ -80,7 +79,7 @@ public String getPartitionKeyRangeId() { * @return the response from the underlying call. */ @Override - public FeedResponse getFeedResponse() { + public FeedResponse getFeedResponse() { return this.feedResponse; } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java similarity index 84% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java index d7ec55ec27705..6c001b584bb11 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java @@ -20,14 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.ChangeFeedObserver; -import com.microsoft.azure.cosmos.ChangeFeedObserverFactory; -import com.microsoft.azure.cosmos.changefeed.exceptions.ObserverException; +import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.changefeed.exceptions.ObserverException; +import com.azure.data.cosmos.ChangeFeedObserverFactory; /** - * Default implementation for {@link ChangeFeedObserverFactory}. + * DEFAULT implementation for {@link ChangeFeedObserverFactory}. */ public class ChangeFeedObserverFactoryImpl implements ChangeFeedObserverFactory { private final Class observerType; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java similarity index 87% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java index 3b445ae3bf42e..833fa861bc187 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java @@ -20,25 +20,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; - -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.ChangeFeedObserver; -import com.microsoft.azure.cosmos.ChangeFeedObserverFactory; -import com.microsoft.azure.cosmos.ChangeFeedProcessor; -import com.microsoft.azure.cosmos.ChangeFeedProcessorOptions; -import com.microsoft.azure.cosmos.changefeed.Bootstrapper; -import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; -import com.microsoft.azure.cosmos.changefeed.HealthMonitor; -import com.microsoft.azure.cosmos.changefeed.LeaseStoreManager; -import com.microsoft.azure.cosmos.changefeed.PartitionController; -import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancer; -import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancingStrategy; -import com.microsoft.azure.cosmos.changefeed.PartitionManager; -import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; -import com.microsoft.azure.cosmos.changefeed.PartitionProcessorFactory; -import com.microsoft.azure.cosmos.changefeed.PartitionSupervisorFactory; -import com.microsoft.azure.cosmos.changefeed.RequestOptionsFactory; +package com.azure.data.cosmos.changefeed.internal; + +import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.ChangeFeedProcessor; +import com.azure.data.cosmos.ChangeFeedProcessorOptions; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.ChangeFeedObserverFactory; +import com.azure.data.cosmos.changefeed.Bootstrapper; +import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.changefeed.HealthMonitor; +import com.azure.data.cosmos.changefeed.LeaseStoreManager; +import com.azure.data.cosmos.changefeed.PartitionController; +import com.azure.data.cosmos.changefeed.PartitionLoadBalancer; +import com.azure.data.cosmos.changefeed.PartitionLoadBalancingStrategy; +import com.azure.data.cosmos.changefeed.PartitionManager; +import com.azure.data.cosmos.changefeed.PartitionProcessor; +import com.azure.data.cosmos.changefeed.PartitionProcessorFactory; +import com.azure.data.cosmos.changefeed.PartitionSupervisorFactory; +import com.azure.data.cosmos.changefeed.RequestOptionsFactory; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; @@ -143,7 +143,7 @@ public ChangeFeedProcessorBuilderImpl withProcessorOptions(ChangeFeedProcessorOp } this.changeFeedProcessorOptions = changeFeedProcessorOptions; - this.executorService = changeFeedProcessorOptions.getExecutorService(); + this.executorService = changeFeedProcessorOptions.executorService(); return this; } @@ -325,7 +325,7 @@ private Mono initializeCollectionPropertiesForBuild() { this.feedContextClient .readDatabase(this.feedContextClient.getDatabaseClient(), null) .map( databaseResourceResponse -> { - self.databaseResourceId = databaseResourceResponse.getDatabase().getId(); + self.databaseResourceId = databaseResourceResponse.database().id(); return self.databaseResourceId; }) .subscribeOn(Schedulers.elastic()) @@ -337,7 +337,7 @@ private Mono initializeCollectionPropertiesForBuild() { self.feedContextClient .readContainer(self.feedContextClient.getContainerClient(), null) .map(documentCollectionResourceResponse -> { - self.collectionResourceId = documentCollectionResourceResponse.getContainer().getId(); + self.collectionResourceId = documentCollectionResourceResponse.container().id(); return self.collectionResourceId; }) .subscribeOn(Schedulers.elastic()) @@ -356,10 +356,10 @@ private Mono getLeaseStoreManager() { return this.leaseContextClient.readContainerSettings(this.leaseContextClient.getContainerClient(), null) .map( collectionSettings -> { boolean isPartitioned = - collectionSettings.getPartitionKey() != null && - collectionSettings.getPartitionKey().getPaths() != null && - collectionSettings.getPartitionKey().getPaths().size() > 0; - if (!isPartitioned || (collectionSettings.getPartitionKey().getPaths().size() != 1 || !collectionSettings.getPartitionKey().getPaths().get(0).equals("/id"))) { + collectionSettings.partitionKey() != null && + collectionSettings.partitionKey().paths() != null && + collectionSettings.partitionKey().paths().size() > 0; + if (!isPartitioned || (collectionSettings.partitionKey().paths().size() != 1 || !collectionSettings.partitionKey().paths().get(0).equals("/id"))) { // throw new IllegalArgumentException("The lease collection, if partitioned, must have partition key equal to id."); Mono.error(new IllegalArgumentException("The lease collection must have partition key equal to id.")); } @@ -384,7 +384,7 @@ private Mono getLeaseStoreManager() { } private String getLeasePrefix() { - String optionsPrefix = this.changeFeedProcessorOptions.getLeasePrefix(); + String optionsPrefix = this.changeFeedProcessorOptions.leasePrefix(); if (optionsPrefix == null) { optionsPrefix = ""; @@ -403,15 +403,15 @@ private String getLeasePrefix() { private Mono buildPartitionManager(LeaseStoreManager leaseStoreManager) { ChangeFeedProcessorBuilderImpl self = this; - CheckpointerObserverFactory factory = new CheckpointerObserverFactory(this.observerFactory, this.changeFeedProcessorOptions.getCheckpointFrequency()); + CheckpointerObserverFactory factory = new CheckpointerObserverFactory(this.observerFactory, this.changeFeedProcessorOptions.checkpointFrequency()); PartitionSynchronizerImpl synchronizer = new PartitionSynchronizerImpl( this.feedContextClient, this.feedContextClient.getContainerClient(), leaseStoreManager, leaseStoreManager, - this.changeFeedProcessorOptions.getDegreeOfParallelism(), - this.changeFeedProcessorOptions.getQueryPartitionsMaxBatchSize() + this.changeFeedProcessorOptions.degreeOfParallelism(), + this.changeFeedProcessorOptions.queryPartitionsMaxBatchSize() ); Bootstrapper bootstrapper = new BootstrapperImpl(synchronizer, leaseStoreManager, this.lockTime, this.sleepTime); @@ -430,9 +430,9 @@ private Mono buildPartitionManager(LeaseStoreManager leaseStor if (this.loadBalancingStrategy == null) { this.loadBalancingStrategy = new EqualPartitionsBalancingStrategy( this.hostName, - this.changeFeedProcessorOptions.getMinPartitionCount(), - this.changeFeedProcessorOptions.getMaxPartitionCount(), - this.changeFeedProcessorOptions.getLeaseExpirationInterval()); + this.changeFeedProcessorOptions.minPartitionCount(), + this.changeFeedProcessorOptions.maxPartitionCount(), + this.changeFeedProcessorOptions.leaseExpirationInterval()); } PartitionController partitionController = new PartitionControllerImpl(leaseStoreManager, leaseStoreManager, partitionSupervisorFactory, synchronizer, executorService); @@ -447,7 +447,7 @@ private Mono buildPartitionManager(LeaseStoreManager leaseStor partitionController2, leaseStoreManager, this.loadBalancingStrategy, - this.changeFeedProcessorOptions.getLeaseAcquireInterval(), + this.changeFeedProcessorOptions.leaseAcquireInterval(), this.executorService ); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/CheckpointerObserverFactory.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/CheckpointerObserverFactory.java similarity index 91% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/CheckpointerObserverFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/CheckpointerObserverFactory.java index 8a4714caf8e31..2988cb9d47bf7 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/CheckpointerObserverFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/CheckpointerObserverFactory.java @@ -20,11 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.ChangeFeedObserver; -import com.microsoft.azure.cosmos.ChangeFeedObserverFactory; -import com.microsoft.azure.cosmos.changefeed.CheckpointFrequency; +import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.changefeed.CheckpointFrequency; +import com.azure.data.cosmos.ChangeFeedObserverFactory; /** * Factory class used to create instance(s) of {@link ChangeFeedObserver}. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/Constants.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/Constants.java similarity index 99% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/Constants.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/Constants.java index f8c9aff7192fe..3c9814a2d9827 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/Constants.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/Constants.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; /** @@ -173,7 +173,7 @@ public static final class Properties { public static final String TTL = "ttl"; public static final String DEFAULT_TTL = "defaultTtl"; - // Global DB account properties + // Global DB account item public static final String Name = "name"; public static final String WRITABLE_LOCATIONS = "writableLocations"; public static final String READABLE_LOCATIONS = "readableLocations"; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseStore.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseStore.java similarity index 67% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseStore.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseStore.java index ea74e8ba9f150..89da881d1c2d0 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseStore.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseStore.java @@ -20,27 +20,24 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; - -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; -import com.microsoft.azure.cosmos.changefeed.LeaseStore; -import com.microsoft.azure.cosmos.changefeed.RequestOptionsFactory; -import com.microsoft.azure.cosmos.changefeed.ServiceItemLease; -import com.microsoft.azure.cosmosdb.AccessCondition; -import com.microsoft.azure.cosmosdb.AccessConditionType; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; +package com.azure.data.cosmos.changefeed.internal; + +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.changefeed.LeaseStore; +import com.azure.data.cosmos.changefeed.RequestOptionsFactory; +import com.azure.data.cosmos.changefeed.ServiceItemLease; +import com.azure.data.cosmos.AccessCondition; +import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Document; import reactor.core.publisher.Mono; import java.time.Duration; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; - /** * Implementation for LeaseStore. */ @@ -68,19 +65,19 @@ public DocumentServiceLeaseStore( public Mono isInitialized() { String markerDocId = this.getStoreMarkerName(); - CosmosItemSettings doc = new CosmosItemSettings(); - doc.setId(markerDocId); + CosmosItemProperties doc = new CosmosItemProperties(); + doc.id(markerDocId); CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createRequestOptions( ServiceItemLease.fromDocument(doc)); CosmosItem docItem = this.client.getContainerClient().getItem(markerDocId, "/id"); return this.client.readItem(docItem, requestOptions) - .flatMap(documentResourceResponse -> Mono.just(documentResourceResponse.getItem() != null)) + .flatMap(documentResourceResponse -> Mono.just(documentResourceResponse.item() != null)) .onErrorResume(throwable -> { - if (throwable instanceof DocumentClientException) { - DocumentClientException e = (DocumentClientException) throwable; - if (e.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + if (throwable instanceof CosmosClientException) { + CosmosClientException e = (CosmosClientException) throwable; + if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND) { return Mono.just(false); } } @@ -92,15 +89,15 @@ public Mono isInitialized() { @Override public Mono markInitialized() { String markerDocId = this.getStoreMarkerName(); - CosmosItemSettings containerDocument = new CosmosItemSettings(); - containerDocument.setId(markerDocId); + CosmosItemProperties containerDocument = new CosmosItemProperties(); + containerDocument.id(markerDocId); return this.client.createItem(this.leaseCollectionLink, containerDocument, null, false) .map( item -> true) .onErrorResume(throwable -> { - if (throwable instanceof DocumentClientException) { - DocumentClientException e = (DocumentClientException) throwable; - if (e.getStatusCode() == HTTP_STATUS_CODE_CONFLICT) { + if (throwable instanceof CosmosClientException) { + CosmosClientException e = (CosmosClientException) throwable; + if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { return Mono.just(true); } } @@ -112,23 +109,23 @@ public Mono markInitialized() { public Mono acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); Document containerDocument = new Document(); - containerDocument.setId(lockId); + containerDocument.id(lockId); containerDocument.setTimeToLive(Long.valueOf(lockExpirationTime.getSeconds()).intValue()); DocumentServiceLeaseStore self = this; return this.client.createItem(this.leaseCollectionLink, containerDocument, null, false) .map(documentResourceResponse -> { - if (documentResourceResponse.getItem() != null) { - self.lockETag = documentResourceResponse.getCosmosItemSettings().getETag(); + if (documentResourceResponse.item() != null) { + self.lockETag = documentResourceResponse.properties().etag(); return true; } else { return false; } }) .onErrorResume(throwable -> { - if (throwable instanceof DocumentClientException) { - DocumentClientException e = (DocumentClientException) throwable; - if (e.getStatusCode() == HTTP_STATUS_CODE_CONFLICT) { + if (throwable instanceof CosmosClientException) { + CosmosClientException e = (CosmosClientException) throwable; + if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { return Mono.just(false); } } @@ -140,8 +137,8 @@ public Mono acquireInitializationLock(Duration lockExpirationTime) { @Override public Mono releaseInitializationLock() { String lockId = this.getStoreLockName(); - CosmosItemSettings doc = new CosmosItemSettings(); - doc.setId(lockId); + CosmosItemProperties doc = new CosmosItemProperties(); + doc.id(lockId); CosmosItemRequestOptions requestOptions = this.requestOptionsFactory.createRequestOptions( ServiceItemLease.fromDocument(doc)); @@ -151,15 +148,15 @@ public Mono releaseInitializationLock() { } AccessCondition accessCondition = new AccessCondition(); - accessCondition.setType(AccessConditionType.IfMatch); - accessCondition.setCondition(this.lockETag); + accessCondition.type(AccessConditionType.IF_MATCH); + accessCondition.condition(this.lockETag); requestOptions.accessCondition(accessCondition); DocumentServiceLeaseStore self = this; CosmosItem docItem = this.client.getContainerClient().getItem(lockId, "/id"); return this.client.deleteItem(docItem, requestOptions) .map(documentResourceResponse -> { - if (documentResourceResponse.getItem() != null) { + if (documentResourceResponse.item() != null) { self.lockETag = null; return true; } else { @@ -167,9 +164,9 @@ public Mono releaseInitializationLock() { } }) .onErrorResume(throwable -> { - if (throwable instanceof DocumentClientException) { - DocumentClientException e = (DocumentClientException) throwable; - if (e.getStatusCode() == HTTP_STATUS_CODE_CONFLICT) { + if (throwable instanceof CosmosClientException) { + CosmosClientException e = (CosmosClientException) throwable; + if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { return Mono.just(false); } } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java similarity index 70% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java index 9d0ca6d13a08d..9969ae4f50c8a 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java @@ -20,20 +20,20 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; - -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemResponse; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.ServiceItemLease; -import com.microsoft.azure.cosmos.changefeed.ServiceItemLeaseUpdater; -import com.microsoft.azure.cosmos.changefeed.exceptions.LeaseLostException; -import com.microsoft.azure.cosmosdb.AccessCondition; -import com.microsoft.azure.cosmosdb.AccessConditionType; -import com.microsoft.azure.cosmosdb.DocumentClientException; +package com.azure.data.cosmos.changefeed.internal; + +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.CosmosItemResponse; +import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.ServiceItemLease; +import com.azure.data.cosmos.changefeed.ServiceItemLeaseUpdater; +import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.AccessCondition; +import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.CosmosClientException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -42,9 +42,9 @@ import java.time.ZonedDateTime; import java.util.function.Function; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_PRECONDITION_FAILED; +import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT; +import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; +import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_PRECONDITION_FAILED; /** * Implementation for service lease updater interface. @@ -74,22 +74,22 @@ public Mono updateLease(Lease cachedLease, CosmosItem itemLink, CosmosIte } lease.setTimestamp(ZonedDateTime.now(ZoneId.of("UTC"))); - CosmosItemSettings leaseDocument = this.tryReplaceLease(lease, itemLink); + CosmosItemProperties leaseDocument = this.tryReplaceLease(lease, itemLink); if (leaseDocument != null) { return Mono.just(ServiceItemLease.fromDocument(leaseDocument)); } // Partition lease update conflict. Reading the current version of lease. - CosmosItemSettings document = null; + CosmosItemProperties document = null; try { CosmosItemResponse response = this.client.readItem(itemLink, requestOptions) .block(); - document = response.getCosmosItemSettings(); + document = response.properties(); } catch (RuntimeException re) { - if (re.getCause() instanceof DocumentClientException) { - DocumentClientException ex = (DocumentClientException) re.getCause(); - if (ex.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + if (re.getCause() instanceof CosmosClientException) { + CosmosClientException ex = (CosmosClientException) re.getCause(); + if (ex.statusCode() == HTTP_STATUS_CODE_NOT_FOUND) { // Partition lease no longer exists throw new LeaseLostException(lease); } @@ -112,15 +112,15 @@ public Mono updateLease(Lease cachedLease, CosmosItem itemLink, CosmosIte throw new LeaseLostException(lease); } - private CosmosItemSettings tryReplaceLease(Lease lease, CosmosItem itemLink) throws LeaseLostException { + private CosmosItemProperties tryReplaceLease(Lease lease, CosmosItem itemLink) throws LeaseLostException { try { CosmosItemResponse response = this.client.replaceItem(itemLink, lease, this.getCreateIfMatchOptions(lease)) .block(); - return response.getCosmosItemSettings(); + return response.properties(); } catch (RuntimeException re) { - if (re.getCause() instanceof DocumentClientException) { - DocumentClientException ex = (DocumentClientException) re.getCause(); - switch (ex.getStatusCode()) { + if (re.getCause() instanceof CosmosClientException) { + CosmosClientException ex = (CosmosClientException) re.getCause(); + switch (ex.statusCode()) { case HTTP_STATUS_CODE_PRECONDITION_FAILED: { return null; } @@ -141,8 +141,8 @@ private CosmosItemSettings tryReplaceLease(Lease lease, CosmosItem itemLink) thr private CosmosItemRequestOptions getCreateIfMatchOptions(Lease lease) { AccessCondition ifMatchCondition = new AccessCondition(); - ifMatchCondition.setType(AccessConditionType.IfMatch); - ifMatchCondition.setCondition(lease.getConcurrencyToken()); + ifMatchCondition.type(AccessConditionType.IF_MATCH); + ifMatchCondition.condition(lease.getConcurrencyToken()); CosmosItemRequestOptions createIfMatchOptions = new CosmosItemRequestOptions(); createIfMatchOptions.accessCondition(ifMatchCondition); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java similarity index 97% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java index c8875801b066e..3b671beaf867b 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancingStrategy; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.PartitionLoadBalancingStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ExceptionClassifier.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ExceptionClassifier.java similarity index 64% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ExceptionClassifier.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ExceptionClassifier.java index 7b6119aef93bb..950d74b6cb238 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ExceptionClassifier.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ExceptionClassifier.java @@ -20,14 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmosdb.DocumentClientException; - -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_GONE; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_TOO_MANY_REQUESTS; +import com.azure.data.cosmos.CosmosClientException; /** * Classifies exceptions based on the status codes. @@ -45,16 +40,16 @@ public class ExceptionClassifier { public static final int SubStatusCode_ReadSessionNotAvailable = 1002; - public static StatusCodeErrorType classifyClientException(DocumentClientException clientException) { - Integer subStatusCode = clientException.getSubStatusCode(); + public static StatusCodeErrorType classifyClientException(CosmosClientException clientException) { + Integer subStatusCode = clientException.subStatusCode(); - if (clientException.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND && subStatusCode != SubStatusCode_ReadSessionNotAvailable) + if (clientException.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND && subStatusCode != SubStatusCode_ReadSessionNotAvailable) return StatusCodeErrorType.PARTITION_NOT_FOUND; - if (clientException.getStatusCode() == HTTP_STATUS_CODE_GONE && (subStatusCode == SubStatusCode_PartitionKeyRangeGone || subStatusCode == SubStatusCode_Splitting)) + if (clientException.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_GONE && (subStatusCode == SubStatusCode_PartitionKeyRangeGone || subStatusCode == SubStatusCode_Splitting)) return StatusCodeErrorType.PARTITION_SPLIT; - if (clientException.getStatusCode() == HTTP_STATUS_CODE_TOO_MANY_REQUESTS || clientException.getStatusCode() >= HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR) + if (clientException.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_TOO_MANY_REQUESTS || clientException.statusCode() >= ChangeFeedHelper.HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR) return StatusCodeErrorType.TRANSIENT_ERROR; // Temporary workaround to compare exception message, until server provides better way of handling this case. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java similarity index 85% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java index 9247c11859f9f..ddd96dca5806a 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.changefeed.HealthMonitor; -import com.microsoft.azure.cosmos.changefeed.HealthMonitoringRecord; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.PartitionController; -import com.microsoft.azure.cosmosdb.DocumentClientException; +import com.azure.data.cosmos.changefeed.HealthMonitor; +import com.azure.data.cosmos.changefeed.HealthMonitoringRecord; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.PartitionController; +import com.azure.data.cosmos.CosmosClientException; import reactor.core.publisher.Mono; /** @@ -48,7 +48,7 @@ public HealthMonitoringPartitionControllerDecorator(PartitionController inner, H public Mono addOrUpdateLease(Lease lease) { return this.inner.addOrUpdateLease(lease) .onErrorResume(throwable -> { - if (throwable instanceof DocumentClientException) { + if (throwable instanceof CosmosClientException) { // do nothing. } else { monitor.inspect(new HealthMonitoringRecord( diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseRenewerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseRenewerImpl.java similarity index 92% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseRenewerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseRenewerImpl.java index dda2c7378899f..a6b7ef61ca05d 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseRenewerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseRenewerImpl.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.changefeed.CancellationToken; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.LeaseManager; -import com.microsoft.azure.cosmos.changefeed.LeaseRenewer; -import com.microsoft.azure.cosmos.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.changefeed.CancellationToken; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.LeaseManager; +import com.azure.data.cosmos.changefeed.LeaseRenewer; +import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseStoreManagerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseStoreManagerImpl.java similarity index 84% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseStoreManagerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseStoreManagerImpl.java index 8672304b8565b..fc73b6c6f2b79 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/LeaseStoreManagerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseStoreManagerImpl.java @@ -20,25 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; - -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.LeaseStore; -import com.microsoft.azure.cosmos.changefeed.LeaseStoreManager; -import com.microsoft.azure.cosmos.changefeed.LeaseStoreManagerSettings; -import com.microsoft.azure.cosmos.changefeed.RequestOptionsFactory; -import com.microsoft.azure.cosmos.changefeed.ServiceItemLease; -import com.microsoft.azure.cosmos.changefeed.ServiceItemLeaseUpdater; -import com.microsoft.azure.cosmos.changefeed.exceptions.LeaseLostException; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.SqlParameter; -import com.microsoft.azure.cosmosdb.SqlParameterCollection; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; +package com.azure.data.cosmos.changefeed.internal; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.LeaseStore; +import com.azure.data.cosmos.changefeed.LeaseStoreManager; +import com.azure.data.cosmos.changefeed.LeaseStoreManagerSettings; +import com.azure.data.cosmos.changefeed.RequestOptionsFactory; +import com.azure.data.cosmos.changefeed.ServiceItemLease; +import com.azure.data.cosmos.changefeed.ServiceItemLeaseUpdater; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; @@ -46,9 +39,6 @@ import java.time.Duration; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT; -import static com.microsoft.azure.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; - /** * Provides flexible way to build lease manager constructor parameters. * For the actual creation of lease manager instance, delegates to lease manager factory. @@ -173,9 +163,9 @@ public Mono createLeaseIfNotExist(String leaseToken, String continuationT return this.leaseDocumentClient.createItem(this.settings.getLeaseCollectionLink(), documentServiceLease, null, false) .onErrorResume( ex -> { - if (ex instanceof DocumentClientException) { - DocumentClientException e = (DocumentClientException) ex; - if (e.getStatusCode() == HTTP_STATUS_CODE_CONFLICT) { + if (ex instanceof CosmosClientException) { + CosmosClientException e = (CosmosClientException) ex; + if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { //Logger.InfoFormat("Some other host created lease for {0}.", leaseToken); return Mono.empty(); } @@ -187,10 +177,10 @@ public Mono createLeaseIfNotExist(String leaseToken, String continuationT .map(documentResourceResponse -> { if (documentResourceResponse == null) return null; - CosmosItemSettings document = documentResourceResponse.getCosmosItemSettings(); + CosmosItemProperties document = documentResourceResponse.properties(); return documentServiceLease - .withId(document.getId()) - .withEtag(document.getETag()) + .withId(document.id()) + .withEtag(document.etag()) .withTs(document.getString(Constants.Properties.LAST_MODIFIED)); }); //Logger.InfoFormat("Created lease for partition {0}.", leaseToken); @@ -205,9 +195,9 @@ public Mono delete(Lease lease) { return this.leaseDocumentClient .deleteItem(itemForLease, this.requestOptionsFactory.createRequestOptions(lease)) .onErrorResume( ex -> { - if (ex instanceof DocumentClientException) { - DocumentClientException e = (DocumentClientException) ex; - if (e.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + if (ex instanceof CosmosClientException) { + CosmosClientException e = (CosmosClientException) ex; + if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND) { // Ignore - document was already deleted. return Mono.empty(); } @@ -252,9 +242,9 @@ public Mono release(Lease lease) { return this.leaseDocumentClient.readItem(itemForLease, this.requestOptionsFactory.createRequestOptions(lease)) .onErrorResume( ex -> { - if (ex instanceof DocumentClientException) { - DocumentClientException e = (DocumentClientException) ex; - if (e.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + if (ex instanceof CosmosClientException) { + CosmosClientException e = (CosmosClientException) ex; + if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND) { // Logger.InfoFormat("Partition {0} failed to renew lease. The lease is gone already.", lease.LeaseToken); Mono.error(new LeaseLostException(lease)); } @@ -263,7 +253,7 @@ public Mono release(Lease lease) { Mono.error(ex); return Mono.empty(); }) - .map( documentResourceResponse -> ServiceItemLease.fromDocument(documentResourceResponse.getCosmosItemSettings())) + .map( documentResourceResponse -> ServiceItemLease.fromDocument(documentResourceResponse.properties())) .flatMap( refreshedLease -> self.leaseUpdater.updateLease( refreshedLease, self.createItemForLease(refreshedLease.getId()), @@ -293,9 +283,9 @@ public Mono renew(Lease lease) { return this.leaseDocumentClient.readItem(itemForLease, this.requestOptionsFactory.createRequestOptions(lease)) .onErrorResume( ex -> { - if (ex instanceof DocumentClientException) { - DocumentClientException e = (DocumentClientException) ex; - if (e.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + if (ex instanceof CosmosClientException) { + CosmosClientException e = (CosmosClientException) ex; + if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND) { // Logger.InfoFormat("Partition {0} failed to renew lease. The lease is gone already.", lease.LeaseToken); Mono.error(new LeaseLostException(lease)); } @@ -304,7 +294,7 @@ public Mono renew(Lease lease) { Mono.error(ex); return Mono.empty(); }) - .map( documentResourceResponse -> ServiceItemLease.fromDocument(documentResourceResponse.getCosmosItemSettings())) + .map( documentResourceResponse -> ServiceItemLease.fromDocument(documentResourceResponse.properties())) .flatMap( refreshedLease -> self.leaseUpdater.updateLease( refreshedLease, self.createItemForLease(refreshedLease.getId()), @@ -327,7 +317,7 @@ public Mono updateProperties(Lease lease) { if (!lease.getOwner().equalsIgnoreCase(this.settings.getHostName())) { - // Logger.InfoFormat("Partition '{0}' lease was taken over by owner '{1}' before lease properties update", lease.LeaseToken, lease.Owner); + // Logger.InfoFormat("Partition '{0}' lease was taken over by owner '{1}' before lease item update", lease.LeaseToken, lease.Owner); Mono.error(new LeaseLostException(lease)); } @@ -393,9 +383,9 @@ private Mono tryGetLease(Lease lease) { return this.leaseDocumentClient.readItem(itemForLease, this.requestOptionsFactory.createRequestOptions(lease)) .onErrorResume( ex -> { - if (ex instanceof DocumentClientException) { - DocumentClientException e = (DocumentClientException) ex; - if (e.getStatusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + if (ex instanceof CosmosClientException) { + CosmosClientException e = (CosmosClientException) ex; + if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND) { return Mono.empty(); } } @@ -405,7 +395,7 @@ private Mono tryGetLease(Lease lease) { }) .map( documentResourceResponse -> { if (documentResourceResponse == null) return null; - return ServiceItemLease.fromDocument(documentResourceResponse.getCosmosItemSettings()); + return ServiceItemLease.fromDocument(documentResourceResponse.properties()); }); } @@ -415,18 +405,18 @@ private Flux listDocuments(String prefix) { } SqlParameter param = new SqlParameter(); - param.setName("@PartitionLeasePrefix"); - param.setValue(prefix); + param.name("@PartitionLeasePrefix"); + param.value(prefix); SqlQuerySpec querySpec = new SqlQuerySpec( "SELECT * FROM c WHERE STARTSWITH(c.id, @PartitionLeasePrefix)", new SqlParameterCollection(param)); - Flux> query = this.leaseDocumentClient.queryItems( + Flux> query = this.leaseDocumentClient.queryItems( this.settings.getLeaseCollectionLink(), querySpec, this.requestOptionsFactory.createFeedOptions()); - return query.flatMap( documentFeedResponse -> Flux.fromIterable(documentFeedResponse.getResults())) + return query.flatMap( documentFeedResponse -> Flux.fromIterable(documentFeedResponse.results())) .map( ServiceItemLease::fromDocument); } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java similarity index 86% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java index e31e9d32a8bc2..76f36ef92ccf2 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java @@ -20,14 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.ChangeFeedObserver; -import com.microsoft.azure.cosmos.ChangeFeedObserverCloseReason; -import com.microsoft.azure.cosmos.ChangeFeedObserverContext; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.changefeed.exceptions.ObserverException; +import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.ChangeFeedObserverCloseReason; +import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.changefeed.exceptions.ObserverException; import java.util.List; @@ -69,7 +68,7 @@ public void close(ChangeFeedObserverContext context, ChangeFeedObserverCloseReas } @Override - public void processChanges(ChangeFeedObserverContext context, List docs) { + public void processChanges(ChangeFeedObserverContext context, List docs) { try { this.changeFeedObserver.processChanges(context, docs); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionCheckpointerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionCheckpointerImpl.java similarity index 90% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionCheckpointerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionCheckpointerImpl.java index bda13fdfaeba8..9b9f576799854 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionCheckpointerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionCheckpointerImpl.java @@ -20,11 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.LeaseCheckpointer; -import com.microsoft.azure.cosmos.changefeed.PartitionCheckpointer; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.LeaseCheckpointer; +import com.azure.data.cosmos.changefeed.PartitionCheckpointer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionControllerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionControllerImpl.java similarity index 88% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionControllerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionControllerImpl.java index ac6d9d56ddea8..450c89cecba95 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionControllerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionControllerImpl.java @@ -20,19 +20,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; - -import com.microsoft.azure.cosmos.changefeed.CancellationToken; -import com.microsoft.azure.cosmos.changefeed.CancellationTokenSource; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.LeaseContainer; -import com.microsoft.azure.cosmos.changefeed.LeaseManager; -import com.microsoft.azure.cosmos.changefeed.PartitionController; -import com.microsoft.azure.cosmos.changefeed.PartitionSupervisor; -import com.microsoft.azure.cosmos.changefeed.PartitionSupervisorFactory; -import com.microsoft.azure.cosmos.changefeed.PartitionSynchronizer; -import com.microsoft.azure.cosmos.changefeed.exceptions.PartitionSplitException; -import com.microsoft.azure.cosmos.changefeed.exceptions.TaskCancelledException; +package com.azure.data.cosmos.changefeed.internal; + +import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; +import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; +import com.azure.data.cosmos.changefeed.CancellationToken; +import com.azure.data.cosmos.changefeed.CancellationTokenSource; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.LeaseContainer; +import com.azure.data.cosmos.changefeed.LeaseManager; +import com.azure.data.cosmos.changefeed.PartitionController; +import com.azure.data.cosmos.changefeed.PartitionSupervisor; +import com.azure.data.cosmos.changefeed.PartitionSupervisorFactory; +import com.azure.data.cosmos.changefeed.PartitionSynchronizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -46,7 +46,7 @@ */ public class PartitionControllerImpl implements PartitionController { private final Logger logger = LoggerFactory.getLogger(PartitionControllerImpl.class); - // private final Map currentlyOwnedPartitions = new ConcurrentHashMap(); + // private final Map currentlyOwnedPartitions = new ConcurrentHashMap(); private final Map currentlyOwnedPartitions = new ConcurrentHashMap<>(); private final LeaseContainer leaseContainer; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java similarity index 91% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java index f8ec5febcd2bd..fdab39a5cd084 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java @@ -20,15 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; - -import com.microsoft.azure.cosmos.changefeed.CancellationToken; -import com.microsoft.azure.cosmos.changefeed.CancellationTokenSource; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.LeaseContainer; -import com.microsoft.azure.cosmos.changefeed.PartitionController; -import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancer; -import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancingStrategy; +package com.azure.data.cosmos.changefeed.internal; + +import com.azure.data.cosmos.changefeed.CancellationToken; +import com.azure.data.cosmos.changefeed.CancellationTokenSource; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.LeaseContainer; +import com.azure.data.cosmos.changefeed.PartitionController; +import com.azure.data.cosmos.changefeed.PartitionLoadBalancer; +import com.azure.data.cosmos.changefeed.PartitionLoadBalancingStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionManagerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionManagerImpl.java similarity index 87% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionManagerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionManagerImpl.java index 933b7d745aab1..f383ccfbb1b5f 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionManagerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionManagerImpl.java @@ -20,12 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.changefeed.Bootstrapper; -import com.microsoft.azure.cosmos.changefeed.PartitionController; -import com.microsoft.azure.cosmos.changefeed.PartitionLoadBalancer; -import com.microsoft.azure.cosmos.changefeed.PartitionManager; +import com.azure.data.cosmos.changefeed.Bootstrapper; +import com.azure.data.cosmos.changefeed.PartitionController; +import com.azure.data.cosmos.changefeed.PartitionLoadBalancer; +import com.azure.data.cosmos.changefeed.PartitionManager; import reactor.core.publisher.Mono; /** diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java similarity index 76% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java index 29199374604e0..7371bd77730c2 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java @@ -20,18 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.ChangeFeedObserver; -import com.microsoft.azure.cosmos.ChangeFeedProcessorOptions; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.LeaseCheckpointer; -import com.microsoft.azure.cosmos.changefeed.PartitionCheckpointer; -import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; -import com.microsoft.azure.cosmos.changefeed.PartitionProcessorFactory; -import com.microsoft.azure.cosmos.changefeed.ProcessorSettings; +import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.ChangeFeedProcessorOptions; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.LeaseCheckpointer; +import com.azure.data.cosmos.changefeed.PartitionCheckpointer; +import com.azure.data.cosmos.changefeed.PartitionProcessor; +import com.azure.data.cosmos.changefeed.PartitionProcessorFactory; +import com.azure.data.cosmos.changefeed.ProcessorSettings; /** * Implementation for {@link PartitionProcessorFactory}. @@ -67,17 +67,17 @@ public PartitionProcessor create(Lease lease, ChangeFeedObserver observer) { String startContinuation = lease.getContinuationToken(); if (startContinuation == null || startContinuation.isEmpty()) { - startContinuation = this.changeFeedProcessorOptions.getStartContinuation(); + startContinuation = this.changeFeedProcessorOptions.startContinuation(); } ProcessorSettings settings = new ProcessorSettings() .withCollectionLink(this.collectionSelfLink) .withStartContinuation(startContinuation) .withPartitionKeyRangeId(lease.getLeaseToken()) - .withFeedPollDelay(this.changeFeedProcessorOptions.getFeedPollDelay()) - .withMaxItemCount(this.changeFeedProcessorOptions.getMaxItemCount()) - .withStartFromBeginning(this.changeFeedProcessorOptions.isStartFromBeginning()) - .withStartTime(this.changeFeedProcessorOptions.getStartTime()); // .withSessionToken(this.changeFeedProcessorOptions.getSessionToken()); + .withFeedPollDelay(this.changeFeedProcessorOptions.feedPollDelay()) + .withMaxItemCount(this.changeFeedProcessorOptions.maxItemCount()) + .withStartFromBeginning(this.changeFeedProcessorOptions.startFromBeginning()) + .withStartTime(this.changeFeedProcessorOptions.startTime()); // .sessionToken(this.changeFeedProcessorOptions.sessionToken()); PartitionCheckpointer checkpointer = new PartitionCheckpointerImpl(this.leaseCheckpointer, lease); return new PartitionProcessorImpl(observer, this.documentClient, settings, checkpointer); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorImpl.java similarity index 66% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorImpl.java index f9db2d7dfd507..a52501c7a762f 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionProcessorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorImpl.java @@ -20,23 +20,22 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; - -import com.microsoft.azure.cosmos.ChangeFeedObserver; -import com.microsoft.azure.cosmos.ChangeFeedObserverContext; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.changefeed.CancellationToken; -import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; -import com.microsoft.azure.cosmos.changefeed.PartitionCheckpointer; -import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; -import com.microsoft.azure.cosmos.changefeed.ProcessorSettings; -import com.microsoft.azure.cosmos.changefeed.exceptions.PartitionNotFoundException; -import com.microsoft.azure.cosmos.changefeed.exceptions.PartitionSplitException; -import com.microsoft.azure.cosmos.changefeed.exceptions.TaskCancelledException; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedResponse; +package com.azure.data.cosmos.changefeed.internal; + +import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.changefeed.exceptions.PartitionNotFoundException; +import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; +import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; +import com.azure.data.cosmos.changefeed.CancellationToken; +import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.changefeed.PartitionCheckpointer; +import com.azure.data.cosmos.changefeed.PartitionProcessor; +import com.azure.data.cosmos.changefeed.ProcessorSettings; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Mono; import java.time.Duration; @@ -64,12 +63,12 @@ public PartitionProcessorImpl(ChangeFeedObserver observer, ChangeFeedContextClie this.checkpointer = checkpointer; this.options = new ChangeFeedOptions(); - this.options.setMaxItemCount(settings.getMaxItemCount()); - this.options.setPartitionKeyRangeId(settings.getPartitionKeyRangeId()); - // this.options.setSessionToken(settings.getSessionToken()); - this.options.setStartFromBeginning(settings.isStartFromBeginning()); - this.options.setRequestContinuation(settings.getStartContinuation()); - this.options.setStartDateTime(settings.getStartTime()); + this.options.maxItemCount(settings.getMaxItemCount()); + this.options.partitionKeyRangeId(settings.getPartitionKeyRangeId()); + // this.options.sessionToken(settings.sessionToken()); + this.options.startFromBeginning(settings.isStartFromBeginning()); + this.options.requestContinuation(settings.getStartContinuation()); + this.options.startDateTime(settings.getStartTime()); //this.query = documentClient.createDocumentChangeFeedQuery(self.settings.getCollectionSelfLink(), this.options); } @@ -84,18 +83,18 @@ public Mono run(CancellationToken cancellationToken) { Duration delay = self.settings.getFeedPollDelay(); try { - self.options.setRequestContinuation(self.lastContinuation); - List> documentFeedResponseList = self.documentClient.createDocumentChangeFeedQuery(self.settings.getCollectionSelfLink(), self.options) + self.options.requestContinuation(self.lastContinuation); + List> documentFeedResponseList = self.documentClient.createDocumentChangeFeedQuery(self.settings.getCollectionSelfLink(), self.options) .collectList() .block(); - for (FeedResponse documentFeedResponse : documentFeedResponseList) { - self.lastContinuation = documentFeedResponse.getResponseContinuation(); - if (documentFeedResponse.getResults() != null && documentFeedResponse.getResults().size() > 0) { + for (FeedResponse documentFeedResponse : documentFeedResponseList) { + self.lastContinuation = documentFeedResponse.continuationToken(); + if (documentFeedResponse.results() != null && documentFeedResponse.results().size() > 0) { self.dispatchChanges(documentFeedResponse); } - self.options.setRequestContinuation(self.lastContinuation); + self.options.requestContinuation(self.lastContinuation); if (cancellationToken.isCancellationRequested()) { // Observation was cancelled. @@ -103,13 +102,13 @@ public Mono run(CancellationToken cancellationToken) { } } - if (this.options.getMaxItemCount().compareTo(this.settings.getMaxItemCount()) == 0) { - this.options.setMaxItemCount(this.settings.getMaxItemCount()); // Reset after successful execution. + if (this.options.maxItemCount().compareTo(this.settings.getMaxItemCount()) == 0) { + this.options.maxItemCount(this.settings.getMaxItemCount()); // Reset after successful execution. } } catch (RuntimeException ex) { - if (ex.getCause() instanceof DocumentClientException) { + if (ex.getCause() instanceof CosmosClientException) { - DocumentClientException clientException = (DocumentClientException) ex.getCause(); + CosmosClientException clientException = (CosmosClientException) ex.getCause(); // this.logger.WarnException("exception: partition '{0}'", clientException, this.settings.PartitionKeyRangeId); StatusCodeErrorType docDbError = ExceptionClassifier.classifyClientException(clientException); @@ -124,14 +123,14 @@ public Mono run(CancellationToken cancellationToken) { self.resultException = ex; } case MAX_ITEM_COUNT_TOO_LARGE: { - if (this.options.getMaxItemCount() == null) { - this.options.setMaxItemCount(DefaultMaxItemCount); - } else if (this.options.getMaxItemCount() <= 1) { + if (this.options.maxItemCount() == null) { + this.options.maxItemCount(DefaultMaxItemCount); + } else if (this.options.maxItemCount() <= 1) { // this.logger.ErrorFormat("Cannot reduce maxItemCount further as it's already at {0}.", this.options.MaxItemCount); throw ex; } - this.options.setMaxItemCount(this.options.getMaxItemCount() / 2); + this.options.maxItemCount(this.options.maxItemCount() / 2); // this.logger.WarnFormat("Reducing maxItemCount, new value: {0}.", this.options.MaxItemCount); break; } @@ -166,9 +165,9 @@ public RuntimeException getResultException() { return this.resultException; } - private void dispatchChanges(FeedResponse response) { + private void dispatchChanges(FeedResponse response) { ChangeFeedObserverContext context = new ChangeFeedObserverContextImpl(this.settings.getPartitionKeyRangeId(), response, this.checkpointer); - this.observer.processChanges(context, response.getResults()); + this.observer.processChanges(context, response.results()); } } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java similarity index 80% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java index 282a0dbe0ca12..cfb51eb77b664 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java @@ -20,18 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.ChangeFeedObserver; -import com.microsoft.azure.cosmos.ChangeFeedObserverFactory; -import com.microsoft.azure.cosmos.ChangeFeedProcessorOptions; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.LeaseManager; -import com.microsoft.azure.cosmos.changefeed.LeaseRenewer; -import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; -import com.microsoft.azure.cosmos.changefeed.PartitionProcessorFactory; -import com.microsoft.azure.cosmos.changefeed.PartitionSupervisor; -import com.microsoft.azure.cosmos.changefeed.PartitionSupervisorFactory; +import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.ChangeFeedProcessorOptions; +import com.azure.data.cosmos.ChangeFeedObserverFactory; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.LeaseManager; +import com.azure.data.cosmos.changefeed.LeaseRenewer; +import com.azure.data.cosmos.changefeed.PartitionProcessor; +import com.azure.data.cosmos.changefeed.PartitionProcessorFactory; +import com.azure.data.cosmos.changefeed.PartitionSupervisor; +import com.azure.data.cosmos.changefeed.PartitionSupervisorFactory; import java.util.concurrent.ExecutorService; @@ -70,7 +70,7 @@ public PartitionSupervisor create(Lease lease) { ChangeFeedObserver changeFeedObserver = this.observerFactory.createObserver(); PartitionProcessor processor = this.partitionProcessorFactory.create(lease, changeFeedObserver); - LeaseRenewer renewer = new LeaseRenewerImpl(lease, this.leaseManager, this.changeFeedProcessorOptions.getLeaseRenewInterval()); + LeaseRenewer renewer = new LeaseRenewerImpl(lease, this.leaseManager, this.changeFeedProcessorOptions.leaseRenewInterval()); return new PartitionSupervisorImpl(lease, changeFeedObserver, processor, renewer, this.executorService); } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java similarity index 86% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java index 3ba263e148e40..7b2fce321e25e 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSupervisorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java @@ -20,21 +20,21 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; - -import com.microsoft.azure.cosmos.ChangeFeedObserver; -import com.microsoft.azure.cosmos.ChangeFeedObserverCloseReason; -import com.microsoft.azure.cosmos.ChangeFeedObserverContext; -import com.microsoft.azure.cosmos.changefeed.CancellationToken; -import com.microsoft.azure.cosmos.changefeed.CancellationTokenSource; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.LeaseRenewer; -import com.microsoft.azure.cosmos.changefeed.PartitionProcessor; -import com.microsoft.azure.cosmos.changefeed.PartitionSupervisor; -import com.microsoft.azure.cosmos.changefeed.exceptions.LeaseLostException; -import com.microsoft.azure.cosmos.changefeed.exceptions.ObserverException; -import com.microsoft.azure.cosmos.changefeed.exceptions.PartitionSplitException; -import com.microsoft.azure.cosmos.changefeed.exceptions.TaskCancelledException; +package com.azure.data.cosmos.changefeed.internal; + +import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.ChangeFeedObserverCloseReason; +import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.changefeed.exceptions.ObserverException; +import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; +import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; +import com.azure.data.cosmos.changefeed.CancellationToken; +import com.azure.data.cosmos.changefeed.CancellationTokenSource; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.LeaseRenewer; +import com.azure.data.cosmos.changefeed.PartitionProcessor; +import com.azure.data.cosmos.changefeed.PartitionSupervisor; import reactor.core.publisher.Mono; import java.io.Closeable; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSynchronizerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSynchronizerImpl.java similarity index 89% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSynchronizerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSynchronizerImpl.java index 5577c6253d4d5..9606a536d5a86 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionSynchronizerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSynchronizerImpl.java @@ -20,16 +20,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.LeaseContainer; -import com.microsoft.azure.cosmos.changefeed.LeaseManager; -import com.microsoft.azure.cosmos.changefeed.PartitionSynchronizer; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.LeaseContainer; +import com.azure.data.cosmos.changefeed.LeaseManager; +import com.azure.data.cosmos.changefeed.PartitionSynchronizer; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.PartitionKeyRange; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; @@ -73,7 +73,7 @@ public Mono createMissingLeases() { return this.enumPartitionKeyRanges() .map(partitionKeyRange -> { // TODO: log the partition key ID found. - return partitionKeyRange.getId(); + return partitionKeyRange.id(); }) .collectList() .flatMap( partitionKeyRangeIds -> { @@ -99,7 +99,7 @@ public Flux splitPartition(Lease lease) { // After a split, the children are either all or none available return this.enumPartitionKeyRanges() .filter(range -> range != null && range.getParents() != null && range.getParents().contains(leaseToken)) - .map(PartitionKeyRange::getId) + .map(PartitionKeyRange::id) .collectList() .flatMapMany(addedLeaseTokens -> { if (addedLeaseTokens.size() == 0) { @@ -119,14 +119,14 @@ public Flux splitPartition(Lease lease) { } private Flux enumPartitionKeyRanges() { - // String partitionKeyRangesPath = String.format("%spkranges", this.collectionSelfLink); + // STRING partitionKeyRangesPath = STRING.format("%spkranges", this.collectionSelfLink); String partitionKeyRangesPath = CosmosContainer.getSelfLink(this.collectionSelfLink); FeedOptions feedOptions = new FeedOptions(); - feedOptions.setMaxItemCount(this.maxBatchSize); - feedOptions.setRequestContinuation(null); + feedOptions.maxItemCount(this.maxBatchSize); + feedOptions.requestContinuation(null); return this.documentClient.readPartitionKeyRangeFeed(partitionKeyRangesPath, feedOptions) - .map(partitionKeyRangeFeedResponse -> partitionKeyRangeFeedResponse.getResults()) + .map(partitionKeyRangeFeedResponse -> partitionKeyRangeFeedResponse.results()) .flatMap(partitionKeyRangeList -> Flux.fromIterable(partitionKeyRangeList)) .onErrorResume(throwable -> { // TODO: Log the exception. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java similarity index 76% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java index 4fd7e7601259f..042ce44cd912f 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java @@ -20,14 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.changefeed.Lease; -import com.microsoft.azure.cosmos.changefeed.RequestOptionsFactory; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.RequestOptions; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.RequestOptionsFactory; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.PartitionKey; /** * Used to create request options for partitioned lease collections, when partition key is defined as /id. @@ -36,7 +35,7 @@ public class PartitionedByIdCollectionRequestOptionsFactory implements RequestOp @Override public CosmosItemRequestOptions createRequestOptions(Lease lease) { CosmosItemRequestOptions requestOptions = new CosmosItemRequestOptions(); - requestOptions.setPartitionKey(new PartitionKey(lease.getId())); + requestOptions.partitionKey(new PartitionKey(lease.getId())); return requestOptions; } @@ -44,7 +43,7 @@ public CosmosItemRequestOptions createRequestOptions(Lease lease) { @Override public FeedOptions createFeedOptions() { FeedOptions feedOptions = new FeedOptions(); - feedOptions.setEnableCrossPartitionQuery(true); + feedOptions.enableCrossPartitionQuery(true); return feedOptions; } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java similarity index 94% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java index b39a546ea0ba6..bd1e375a14460 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.changefeed.RemainingPartitionWork; +import com.azure.data.cosmos.changefeed.RemainingPartitionWork; /** * Implements the {@link RemainingPartitionWork} interface. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java similarity index 90% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java index 119d535af2f6b..9394e73170bd9 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java @@ -20,12 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.changefeed.ChangeFeedContextClient; -import com.microsoft.azure.cosmos.changefeed.LeaseContainer; -import com.microsoft.azure.cosmos.changefeed.RemainingPartitionWork; -import com.microsoft.azure.cosmos.changefeed.RemainingWorkEstimator; +import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.changefeed.LeaseContainer; +import com.azure.data.cosmos.changefeed.RemainingPartitionWork; +import com.azure.data.cosmos.changefeed.RemainingWorkEstimator; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/StatusCodeErrorType.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/StatusCodeErrorType.java similarity index 96% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/StatusCodeErrorType.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/StatusCodeErrorType.java index c4cbec2c1d793..618bb53e32791 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/StatusCodeErrorType.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/StatusCodeErrorType.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; /** * Groups types of status code errors returned while processing the change feeds. diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/TraceHealthMonitor.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/TraceHealthMonitor.java similarity index 90% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/TraceHealthMonitor.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/TraceHealthMonitor.java index 0b71a28d42bdd..0af1a33f50255 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/TraceHealthMonitor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/TraceHealthMonitor.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; -import com.microsoft.azure.cosmos.changefeed.HealthMonitor; -import com.microsoft.azure.cosmos.changefeed.HealthMonitoringRecord; +import com.azure.data.cosmos.changefeed.HealthMonitor; +import com.azure.data.cosmos.changefeed.HealthMonitoringRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/WorkerTask.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/WorkerTask.java similarity index 96% rename from sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/WorkerTask.java rename to sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/WorkerTask.java index 5ceb41c7b7763..ca74075c88f74 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmos/changefeed/internal/WorkerTask.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/WorkerTask.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos.changefeed.internal; +package com.azure.data.cosmos.changefeed.internal; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ChangeFeedQueryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java similarity index 70% rename from sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ChangeFeedQueryImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java index 4b988cd84bc78..82e954abeb21e 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/ChangeFeedQueryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java @@ -20,23 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import java.util.HashMap; import java.util.Map; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.Paths; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.rx.internal.query.Paginator; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.query.Paginator; import rx.Observable; import rx.Single; @@ -65,12 +60,12 @@ public ChangeFeedQueryImpl(RxDocumentClientImpl client, changeFeedOptions = changeFeedOptions != null ? changeFeedOptions: new ChangeFeedOptions(); - if (resourceType.isPartitioned() && changeFeedOptions.getPartitionKeyRangeId() == null && changeFeedOptions.getPartitionKey() == null) { + if (resourceType.isPartitioned() && changeFeedOptions.partitionKeyRangeId() == null && changeFeedOptions.partitionKey() == null) { throw new IllegalArgumentException(RMResources.PartitionKeyRangeIdOrPartitionKeyMustBeSpecified); } - if (changeFeedOptions.getPartitionKey() != null && - !Strings.isNullOrEmpty(changeFeedOptions.getPartitionKeyRangeId())) { + if (changeFeedOptions.partitionKey() != null && + !Strings.isNullOrEmpty(changeFeedOptions.partitionKeyRangeId())) { throw new IllegalArgumentException(String.format( RMResources.PartitionKeyAndParitionKeyRangeIdBothSpecified @@ -80,16 +75,16 @@ public ChangeFeedQueryImpl(RxDocumentClientImpl client, String initialNextIfNoneMatch = null; boolean canUseStartFromBeginning = true; - if (changeFeedOptions.getRequestContinuation() != null) { - initialNextIfNoneMatch = changeFeedOptions.getRequestContinuation(); + if (changeFeedOptions.requestContinuation() != null) { + initialNextIfNoneMatch = changeFeedOptions.requestContinuation(); canUseStartFromBeginning = false; } - if(changeFeedOptions.getStartDateTime() != null){ + if(changeFeedOptions.startDateTime() != null){ canUseStartFromBeginning = false; } - if (canUseStartFromBeginning && !changeFeedOptions.isStartFromBeginning()) { + if (canUseStartFromBeginning && !changeFeedOptions.startFromBeginning()) { initialNextIfNoneMatch = IfNonMatchAllHeaderValue; } @@ -99,24 +94,24 @@ public ChangeFeedQueryImpl(RxDocumentClientImpl client, private RxDocumentServiceRequest createDocumentServiceRequest(String continuationToken, int pageSize) { Map headers = new HashMap<>(); - if (options.getMaxItemCount() != null) { - headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, String.valueOf(options.getMaxItemCount())); + if (options.maxItemCount() != null) { + headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, String.valueOf(options.maxItemCount())); } - // On REST level, change feed is using IfNoneMatch/ETag instead of continuation. + // On REST level, change feed is using IF_NONE_MATCH/ETag instead of continuation. if(continuationToken != null) { headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, continuationToken); } headers.put(HttpConstants.HttpHeaders.A_IM, HttpConstants.A_IMHeaderValues.INCREMENTAL_FEED); - if (options.getPartitionKey() != null) { - PartitionKeyInternal partitionKey = options.getPartitionKey().getInternalPartitionKey(); + if (options.partitionKey() != null) { + PartitionKeyInternal partitionKey = options.partitionKey().getInternalPartitionKey(); headers.put(HttpConstants.HttpHeaders.PARTITION_KEY, partitionKey.toJson()); } - if(options.getStartDateTime() != null){ - String dateTimeInHttpFormat = Utils.zonedDateTimeAsUTCRFC1123(options.getStartDateTime()); + if(options.startDateTime() != null){ + String dateTimeInHttpFormat = Utils.zonedDateTimeAsUTCRFC1123(options.startDateTime()); headers.put(HttpConstants.HttpHeaders.IF_MODIFIED_SINCE, dateTimeInHttpFormat); } @@ -127,8 +122,8 @@ private RxDocumentServiceRequest createDocumentServiceRequest(String continuatio headers, options); - if (options.getPartitionKeyRangeId() != null) { - req.routeTo(new PartitionKeyRangeIdentity(this.options.getPartitionKeyRangeId())); + if (options.partitionKeyRangeId() != null) { + req.routeTo(new PartitionKeyRangeIdentity(this.options.partitionKeyRangeId())); } return req; @@ -136,7 +131,7 @@ private RxDocumentServiceRequest createDocumentServiceRequest(String continuatio private ChangeFeedOptions getChangeFeedOptions(ChangeFeedOptions options, String continuationToken) { ChangeFeedOptions newOps = new ChangeFeedOptions(options); - newOps.setRequestContinuation(continuationToken); + newOps.requestContinuation(continuationToken); return newOps; } @@ -147,7 +142,7 @@ public Observable> executeAsync() { // TODO: clean up if we want to use single vs observable. Func1>> executeFunc = request -> this.executeRequestAsync(request).toObservable(); - return Paginator.getPaginatedChangeFeedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, options.getMaxItemCount() != null ? options.getMaxItemCount(): -1); + return Paginator.getPaginatedChangeFeedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, options.maxItemCount() != null ? options.maxItemCount(): -1); } private Single> executeRequestAsync(RxDocumentServiceRequest request) { diff --git a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java similarity index 84% rename from sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java index e79e27b859c4a..69b517b17eba0 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java @@ -20,79 +20,59 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.directconnectivity.GlobalAddressResolver; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.microsoft.azure.cosmosdb.AccessConditionType; -import com.microsoft.azure.cosmosdb.Attachment; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.Conflict; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.CosmosResourceType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseAccount; -import com.microsoft.azure.cosmosdb.DatabaseAccountManagerInternal; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedOptionsBase; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.JsonSerializable; -import com.microsoft.azure.cosmosdb.MediaOptions; -import com.microsoft.azure.cosmosdb.MediaReadMode; -import com.microsoft.azure.cosmosdb.MediaResponse; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.StoredProcedureResponse; -import com.microsoft.azure.cosmosdb.TokenResolver; -import com.microsoft.azure.cosmosdb.Trigger; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; -import com.microsoft.azure.cosmosdb.internal.BaseAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.internal.Constants; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.LifeCycleUtils; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.PathInfo; -import com.microsoft.azure.cosmosdb.internal.PathParser; -import com.microsoft.azure.cosmosdb.internal.Paths; -import com.microsoft.azure.cosmosdb.internal.PathsHelper; -import com.microsoft.azure.cosmosdb.internal.QueryCompatibilityMode; -import com.microsoft.azure.cosmosdb.internal.ResourceTokenAuthorizationHelper; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.RuntimeConstants; -import com.microsoft.azure.cosmosdb.internal.SessionContainer; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.GatewayServiceConfigurationReader; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.ServerStoreModel; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreClient; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreClientFactory; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyAndResourceTokenPair; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxClientCollectionCache; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxCollectionCache; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxPartitionKeyRangeCache; -import com.microsoft.azure.cosmosdb.rx.internal.directconnectivity.GlobalAddressResolver; -import com.microsoft.azure.cosmosdb.rx.internal.query.DocumentQueryExecutionContextFactory; -import com.microsoft.azure.cosmosdb.rx.internal.query.IDocumentQueryClient; -import com.microsoft.azure.cosmosdb.rx.internal.query.IDocumentQueryExecutionContext; -import com.microsoft.azure.cosmosdb.rx.internal.query.Paginator; +import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.Conflict; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosResourceType; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DatabaseAccount; +import com.azure.data.cosmos.DatabaseAccountManagerInternal; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedOptionsBase; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.JsonSerializable; +import com.azure.data.cosmos.MediaOptions; +import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.StoredProcedure; +import com.azure.data.cosmos.StoredProcedureResponse; +import com.azure.data.cosmos.TokenResolver; +import com.azure.data.cosmos.Trigger; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.UserDefinedFunction; +import com.azure.data.cosmos.directconnectivity.GatewayServiceConfigurationReader; +import com.azure.data.cosmos.directconnectivity.ServerStoreModel; +import com.azure.data.cosmos.directconnectivity.StoreClient; +import com.azure.data.cosmos.directconnectivity.StoreClientFactory; +import com.azure.data.cosmos.internal.routing.PartitionKeyAndResourceTokenPair; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.internal.query.DocumentQueryExecutionContextFactory; +import com.azure.data.cosmos.internal.query.IDocumentQueryClient; +import com.azure.data.cosmos.internal.query.IDocumentQueryExecutionContext; +import com.azure.data.cosmos.internal.query.Paginator; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import io.reactivex.netty.protocol.http.client.CompositeHttpClientBuilder; @@ -105,7 +85,6 @@ import rx.functions.Func2; import java.io.IOException; -import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; @@ -117,12 +96,12 @@ import java.util.Map; import java.util.UUID; -import static com.microsoft.azure.cosmosdb.BridgeInternal.documentFromObject; -import static com.microsoft.azure.cosmosdb.BridgeInternal.getAltLink; -import static com.microsoft.azure.cosmosdb.BridgeInternal.toDatabaseAccount; -import static com.microsoft.azure.cosmosdb.BridgeInternal.toFeedResponsePage; -import static com.microsoft.azure.cosmosdb.BridgeInternal.toResourceResponse; -import static com.microsoft.azure.cosmosdb.BridgeInternal.toStoredProcedureResponse; +import static com.azure.data.cosmos.BridgeInternal.documentFromObject; +import static com.azure.data.cosmos.BridgeInternal.getAltLink; +import static com.azure.data.cosmos.BridgeInternal.toDatabaseAccount; +import static com.azure.data.cosmos.BridgeInternal.toFeedResponsePage; +import static com.azure.data.cosmos.BridgeInternal.toResourceResponse; +import static com.azure.data.cosmos.BridgeInternal.toStoredProcedureResponse; /** * While this class is public, but it is not part of our published public APIs. @@ -266,7 +245,7 @@ public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken this.userAgentContainer = new UserAgentContainer(); - String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); + String userAgentSuffix = this.connectionPolicy.userAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } @@ -296,7 +275,7 @@ private void initializeGatewayConfigurationReader() { this.rxClient); DatabaseAccount databaseAccount = this.gatewayConfigurationReader.initializeReaderAsync().toBlocking().value(); - this.useMultipleWriteLocations = this.connectionPolicy.isUsingMultipleWriteLocations() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); + this.useMultipleWriteLocations = this.connectionPolicy.usingMultipleWriteLocations() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); // TODO: add support for openAsync // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/332589 @@ -322,7 +301,7 @@ public void init() { this.partitionKeyRangeCache = new RxPartitionKeyRangeCache(RxDocumentClientImpl.this, collectionCache); - if (this.connectionPolicy.getConnectionMode() == ConnectionMode.Gateway) { + if (this.connectionPolicy.connectionMode() == ConnectionMode.GATEWAY) { this.storeModel = this.gatewayProxy; } else { this.initializeDirectConnectivity(); @@ -333,7 +312,7 @@ private void initializeDirectConnectivity() { this.storeClientFactory = new StoreClientFactory( this.configs, - this.connectionPolicy.getRequestTimeoutInMillis() / 1000, + this.connectionPolicy.requestTimeoutInMillis() / 1000, // this.maxConcurrentConnectionOpenRequests, 0, this.userAgentContainer @@ -347,7 +326,7 @@ private void initializeDirectConnectivity() { this.collectionCache, this.partitionKeyRangeCache, userAgentContainer, - // TODO: Gateway Configuration Reader + // TODO: GATEWAY Configuration Reader // this.gatewayConfigurationReader, null, this.connectionPolicy); @@ -393,10 +372,10 @@ RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, private CompositeHttpClientBuilder httpClientBuilder() { HttpClientFactory factory = new HttpClientFactory(this.configs) - .withMaxIdleConnectionTimeoutInMillis(this.connectionPolicy.getIdleConnectionTimeoutInMillis()) - .withPoolSize(this.connectionPolicy.getMaxPoolSize()) - .withHttpProxy(this.connectionPolicy.getProxy()) - .withRequestTimeoutInMillis(this.connectionPolicy.getRequestTimeoutInMillis()); + .withMaxIdleConnectionTimeoutInMillis(this.connectionPolicy.idleConnectionTimeoutInMillis()) + .withPoolSize(this.connectionPolicy.maxPoolSize()) + .withHttpProxy(this.connectionPolicy.proxy()) + .withRequestTimeoutInMillis(this.connectionPolicy.requestTimeoutInMillis()); return factory.toHttpClientBuilder(); } @@ -463,7 +442,7 @@ private Observable> createDatabaseInternal(Database d throw new IllegalArgumentException("Database"); } - logger.debug("Creating a Database. id: [{}]", database.getId()); + logger.debug("Creating a Database. id: [{}]", database.id()); validateResource(database); Map requestHeaders = this.getRequestHeaders(options); @@ -628,7 +607,7 @@ private Observable> createCollectionInterna } logger.debug("Creating a Collection. databaseLink: [{}], Collection id: [{}]", databaseLink, - collection.getId()); + collection.id()); validateResource(collection); String path = Utils.joinPath(databaseLink, Paths.COLLECTIONS_PATH_SEGMENT); @@ -643,7 +622,7 @@ private Observable> createCollectionInterna return this.create(request).map(response -> toResourceResponse(response, DocumentCollection.class)) .doOnNext(resourceResponse -> { // set the session token - this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), + this.sessionContainer.setSessionToken(resourceResponse.getResource().resourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); }); @@ -667,10 +646,10 @@ private Observable> replaceCollectionIntern throw new IllegalArgumentException("collection"); } - logger.debug("Replacing a Collection. id: [{}]", collection.getId()); + logger.debug("Replacing a Collection. id: [{}]", collection.id()); validateResource(collection); - String path = Utils.joinPath(collection.getSelfLink(), null); + String path = Utils.joinPath(collection.selfLink(), null); Map requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, @@ -686,7 +665,7 @@ private Observable> replaceCollectionIntern .doOnNext(resourceResponse -> { if (resourceResponse.getResource() != null) { // set the session token - this.sessionContainer.setSessionToken(resourceResponse.getResource().getResourceId(), + this.sessionContainer.setSessionToken(resourceResponse.getResource().resourceId(), getAltLink(resourceResponse.getResource()), resourceResponse.getResponseHeaders()); } @@ -823,7 +802,7 @@ private static String serializeProcedureParams(Object[] objectArray) { stringArray[i] = ((JsonSerializable) object).toJson(); } else { - // POJO, ObjectNode, number, String or Boolean + // POJO, ObjectNode, number, STRING or Boolean try { stringArray[i] = mapper.writeValueAsString(object); } catch (IOException e) { @@ -836,13 +815,13 @@ private static String serializeProcedureParams(Object[] objectArray) { } private static void validateResource(Resource resource) { - if (!StringUtils.isEmpty(resource.getId())) { - if (resource.getId().indexOf('/') != -1 || resource.getId().indexOf('\\') != -1 || - resource.getId().indexOf('?') != -1 || resource.getId().indexOf('#') != -1) { + if (!StringUtils.isEmpty(resource.id())) { + if (resource.id().indexOf('/') != -1 || resource.id().indexOf('\\') != -1 || + resource.id().indexOf('?') != -1 || resource.id().indexOf('#') != -1) { throw new IllegalArgumentException("Id contains illegal chars."); } - if (resource.getId().endsWith(" ")) { + if (resource.id().endsWith(" ")) { throw new IllegalArgumentException("Id ends with a space."); } } @@ -869,10 +848,10 @@ private Map getRequestHeaders(RequestOptions options) { } if (options.getAccessCondition() != null) { - if (options.getAccessCondition().getType() == AccessConditionType.IfMatch) { - headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getAccessCondition().getCondition()); + if (options.getAccessCondition().type() == AccessConditionType.IF_MATCH) { + headers.put(HttpConstants.HttpHeaders.IF_MATCH, options.getAccessCondition().condition()); } else { - headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getAccessCondition().getCondition()); + headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, options.getAccessCondition().condition()); } } @@ -972,7 +951,7 @@ private void addPartitionKeyInformation(RxDocumentServiceRequest request, Docume partitionKeyInternal = BridgeInternal.getNonePartitionKey(partitionKeyDefinition); } else if (options != null && options.getPartitionKey() != null) { partitionKeyInternal = options.getPartitionKey().getInternalPartitionKey(); - } else if (partitionKeyDefinition == null || partitionKeyDefinition.getPaths().size() == 0) { + } else if (partitionKeyDefinition == null || partitionKeyDefinition.paths().size() == 0) { // For backward compatibility, if collection doesn't have partition key defined, we assume all documents // have empty value for it and user doesn't need to specify it explicitly. partitionKeyInternal = PartitionKeyInternal.getEmpty(); @@ -1002,7 +981,7 @@ private static PartitionKeyInternal extractPartitionKeyValueFromDocument( Document document, PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition != null) { - String path = partitionKeyDefinition.getPaths().iterator().next(); + String path = partitionKeyDefinition.paths().iterator().next(); List parts = PathParser.getPathParts(path); if (parts.size() >= 1) { Object value = document.getObjectByPath(parts); @@ -1035,10 +1014,10 @@ private Single getCreateDocumentRequest(String documen RxDocumentClientImpl.validateResource(typedDocument); - if (typedDocument.getId() == null && !disableAutomaticIdGeneration) { + if (typedDocument.id() == null && !disableAutomaticIdGeneration) { // We are supposed to use GUID. Basically UUID is the same as GUID // when represented as a string. - typedDocument.setId(UUID.randomUUID().toString()); + typedDocument.id(UUID.randomUUID().toString()); } String path = Utils.joinPath(documentCollectionLink, Paths.DOCUMENTS_PATH_SEGMENT); Map requestHeaders = this.getRequestHeaders(options); @@ -1264,7 +1243,7 @@ private Observable> replaceDocumentInternal(String do public Observable> replaceDocument(Document document, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { - String collectionLink = document.getSelfLink(); + String collectionLink = document.selfLink(); requestRetryPolicy = new PartitionKeyMismatchRetryPolicy(collectionCache, requestRetryPolicy, collectionLink, options); } IDocumentClientRetryPolicy finalRequestRetryPolicy = requestRetryPolicy; @@ -1278,7 +1257,7 @@ private Observable> replaceDocumentInternal(Document throw new IllegalArgumentException("document"); } - return this.replaceDocumentInternal(document.getSelfLink(), document, options, retryPolicyInstance); + return this.replaceDocumentInternal(document.selfLink(), document, options, retryPolicyInstance); } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); @@ -1535,7 +1514,7 @@ private Observable> createStoredProcedureInter try { logger.debug("Creating a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", - collectionLink, storedProcedure.getId()); + collectionLink, storedProcedure.id()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Create); if (retryPolicyInstance != null) { @@ -1567,7 +1546,7 @@ private Observable> upsertStoredProcedureInter try { logger.debug("Upserting a StoredProcedure. collectionLink: [{}], storedProcedure id [{}]", - collectionLink, storedProcedure.getId()); + collectionLink, storedProcedure.id()); RxDocumentServiceRequest request = getStoredProcedureRequest(collectionLink, storedProcedure, options, OperationType.Upsert); if (retryPolicyInstance != null) { @@ -1597,11 +1576,11 @@ private Observable> replaceStoredProcedureInte if (storedProcedure == null) { throw new IllegalArgumentException("storedProcedure"); } - logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.getId()); + logger.debug("Replacing a StoredProcedure. storedProcedure id [{}]", storedProcedure.id()); RxDocumentClientImpl.validateResource(storedProcedure); - String path = Utils.joinPath(storedProcedure.getSelfLink(), null); + String path = Utils.joinPath(storedProcedure.selfLink(), null); Map requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.StoredProcedure, path, storedProcedure, requestHeaders, options); @@ -1771,7 +1750,7 @@ private Observable> createTriggerInternal(String colle try { logger.debug("Creating a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, - trigger.getId()); + trigger.id()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Create); if (retryPolicyInstance != null){ @@ -1798,7 +1777,7 @@ private Observable> upsertTriggerInternal(String colle try { logger.debug("Upserting a Trigger. collectionLink [{}], trigger id [{}]", collectionLink, - trigger.getId()); + trigger.id()); RxDocumentServiceRequest request = getTriggerRequest(collectionLink, trigger, options, OperationType.Upsert); if (retryPolicyInstance != null){ @@ -1846,10 +1825,10 @@ private Observable> replaceTriggerInternal(Trigger tri throw new IllegalArgumentException("trigger"); } - logger.debug("Replacing a Trigger. trigger id [{}]", trigger.getId()); + logger.debug("Replacing a Trigger. trigger id [{}]", trigger.id()); RxDocumentClientImpl.validateResource(trigger); - String path = Utils.joinPath(trigger.getSelfLink(), null); + String path = Utils.joinPath(trigger.selfLink(), null); Map requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.Trigger, path, trigger, requestHeaders, options); @@ -1965,7 +1944,7 @@ private Observable> createUserDefinedFunct // session) try { logger.debug("Creating a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, - udf.getId()); + udf.id()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Create); if (retryPolicyInstance != null){ @@ -1996,7 +1975,7 @@ private Observable> upsertUserDefinedFunct // session) try { logger.debug("Upserting a UserDefinedFunction. collectionLink [{}], udf id [{}]", collectionLink, - udf.getId()); + udf.id()); RxDocumentServiceRequest request = getUserDefinedFunctionRequest(collectionLink, udf, options, OperationType.Upsert); if (retryPolicyInstance != null){ @@ -2030,10 +2009,10 @@ private Observable> replaceUserDefinedFunc throw new IllegalArgumentException("udf"); } - logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.getId()); + logger.debug("Replacing a UserDefinedFunction. udf id [{}]", udf.id()); validateResource(udf); - String path = Utils.joinPath(udf.getSelfLink(), null); + String path = Utils.joinPath(udf.selfLink(), null); Map requestHeaders = this.getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.UserDefinedFunction, path, udf, requestHeaders, options); @@ -2149,334 +2128,6 @@ public Observable> queryUserDefinedFunctions(S return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } - - @Override - public Observable> createAttachment(String documentLink, Attachment attachment, - RequestOptions options) { - IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); - return ObservableHelper.inlineIfPossibleAsObs(() -> createAttachmentInternal(documentLink, attachment, options, retryPolicyInstance), retryPolicyInstance); - } - - private Observable> createAttachmentInternal(String documentLink, Attachment attachment, - RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { - - try { - logger.debug("Creating a Attachment. documentLink [{}], attachment id [{}]", documentLink, - attachment.getId()); - Observable reqObs = getAttachmentRequest(documentLink, attachment, options, - OperationType.Create).toObservable(); - return reqObs.flatMap(req -> { - if (retryPolicyInstance != null) { - retryPolicyInstance.onBeforeSendRequest(req); - } - - return create(req).map(response -> toResourceResponse(response, Attachment.class)); - }); - - } catch (Exception e) { - logger.debug("Failure in creating a Attachment due to [{}]", e.getMessage(), e); - return Observable.error(e); - } - } - - - @Override - public Observable> upsertAttachment(String documentLink, Attachment attachment, - RequestOptions options) { - IDocumentClientRetryPolicy retryPolicyInstance = this.retryPolicy.getRequestPolicy(); - return ObservableHelper.inlineIfPossibleAsObs(() -> upsertAttachmentInternal(documentLink, attachment, options, retryPolicyInstance), retryPolicyInstance); - } - - private Observable> upsertAttachmentInternal(String documentLink, Attachment attachment, - RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { - - try { - logger.debug("Upserting a Attachment. documentLink [{}], attachment id [{}]", documentLink, - attachment.getId()); - Observable reqObs = getAttachmentRequest(documentLink, attachment, options, - OperationType.Upsert).toObservable(); - return reqObs.flatMap(req -> { - if (retryPolicyInstance != null) { - retryPolicyInstance.onBeforeSendRequest(req); - } - - return upsert(req).map(response -> toResourceResponse(response, Attachment.class)); - }); - - } catch (Exception e) { - logger.debug("Failure in upserting a Attachment due to [{}]", e.getMessage(), e); - return Observable.error(e); - } - } - - @Override - public Observable> replaceAttachment(Attachment attachment, RequestOptions options) { - IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); - return ObservableHelper.inlineIfPossibleAsObs(() -> replaceAttachmentInternal(attachment, options, retryPolicyInstance), retryPolicyInstance); - } - - private Observable> replaceAttachmentInternal(Attachment attachment, RequestOptions options, - IDocumentClientRetryPolicy retryPolicyInstance) { - try { - if (attachment == null) { - throw new IllegalArgumentException("attachment"); - } - - logger.debug("Replacing a Attachment. attachment id [{}]", attachment.getId()); - RxDocumentClientImpl.validateResource(attachment); - - String path = Utils.joinPath(attachment.getSelfLink(), null); - Map requestHeaders = getRequestHeaders(options); - RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, - ResourceType.Attachment, path, attachment, requestHeaders, options); - - Observable reqObs = addPartitionKeyInformation(request, null, options).toObservable(); - return reqObs.flatMap(req -> { - if (retryPolicyInstance != null) { - retryPolicyInstance.onBeforeSendRequest(request); - } - - return replace(request).map(response -> toResourceResponse(response, Attachment.class)); - }); - } catch (Exception e) { - logger.debug("Failure in replacing a Attachment due to [{}]", e.getMessage(), e); - return Observable.error(e); - } - } - - @Override - public Observable> deleteAttachment(String attachmentLink, RequestOptions options) { - IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); - return ObservableHelper.inlineIfPossibleAsObs(() -> deleteAttachmentInternal(attachmentLink, options, retryPolicyInstance), retryPolicyInstance); - } - - private Observable> deleteAttachmentInternal(String attachmentLink, RequestOptions options, - IDocumentClientRetryPolicy retryPolicyInstance) { - - try { - if (StringUtils.isEmpty(attachmentLink)) { - throw new IllegalArgumentException("attachmentLink"); - } - - logger.debug("Deleting a Attachment. attachmentLink [{}]", attachmentLink); - String path = Utils.joinPath(attachmentLink, null); - Map requestHeaders = getRequestHeaders(options); - RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, - ResourceType.Attachment, path, requestHeaders, options); - - Observable reqObs = addPartitionKeyInformation(request, null, options).toObservable(); - return reqObs.flatMap(req -> { - if (retryPolicyInstance != null) { - retryPolicyInstance.onBeforeSendRequest(req); - } - - return delete(req).map(resp -> toResourceResponse(resp, Attachment.class)); - }); - - } catch (Exception e) { - logger.debug("Failure in deleting a Attachment due to [{}]", e.getMessage(), e); - return Observable.error(e); - } - } - - @Override - public Observable> readAttachment(String attachmentLink, RequestOptions options) { - IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); - return ObservableHelper.inlineIfPossibleAsObs(() -> readAttachmentInternal(attachmentLink, options, retryPolicyInstance), retryPolicyInstance); - } - - private Observable> readAttachmentInternal(String attachmentLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { - - try { - if (StringUtils.isEmpty(attachmentLink)) { - throw new IllegalArgumentException("attachmentLink"); - } - - logger.debug("Reading a Attachment. attachmentLink [{}]", attachmentLink); - String path = Utils.joinPath(attachmentLink, null); - Map requestHeaders = getRequestHeaders(options); - RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, - ResourceType.Attachment, path, requestHeaders, options); - - Observable reqObs = addPartitionKeyInformation(request, null, options).toObservable(); - - return reqObs.flatMap(req -> { - - if (retryPolicyInstance != null) { - retryPolicyInstance.onBeforeSendRequest(request); - } - - return read(request).map(response -> toResourceResponse(response, Attachment.class)); - }); - - } catch (Exception e) { - logger.debug("Failure in reading a Attachment due to [{}]", e.getMessage(), e); - return Observable.error(e); - } - } - - @Override - public Observable> readAttachments(String documentLink, FeedOptions options) { - - if (StringUtils.isEmpty(documentLink)) { - throw new IllegalArgumentException("documentLink"); - } - - return readFeedCollectionChild(options, ResourceType.Attachment, Attachment.class, - Utils.joinPath(documentLink, Paths.ATTACHMENTS_PATH_SEGMENT)); - } - - @Override - public Observable readMedia(String mediaLink) { - if (StringUtils.isEmpty(mediaLink)) { - throw new IllegalArgumentException("mediaLink"); - } - - String targetPath = Utils.joinPath(mediaLink, null); - return ObservableHelper.inlineIfPossibleAsObs(() -> readMediaInternal(targetPath), this.resetSessionTokenRetryPolicy.getRequestPolicy()); - } - - private Observable readMediaInternal(String mediaLink) { - logger.debug("Reading a Media. mediaLink [{}]", mediaLink); - RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Media, mediaLink, (Map) null, null); - request.setIsMedia(true); - // Media is strong consistent always -> no need of session handling - populateHeaders(request, HttpConstants.HttpMethods.GET); - return gatewayProxy.processMessage(request).map(response -> - BridgeInternal.toMediaResponse(response, this.connectionPolicy.getMediaReadMode() == MediaReadMode.Buffered)); - } - - @Override - public Observable updateMedia(String mediaLink, InputStream mediaStream, MediaOptions options) { - if (StringUtils.isEmpty(mediaLink)) { - throw new IllegalArgumentException("mediaLink"); - } - if (mediaStream == null) { - throw new IllegalArgumentException("mediaStream"); - } - - String targetPath = Utils.joinPath(mediaLink, null); - return ObservableHelper.inlineIfPossibleAsObs(() -> updateMediaInternal(targetPath, mediaStream, options), this.resetSessionTokenRetryPolicy.getRequestPolicy()); - } - - private Observable updateMediaInternal(String mediaLink, InputStream mediaStream, MediaOptions options) { - logger.debug("Updating a Media. mediaLink [{}]", mediaLink); - Map requestHeaders = this.getMediaHeaders(options); - RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.Media, - mediaLink, - mediaStream, - requestHeaders); - request.setIsMedia(true); - - // Media is strong consistent always -> need of session handling - populateHeaders(request, HttpConstants.HttpMethods.PUT); - return gatewayProxy.processMessage(request).map(response -> - BridgeInternal.toMediaResponse(response, this.connectionPolicy.getMediaReadMode() == MediaReadMode.Buffered)); - } - - @Override - public Observable> queryAttachments(String documentLink, String query, - FeedOptions options) { - return queryAttachments(documentLink, new SqlQuerySpec(query), options); - } - - @Override - public Observable> queryAttachments(String documentLink, SqlQuerySpec querySpec, - FeedOptions options) { - return createQuery(documentLink, querySpec, options, Attachment.class, ResourceType.Attachment); - } - - private Single getAttachmentRequest(String documentLink, Attachment attachment, - RequestOptions options, OperationType operationType) { - if (StringUtils.isEmpty(documentLink)) { - throw new IllegalArgumentException("documentLink"); - } - if (attachment == null) { - throw new IllegalArgumentException("attachment"); - } - - RxDocumentClientImpl.validateResource(attachment); - - String path = Utils.joinPath(documentLink, Paths.ATTACHMENTS_PATH_SEGMENT); - Map requestHeaders = getRequestHeaders(options); - RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, ResourceType.Attachment, path, - attachment, requestHeaders, options); - - return addPartitionKeyInformation(request, null, options); - } - - @Override - public Observable> createAttachment(String documentLink, InputStream mediaStream, - MediaOptions options, RequestOptions requestOptions) { - IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); - return ObservableHelper.inlineIfPossibleAsObs(() -> createAttachmentInternal(documentLink, mediaStream, options, requestOptions, retryPolicyInstance), retryPolicyInstance); - } - - private Observable> createAttachmentInternal(String documentLink, InputStream mediaStream, - MediaOptions options, RequestOptions requestOptions, IDocumentClientRetryPolicy retryPolicyInstance) { - - try { - logger.debug("Creating a Attachment. attachmentLink [{}]", documentLink); - Observable reqObs = getAttachmentRequest(documentLink, mediaStream, options, - requestOptions, OperationType.Create).toObservable(); - return reqObs.flatMap(req -> { - if (retryPolicyInstance != null) { - retryPolicyInstance.onBeforeSendRequest(req); - } - - return create(req).map(response -> toResourceResponse(response, Attachment.class)); - }); - - } catch (Exception e) { - logger.debug("Failure in creating a Attachment due to [{}]", e.getMessage(), e); - return Observable.error(e); - } - } - - @Override - public Observable> upsertAttachment(String documentLink, InputStream mediaStream, - MediaOptions options, RequestOptions requestOptions) { - IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); - return ObservableHelper.inlineIfPossibleAsObs(() -> upsertAttachmentInternal(documentLink, mediaStream, options, requestOptions, retryPolicyInstance), retryPolicyInstance); - } - - private Observable> upsertAttachmentInternal(String documentLink, InputStream mediaStream, - MediaOptions options, RequestOptions requestOptions, IDocumentClientRetryPolicy retryPolicyInstance) { - - try { - logger.debug("Upserting a Attachment. attachmentLink [{}]", documentLink); - Observable reqObs = getAttachmentRequest(documentLink, mediaStream, options, - requestOptions, OperationType.Upsert).toObservable(); - return reqObs.flatMap(req -> { - if (retryPolicyInstance != null) { - retryPolicyInstance.onBeforeSendRequest(req); - } - - return upsert(req).map(response -> toResourceResponse(response, Attachment.class)); - }); - - } catch (Exception e) { - logger.debug("Failure in upserting a Attachment due to [{}]", e.getMessage(), e); - return Observable.error(e); - } - } - - private Single getAttachmentRequest(String documentLink, InputStream mediaStream, - MediaOptions options, RequestOptions requestOptions, OperationType operationType) { - if (StringUtils.isEmpty(documentLink)) { - throw new IllegalArgumentException("documentLink"); - } - if (mediaStream == null) { - throw new IllegalArgumentException("mediaStream"); - } - String path = Utils.joinPath(documentLink, Paths.ATTACHMENTS_PATH_SEGMENT); - Map requestHeaders = this.getMediaHeaders(options); - RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, ResourceType.Attachment, path, - mediaStream, requestHeaders); - request.setIsMedia(true); - return addPartitionKeyInformation(request, null, requestOptions); - } - @Override public Observable> readConflict(String conflictLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); @@ -2576,7 +2227,7 @@ public Observable> createUser(String databaseLink, User u private Observable> createUserInternal(String databaseLink, User user, RequestOptions options) { try { - logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); + logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.id()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); return this.create(request).map(response -> toResourceResponse(response, User.class)); @@ -2595,7 +2246,7 @@ public Observable> upsertUser(String databaseLink, User u private Observable> upsertUserInternal(String databaseLink, User user, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { - logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.getId()); + logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.id()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Upsert); if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); @@ -2639,10 +2290,10 @@ private Observable> replaceUserInternal(User user, Reques if (user == null) { throw new IllegalArgumentException("user"); } - logger.debug("Replacing a User. user id [{}]", user.getId()); + logger.debug("Replacing a User. user id [{}]", user.id()); RxDocumentClientImpl.validateResource(user); - String path = Utils.joinPath(user.getSelfLink(), null); + String path = Utils.joinPath(user.selfLink(), null); Map requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.User, path, user, requestHeaders, options); @@ -2748,7 +2399,7 @@ private Observable> createPermissionInternal(String RequestOptions options) { try { - logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); + logger.debug("Creating a Permission. userLink [{}], permission id [{}]", userLink, permission.id()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Create); return this.create(request).map(response -> toResourceResponse(response, Permission.class)); @@ -2770,7 +2421,7 @@ private Observable> upsertPermissionInternal(String RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { - logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.getId()); + logger.debug("Upserting a Permission. userLink [{}], permission id [{}]", userLink, permission.id()); RxDocumentServiceRequest request = getPermissionRequest(userLink, permission, options, OperationType.Upsert); if (retryPolicyInstance != null) { @@ -2815,10 +2466,10 @@ private Observable> replacePermissionInternal(Permi if (permission == null) { throw new IllegalArgumentException("permission"); } - logger.debug("Replacing a Permission. permission id [{}]", permission.getId()); + logger.debug("Replacing a Permission. permission id [{}]", permission.id()); RxDocumentClientImpl.validateResource(permission); - String path = Utils.joinPath(permission.getSelfLink(), null); + String path = Utils.joinPath(permission.selfLink(), null); Map requestHeaders = getRequestHeaders(options); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.Permission, path, permission, requestHeaders, options); @@ -2927,10 +2578,10 @@ private Observable> replaceOfferInternal(Offer offer) { if (offer == null) { throw new IllegalArgumentException("offer"); } - logger.debug("Replacing an Offer. offer id [{}]", offer.getId()); + logger.debug("Replacing an Offer. offer id [{}]", offer.id()); RxDocumentClientImpl.validateResource(offer); - String path = Utils.joinPath(offer.getSelfLink(), null); + String path = Utils.joinPath(offer.selfLink(), null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Replace, ResourceType.Offer, path, offer, null, null); return this.replace(request).map(response -> toResourceResponse(response, Offer.class)); @@ -2981,11 +2632,11 @@ private Observable> readFeedCollectionChild options = new FeedOptions(); } - int maxPageSize = options.getMaxItemCount() != null ? options.getMaxItemCount() : -1; + int maxPageSize = options.maxItemCount() != null ? options.maxItemCount() : -1; final FeedOptions finalFeedOptions = options; RequestOptions requestOptions = new RequestOptions(); - requestOptions.setPartitionKey(options.getPartitionKey()); + requestOptions.setPartitionKey(options.partitionKey()); Func2 createRequestFunc = (continuationToken, pageSize) -> { Map requestHeaders = new HashMap<>(); if (continuationToken != null) { @@ -3015,7 +2666,7 @@ private Observable> readFeed(FeedOptions op options = new FeedOptions(); } - int maxPageSize = options.getMaxItemCount() != null ? options.getMaxItemCount() : -1; + int maxPageSize = options.maxItemCount() != null ? options.maxItemCount() : -1; final FeedOptions finalFeedOptions = options; Func2 createRequestFunc = (continuationToken, pageSize) -> { Map requestHeaders = new HashMap<>(); @@ -3093,7 +2744,7 @@ public Observable getDatabaseAccountFromEndpoint(URI endpoint) logger.warn(message); }).map(rsp -> rsp.getResource(DatabaseAccount.class)) .doOnNext(databaseAccount -> { - this.useMultipleWriteLocations = this.connectionPolicy.isUsingMultipleWriteLocations() + this.useMultipleWriteLocations = this.connectionPolicy.usingMultipleWriteLocations() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); }); }); @@ -3106,8 +2757,8 @@ public Observable getDatabaseAccountFromEndpoint(URI endpoint) * @return RxStoreModel */ private RxStoreModel getStoreProxy(RxDocumentServiceRequest request) { - // If a request is configured to always use Gateway mode(in some cases when targeting .NET Core) - // we return the Gateway store model + // If a request is configured to always use GATEWAY mode(in some cases when targeting .NET Core) + // we return the GATEWAY store model if (request.UseGatewayMode) { return this.gatewayProxy; } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/RxPartitionKeyRangeCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java similarity index 79% rename from sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/RxPartitionKeyRangeCache.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java index 1636b7ccd29f9..a878a93823ab0 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/caches/RxPartitionKeyRangeCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.caches; +package com.azure.data.cosmos.internal.caches; import java.util.ArrayList; import java.util.HashSet; @@ -29,28 +29,27 @@ import java.util.Set; import java.util.stream.Collectors; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.internal.routing.IServerIdentity; -import com.microsoft.azure.cosmosdb.rx.internal.NotFoundException; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.internal.routing.IServerIdentity; +import com.azure.data.cosmos.internal.NotFoundException; import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.routing.CollectionRoutingMap; -import com.microsoft.azure.cosmosdb.internal.routing.InMemoryCollectionRoutingMap; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.internal.Exceptions; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.Utils; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.InMemoryCollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.Exceptions; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; import rx.Observable; import rx.Single; @@ -73,7 +72,7 @@ public RxPartitionKeyRangeCache(AsyncDocumentClient client, RxCollectionCache co } /* (non-Javadoc) - * @see com.microsoft.azure.cosmosdb.rx.internal.caches.IPartitionKeyRangeCache#tryLookupAsync(java.lang.String, com.microsoft.azure.cosmosdb.internal.routing.CollectionRoutingMap) + * @see IPartitionKeyRangeCache#tryLookupAsync(java.lang.STRING, com.azure.data.cosmos.internal.routing.CollectionRoutingMap) */ @Override public Single tryLookupAsync(String collectionRid, CollectionRoutingMap previousValue, Map properties) { @@ -83,7 +82,7 @@ public Single tryLookupAsync(String collectionRid, Collect () -> getRoutingMapForCollectionAsync(collectionRid, previousValue, properties)) .onErrorResumeNext(err -> { logger.debug("tryLookupAsync on collectionRid {} encountered failure", collectionRid, err); - DocumentClientException dce = Utils.as(err, DocumentClientException.class); + CosmosClientException dce = Utils.as(err, CosmosClientException.class); if (dce != null && Exceptions.isStatusCode(dce, HttpConstants.StatusCodes.NOTFOUND)) { return Single.just(null); } @@ -99,7 +98,7 @@ public Single tryLookupAsync(String collectionRid, Collect } /* (non-Javadoc) - * @see com.microsoft.azure.cosmosdb.rx.internal.caches.IPartitionKeyRangeCache#tryGetOverlappingRangesAsync(java.lang.String, com.microsoft.azure.cosmosdb.internal.routing.Range, boolean) + * @see IPartitionKeyRangeCache#tryGetOverlappingRangesAsync(java.lang.STRING, com.azure.data.cosmos.internal.routing.RANGE, boolean) */ @Override public Single> tryGetOverlappingRangesAsync(String collectionRid, Range range, boolean forceRefresh, @@ -128,7 +127,7 @@ public Single> tryGetOverlappingRangesAsync(String colle } /* (non-Javadoc) - * @see com.microsoft.azure.cosmosdb.rx.internal.caches.IPartitionKeyRangeCache#tryGetPartitionKeyRangeByIdAsync(java.lang.String, java.lang.String, boolean) + * @see IPartitionKeyRangeCache#tryGetPartitionKeyRangeByIdAsync(java.lang.STRING, java.lang.STRING, boolean) */ @Override public Single tryGetPartitionKeyRangeByIdAsync(String collectionResourceId, String partitionKeyRangeId, @@ -154,7 +153,7 @@ public Single tryGetPartitionKeyRangeByIdAsync(String collect } /* (non-Javadoc) - * @see com.microsoft.azure.cosmosdb.rx.internal.caches.IPartitionKeyRangeCache#tryGetRangeByPartitionKeyRangeId(java.lang.String, java.lang.String) + * @see IPartitionKeyRangeCache#tryGetRangeByPartitionKeyRangeId(java.lang.STRING, java.lang.STRING) */ @Override public Single tryGetRangeByPartitionKeyRangeId(String collectionRid, String partitionKeyRangeId, Map properties) { @@ -165,7 +164,7 @@ public Single tryGetRangeByPartitionKeyRangeId(String collect return routingMapObs.map(routingMap -> routingMap.getRangeByPartitionKeyRangeId(partitionKeyRangeId)) .onErrorResumeNext(err -> { - DocumentClientException dce = Utils.as(err, DocumentClientException.class); + CosmosClientException dce = Utils.as(err, CosmosClientException.class); logger.debug("tryGetRangeByPartitionKeyRangeId on collectionRid {} and partitionKeyRangeId {} encountered failure", collectionRid, partitionKeyRangeId, err); @@ -202,7 +201,7 @@ private Single getRoutingMapForCollectionAsync( Set goneRanges = new HashSet<>(ranges.stream().flatMap(range -> CollectionUtils.emptyIfNull(range.getParents()).stream()).collect(Collectors.toSet())); routingMap = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap( - rangesTuples.stream().filter(tuple -> !goneRanges.contains(tuple.left.getId())).collect(Collectors.toList()), + rangesTuples.stream().filter(tuple -> !goneRanges.contains(tuple.left.id())).collect(Collectors.toList()), collectionRid); } else @@ -212,8 +211,8 @@ private Single getRoutingMapForCollectionAsync( if (routingMap == null) { - // Range information either doesn't exist or is not complete. - return Single.error(new NotFoundException(String.format("GetRoutingMapForCollectionAsync(collectionRid: {%s}), Range information either doesn't exist or is not complete.", collectionRid))); + // RANGE information either doesn't exist or is not complete. + return Single.error(new NotFoundException(String.format("GetRoutingMapForCollectionAsync(collectionRid: {%s}), RANGE information either doesn't exist or is not complete.", collectionRid))); } return Single.just(routingMap); @@ -235,11 +234,11 @@ private Single> getPartitionKeyRange(String collectionRi FeedOptions feedOptions = new FeedOptions(); if (properties != null) { - feedOptions.setProperties(properties); + feedOptions.properties(properties); } - Observable> rs = client.readPartitionKeyRanges(coll.getSelfLink(), feedOptions) + Observable> rs = client.readPartitionKeyRanges(coll.selfLink(), feedOptions) // maxConcurrent = 1 to makes it in the right order - .flatMap(p -> Observable.from(p.getResults()), 1).toList(); + .flatMap(p -> Observable.from(p.results()), 1).toList(); return rs.toSingle(); }); } diff --git a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/GlobalAddressResolver.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java similarity index 79% rename from sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/GlobalAddressResolver.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java index 2299c4a04d317..1fc1822e73e50 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/GlobalAddressResolver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java @@ -21,26 +21,26 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.directconnectivity; - - -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.AddressInformation; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.AddressResolver; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.GatewayAddressCache; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.GatewayServiceConfigurationReader; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.IAddressResolver; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.internal.routing.CollectionRoutingMap; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.rx.internal.GlobalEndpointManager; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxCollectionCache; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxPartitionKeyRangeCache; +package com.azure.data.cosmos.internal.directconnectivity; + + +import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.directconnectivity.AddressInformation; +import com.azure.data.cosmos.directconnectivity.AddressResolver; +import com.azure.data.cosmos.directconnectivity.GatewayAddressCache; +import com.azure.data.cosmos.directconnectivity.GatewayServiceConfigurationReader; +import com.azure.data.cosmos.directconnectivity.IAddressResolver; +import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.GlobalEndpointManager; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import rx.Completable; @@ -92,7 +92,7 @@ public GlobalAddressResolver( this.routingMapProvider = routingMapProvider; this.serviceConfigReader = serviceConfigReader; - int maxBackupReadEndpoints = (connectionPolicy.isEnableReadRequestsFallback() == null || connectionPolicy.isEnableReadRequestsFallback()) ? GlobalAddressResolver.MaxBackupReadRegions : 0; + int maxBackupReadEndpoints = (connectionPolicy.enableReadRequestsFallback() == null || connectionPolicy.enableReadRequestsFallback()) ? GlobalAddressResolver.MaxBackupReadRegions : 0; this.maxEndpoints = maxBackupReadEndpoints + 2; // for write and alternate write endpoint (during failover) this.addressCacheByEndpoint = new ConcurrentHashMap<>(); @@ -105,14 +105,14 @@ public GlobalAddressResolver( } Completable openAsync(DocumentCollection collection) { - Single routingMap = this.routingMapProvider.tryLookupAsync(collection.getId(), null, null); + Single routingMap = this.routingMapProvider.tryLookupAsync(collection.id(), null, null); return routingMap.flatMapCompletable(collectionRoutingMap -> { if (collectionRoutingMap == null) { return Completable.complete(); } List ranges = ((List)collectionRoutingMap.getOrderedPartitionKeyRanges()).stream().map(range -> - new PartitionKeyRangeIdentity(collection.getResourceId(), range.getId())).collect(Collectors.toList()); + new PartitionKeyRangeIdentity(collection.resourceId(), range.id())).collect(Collectors.toList()); List tasks = new ArrayList<>(); for (EndpointCache endpointCache : this.addressCacheByEndpoint.values()) { tasks.add(endpointCache.addressCache.openAsync(collection, ranges)); diff --git a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/package-info.java b/sdk/src/main/java/com/azure/data/cosmos/package-info.java similarity index 96% rename from sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/package-info.java rename to sdk/src/main/java/com/azure/data/cosmos/package-info.java index 2a008122642e1..683bac20c6956 100644 --- a/sdk/src/main/java/com/microsoft/azure/cosmosdb/rx/package-info.java +++ b/sdk/src/main/java/com/azure/data/cosmos/package-info.java @@ -23,4 +23,4 @@ /** * This package provides Rx interfaces for interacting with Azure Cosmos DB. */ -package com.microsoft.azure.cosmosdb.rx; \ No newline at end of file +package com.azure.data.cosmos; \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/ClientUnderTestBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java similarity index 92% rename from sdk/src/test/java/com/microsoft/azure/cosmos/ClientUnderTestBuilder.java rename to sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java index d7fcc8954e705..b3caac72443bd 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/ClientUnderTestBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; import java.net.URI; import java.net.URISyntaxException; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientUnderTest; -import com.microsoft.azure.cosmosdb.rx.internal.directconnectivity.ReflectionUtils; +import com.azure.data.cosmos.internal.RxDocumentClientUnderTest; +import com.azure.data.cosmos.internal.directconnectivity.ReflectionUtils; public class ClientUnderTestBuilder extends CosmosClientBuilder { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosBridgeInternal.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosBridgeInternal.java similarity index 69% rename from sdk/src/test/java/com/microsoft/azure/cosmos/CosmosBridgeInternal.java rename to sdk/src/test/java/com/azure/data/cosmos/CosmosBridgeInternal.java index 9e12488d5a0c6..f8f8b30832416 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosBridgeInternal.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosBridgeInternal.java @@ -1,8 +1,4 @@ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.DatabaseAccount; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +package com.azure.data.cosmos; import reactor.core.publisher.Mono; @@ -21,11 +17,11 @@ public static AsyncDocumentClient getAsyncDocumentClient(CosmosClient client) { } public static CosmosDatabase getCosmosDatabaseWithNewClient(CosmosDatabase cosmosDatabase, CosmosClient client) { - return new CosmosDatabase(cosmosDatabase.getId(), client); + return new CosmosDatabase(cosmosDatabase.id(), client); } public static CosmosContainer getCosmosContainerWithNewClient(CosmosContainer cosmosContainer, CosmosDatabase cosmosDatabase, CosmosClient client) { - return new CosmosContainer(cosmosContainer.getId(), CosmosBridgeInternal.getCosmosDatabaseWithNewClient(cosmosDatabase, client)); + return new CosmosContainer(cosmosContainer.id(), CosmosBridgeInternal.getCosmosDatabaseWithNewClient(cosmosDatabase, client)); } public static Mono getDatabaseAccount(CosmosClient client) { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosContainerCrudTest.java similarity index 89% rename from sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/CosmosContainerCrudTest.java index 5aacc530925bf..1f47de95c35e1 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosContainerCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosContainerCrudTest.java @@ -20,11 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.IndexingMode; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; +import com.azure.data.cosmos.rx.FailureValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -57,7 +55,7 @@ public void testCreateContainer() throws Exception { // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(containerSettings.getId()).build(); + .withId(containerSettings.id()).build(); validateSuccess(createMono, validator); } @@ -81,12 +79,12 @@ public void testReadContainer() throws Exception { // read container CosmosContainerSettings settings = getContainerSettings(); CosmosContainer container = - client.getDatabase(PRE_EXISTING_DATABASE_ID).createContainer(settings).block().getContainer(); + client.getDatabase(PRE_EXISTING_DATABASE_ID).createContainer(settings).block().container(); Mono containerResponseMono = container.read(); // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(settings.getId()).build(); + .withId(settings.id()).build(); validateSuccess(containerResponseMono, validator); } @@ -131,20 +129,20 @@ public void testreplaceContainer() throws Exception { Mono containerMono = database.createContainer(getContainerSettings()); CosmosContainerResponse containerResponse = containerMono.block(); - CosmosContainer container = containerResponse.getContainer(); - CosmosContainerSettings settings = containerResponse.getCosmosContainerSettings(); + CosmosContainer container = containerResponse.container(); + CosmosContainerSettings settings = containerResponse.settings(); // sanity check - assertThat(settings.getIndexingPolicy().getIndexingMode()).isEqualTo(IndexingMode.Consistent); + assertThat(settings.indexingPolicy().indexingMode()).isEqualTo(IndexingMode.CONSISTENT); // replace indexing mode IndexingPolicy indexingMode = new IndexingPolicy(); - indexingMode.setIndexingMode(IndexingMode.Lazy); - settings.setIndexingPolicy(indexingMode); + indexingMode.indexingMode(IndexingMode.LAZY); + settings.indexingPolicy(indexingMode); Mono replaceMono = container.replace(settings, null); // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .indexingMode(IndexingMode.Lazy).build(); + .indexingMode(IndexingMode.LAZY).build(); validateSuccess(replaceMono, validator); } @@ -155,7 +153,7 @@ public void testGetThroughput(){ Mono containerMono = database.createContainer(getContainerSettings()); CosmosContainerResponse containerResponse = containerMono.block(); - CosmosContainer container = containerResponse.getContainer(); + CosmosContainer container = containerResponse.container(); Integer throughput = container.readProvisionedThroughput().block(); } @@ -168,7 +166,7 @@ public void testReplaceThroughput(){ Mono containerMono = database.createContainer(getContainerSettings()); CosmosContainerResponse containerResponse = containerMono.block(); - CosmosContainer container = containerResponse.getContainer(); + CosmosContainer container = containerResponse.container(); Integer throughput = container.replaceProvisionedThroughputAsync(newThroughput).block(); assertThat(throughput).isEqualTo(newThroughput); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseCrudTest.java similarity index 97% rename from sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseCrudTest.java index 6f648a64dd591..68eccbdc3492a 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseCrudTest.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; +import com.azure.data.cosmos.rx.FailureValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; @@ -54,7 +54,7 @@ public void createDatabase() throws Exception { // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(databaseSettings.getId()).build(); + .withId(databaseSettings.id()).build(); validateSuccess(createMono , validator); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseForTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java similarity index 83% rename from sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseForTest.java rename to sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java index 925f1836878f3..c6b67cb5d6589 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosDatabaseForTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java @@ -1,137 +1,131 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.microsoft.azure.cosmos; - -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.microsoft.azure.cosmos.CosmosDatabaseSettings; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.SqlParameter; -import com.microsoft.azure.cosmosdb.SqlParameterCollection; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.time.Duration; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -public class CosmosDatabaseForTest { - private static Logger logger = LoggerFactory.getLogger(CosmosDatabaseForTest.class); - public static final String SHARED_DB_ID_PREFIX = "RxJava.SDKTest.SharedDatabase"; - private static final Duration CLEANUP_THRESHOLD_DURATION = Duration.ofHours(2); - private static final String DELIMITER = "_"; - private static DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss"); - - public LocalDateTime createdTime; - public CosmosDatabase createdDatabase; - - private CosmosDatabaseForTest(CosmosDatabase db, LocalDateTime createdTime) { - this.createdDatabase = db; - this.createdTime = createdTime; - } - - private boolean isStale() { - return isOlderThan(CLEANUP_THRESHOLD_DURATION); - } - - private boolean isOlderThan(Duration dur) { - return createdTime.isBefore(LocalDateTime.now().minus(dur)); - } - - public static String generateId() { - return SHARED_DB_ID_PREFIX + DELIMITER + TIME_FORMATTER.format(LocalDateTime.now()) + DELIMITER + RandomStringUtils.randomAlphabetic(3); - } - - private static CosmosDatabaseForTest from(CosmosDatabase db) { - if (db == null || db.getId() == null || db.getLink() == null) { - return null; - } - - String id = db.getId(); - if (id == null) { - return null; - } - - String[] parts = StringUtils.split(id, DELIMITER); - if (parts.length != 3) { - return null; - } - if (!StringUtils.equals(parts[0], SHARED_DB_ID_PREFIX)) { - return null; - } - - try { - LocalDateTime parsedTime = LocalDateTime.parse(parts[1], TIME_FORMATTER); - return new CosmosDatabaseForTest(db, parsedTime); - } catch (Exception e) { - return null; - } - } - - public static CosmosDatabaseForTest create(DatabaseManager client) { - CosmosDatabaseSettings dbDef = new CosmosDatabaseSettings(generateId()); - - CosmosDatabase db = client.createDatabase(dbDef).block().getDatabase(); - CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.from(db); - assertThat(dbForTest).isNotNull(); - return dbForTest; - } - - public static void cleanupStaleTestDatabases(DatabaseManager client) { - logger.info("Cleaning stale test databases ..."); - List dbs = client.queryDatabases( - new SqlQuerySpec("SELECT * FROM c WHERE STARTSWITH(c.id, @PREFIX)", - new SqlParameterCollection(new SqlParameter("@PREFIX", CosmosDatabaseForTest.SHARED_DB_ID_PREFIX)))) - .flatMap(page -> Flux.fromIterable(page.getResults())).collectList().block(); - - for (CosmosDatabaseSettings db : dbs) { - assertThat(db.getId()).startsWith(CosmosDatabaseForTest.SHARED_DB_ID_PREFIX); - - CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.from(client.getDatabase(db.getId())); - - if (db != null && dbForTest.isStale()) { - logger.info("Deleting database {}", db.getId()); - dbForTest.deleteDatabase(db.getId()); - } - } - } - - private void deleteDatabase(String id) { - this.createdDatabase.delete().block(); - } - - public interface DatabaseManager { - Flux> queryDatabases(SqlQuerySpec query); - Mono createDatabase(CosmosDatabaseSettings databaseDefinition); - CosmosDatabase getDatabase(String id); - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.azure.data.cosmos; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CosmosDatabaseForTest { + private static Logger logger = LoggerFactory.getLogger(CosmosDatabaseForTest.class); + public static final String SHARED_DB_ID_PREFIX = "RxJava.SDKTest.SharedDatabase"; + private static final Duration CLEANUP_THRESHOLD_DURATION = Duration.ofHours(2); + private static final String DELIMITER = "_"; + private static DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss"); + + public LocalDateTime createdTime; + public CosmosDatabase createdDatabase; + + private CosmosDatabaseForTest(CosmosDatabase db, LocalDateTime createdTime) { + this.createdDatabase = db; + this.createdTime = createdTime; + } + + private boolean isStale() { + return isOlderThan(CLEANUP_THRESHOLD_DURATION); + } + + private boolean isOlderThan(Duration dur) { + return createdTime.isBefore(LocalDateTime.now().minus(dur)); + } + + public static String generateId() { + return SHARED_DB_ID_PREFIX + DELIMITER + TIME_FORMATTER.format(LocalDateTime.now()) + DELIMITER + RandomStringUtils.randomAlphabetic(3); + } + + private static CosmosDatabaseForTest from(CosmosDatabase db) { + if (db == null || db.id() == null || db.getLink() == null) { + return null; + } + + String id = db.id(); + if (id == null) { + return null; + } + + String[] parts = StringUtils.split(id, DELIMITER); + if (parts.length != 3) { + return null; + } + if (!StringUtils.equals(parts[0], SHARED_DB_ID_PREFIX)) { + return null; + } + + try { + LocalDateTime parsedTime = LocalDateTime.parse(parts[1], TIME_FORMATTER); + return new CosmosDatabaseForTest(db, parsedTime); + } catch (Exception e) { + return null; + } + } + + public static CosmosDatabaseForTest create(DatabaseManager client) { + CosmosDatabaseSettings dbDef = new CosmosDatabaseSettings(generateId()); + + CosmosDatabase db = client.createDatabase(dbDef).block().database(); + CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.from(db); + assertThat(dbForTest).isNotNull(); + return dbForTest; + } + + public static void cleanupStaleTestDatabases(DatabaseManager client) { + logger.info("Cleaning stale test databases ..."); + List dbs = client.queryDatabases( + new SqlQuerySpec("SELECT * FROM c WHERE STARTSWITH(c.id, @PREFIX)", + new SqlParameterCollection(new SqlParameter("@PREFIX", CosmosDatabaseForTest.SHARED_DB_ID_PREFIX)))) + .flatMap(page -> Flux.fromIterable(page.results())).collectList().block(); + + for (CosmosDatabaseSettings db : dbs) { + assertThat(db.id()).startsWith(CosmosDatabaseForTest.SHARED_DB_ID_PREFIX); + + CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.from(client.getDatabase(db.id())); + + if (db != null && dbForTest.isStale()) { + logger.info("Deleting database {}", db.id()); + dbForTest.deleteDatabase(db.id()); + } + } + } + + private void deleteDatabase(String id) { + this.createdDatabase.delete().block(); + } + + public interface DatabaseManager { + Flux> queryDatabases(SqlQuerySpec query); + Mono createDatabase(CosmosDatabaseSettings databaseDefinition); + CosmosDatabase getDatabase(String id); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosItemCrudTest.java similarity index 89% rename from sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/CosmosItemCrudTest.java index f3e524d31f7ca..2cfb6bc8e3854 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosItemCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosItemCrudTest.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; +import com.azure.data.cosmos.rx.FailureValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -48,20 +48,20 @@ public CosmosItemCrudTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void testCreateItem() throws Exception { CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItemSettings itemDefinition = getItemDefinition(); + CosmosItemProperties itemDefinition = getItemDefinition(); // create the item Mono createMono = container.createItem(itemDefinition, "mypk"); // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(itemDefinition.getId()).build(); + .withId(itemDefinition.id()).build(); validateSuccess(createMono, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void testCreateItem_AlreadyExists() throws Exception { CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItemSettings itemDefinition = getItemDefinition(); + CosmosItemProperties itemDefinition = getItemDefinition(); // create the item container.createItem(itemDefinition, itemDefinition.get("mypk")).block(); @@ -77,23 +77,23 @@ public void testCreateItem_AlreadyExists() throws Exception { public void testReadItem() throws Exception { // read item CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItemSettings itemDefinition = getItemDefinition(); + CosmosItemProperties itemDefinition = getItemDefinition(); // create the item - CosmosItem item = container.createItem(itemDefinition, "mypk").block().getItem(); + CosmosItem item = container.createItem(itemDefinition, "mypk").block().item(); Mono readMono = item.read(); // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(itemDefinition.getId()).build(); + .withId(itemDefinition.id()).build(); validateSuccess(readMono, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void testDeleteItem() throws Exception { CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItemSettings itemDefinition = getItemDefinition(); + CosmosItemProperties itemDefinition = getItemDefinition(); // create the item - CosmosItem item = container.createItem(itemDefinition, "mypk").block().getItem(); + CosmosItem item = container.createItem(itemDefinition, "mypk").block().item(); Mono deleteMono = item.delete(); // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -105,9 +105,9 @@ public void testDeleteItem() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void testreplaceItem() throws Exception { CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItemSettings itemDefinition = getItemDefinition(); + CosmosItemProperties itemDefinition = getItemDefinition(); // create the item - CosmosItem item = container.createItem(itemDefinition, "mypk").block().getItem(); + CosmosItem item = container.createItem(itemDefinition, "mypk").block().item(); String newPropValue = UUID.randomUUID().toString(); itemDefinition.set("newProp", newPropValue); @@ -134,9 +134,9 @@ public void afterClass() { safeClose(client); } - private CosmosItemSettings getItemDefinition() { + private CosmosItemProperties getItemDefinition() { String uuid = UUID.randomUUID().toString(); - return new CosmosItemSettings(String.format("{ " + return new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosPartitionKeyTests.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java similarity index 80% rename from sdk/src/test/java/com/microsoft/azure/cosmos/CosmosPartitionKeyTests.java rename to sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java index eff5aa465293d..0d8578e6527ae 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosPartitionKeyTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; +package com.azure.data.cosmos; import static org.assertj.core.api.Assertions.assertThat; @@ -42,25 +42,18 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.internal.BaseAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.Paths; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.Utils; -import com.microsoft.azure.cosmosdb.rx.FeedResponseListValidator; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.TestSuiteBase; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.HttpClientFactory; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.rx.FeedResponseListValidator; +import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.rx.TestSuiteBase; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.HttpClientFactory; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; @@ -100,18 +93,18 @@ public void afterClass() { private void createContainerWithoutPk() throws URISyntaxException, IOException { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); HttpClientFactory factory = new HttpClientFactory(new Configs()) - .withMaxIdleConnectionTimeoutInMillis(connectionPolicy.getIdleConnectionTimeoutInMillis()) - .withPoolSize(connectionPolicy.getMaxPoolSize()) - .withHttpProxy(connectionPolicy.getProxy()) - .withRequestTimeoutInMillis(connectionPolicy.getRequestTimeoutInMillis()); + .withMaxIdleConnectionTimeoutInMillis(connectionPolicy.idleConnectionTimeoutInMillis()) + .withPoolSize(connectionPolicy.maxPoolSize()) + .withHttpProxy(connectionPolicy.proxy()) + .withRequestTimeoutInMillis(connectionPolicy.requestTimeoutInMillis()); CompositeHttpClient httpClient = factory.toHttpClientBuilder().build(); - // Create a non partitioned collection using the rest API and older version - String resourceId = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.getId(); - String path = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.getId() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/"; + // CREATE a non partitioned collection using the rest API and older version + String resourceId = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.id(); + String path = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.id() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/"; DocumentCollection collection = new DocumentCollection(); - collection.setId(NON_PARTITIONED_CONTAINER_ID); + collection.id(NON_PARTITIONED_CONTAINER_ID); HashMap headers = new HashMap(); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); @@ -124,7 +117,7 @@ private void createContainerWithoutPk() throws URISyntaxException, IOException { String[] baseUrlSplit = TestConfigurations.HOST.split(":"); String resourceUri = baseUrlSplit[0] + ":" + baseUrlSplit[1] + ":" + baseUrlSplit[2].split("/")[ - 0] + "//" + Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.getId() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/"; + 0] + "//" + Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.id() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/"; URI uri = new URI(resourceUri); HttpClientRequest httpRequest = HttpClientRequest.create(HttpMethod.POST, uri.toString()); @@ -144,12 +137,12 @@ private void createContainerWithoutPk() throws URISyntaxException, IOException { String createdContainerAsString = IOUtils.readLines(responseStream, "UTF-8").get(0); assertThat(createdContainerAsString).contains("\"id\":\"" + NON_PARTITIONED_CONTAINER_ID + "\""); - // Create a document in the non partitioned collection using the rest API and older version - resourceId = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.getId() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/" + collection.getId(); - path = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.getId() + "/" + Paths.COLLECTIONS_PATH_SEGMENT - + "/" + collection.getId() + "/" + Paths.DOCUMENTS_PATH_SEGMENT + "/"; + // CREATE a document in the non partitioned collection using the rest API and older version + resourceId = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.id() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/" + collection.id(); + path = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.id() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + + "/" + collection.id() + "/" + Paths.DOCUMENTS_PATH_SEGMENT + "/"; Document document = new Document(); - document.setId(NON_PARTITIONED_CONTAINER_DOCUEMNT_ID); + document.id(NON_PARTITIONED_CONTAINER_DOCUEMNT_ID); authorization = base.generateKeyAuthorizationSignature(HttpConstants.HttpMethods.POST, resourceId, Paths.DOCUMENTS_PATH_SEGMENT, headers); headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, URLEncoder.encode(authorization, "UTF-8")); @@ -157,7 +150,7 @@ private void createContainerWithoutPk() throws URISyntaxException, IOException { document, headers, new RequestOptions()); resourceUri = baseUrlSplit[0] + ":" + baseUrlSplit[1] + ":" + baseUrlSplit[2].split("/")[0] + "//" + Paths.DATABASES_PATH_SEGMENT + "/" - + createdDatabase.getId() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/" + collection.getId() + "/" + Paths.DOCUMENTS_PATH_SEGMENT + "/"; + + createdDatabase.id() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/" + collection.id() + "/" + Paths.DOCUMENTS_PATH_SEGMENT + "/"; uri = new URI(resourceUri); httpRequest = HttpClientRequest.create(HttpMethod.POST, uri.toString()); @@ -188,7 +181,7 @@ public void testNonPartitionedCollectionOperations() throws Exception { validateSuccess(readMono, validator); String createdItemId = UUID.randomUUID().toString(); - Mono createMono = createdContainer.createItem(new CosmosItemSettings("{'id':'" + createdItemId + "'}")); + Mono createMono = createdContainer.createItem(new CosmosItemProperties("{'id':'" + createdItemId + "'}")); validator = new CosmosResponseValidator.Builder() .withId(createdItemId).build(); validateSuccess(createMono, validator); @@ -198,10 +191,10 @@ public void testNonPartitionedCollectionOperations() throws Exception { .withId(createdItemId).build(); validateSuccess(readMono, validator); - CosmosItem itemToReplace = createdContainer.getItem(createdItemId, PartitionKey.None).read().block().getCosmosItem(); - CosmosItemSettings itemSettingsToReplace = itemToReplace.read().block().getCosmosItemSettings(); + CosmosItem itemToReplace = createdContainer.getItem(createdItemId, PartitionKey.None).read().block().item(); + CosmosItemProperties itemSettingsToReplace = itemToReplace.read().block().properties(); String replacedItemId = UUID.randomUUID().toString(); - itemSettingsToReplace.setId(replacedItemId); + itemSettingsToReplace.id(replacedItemId); Mono replaceMono = itemToReplace.replace(itemSettingsToReplace); validator = new CosmosResponseValidator.Builder() .withId(replacedItemId).build(); @@ -209,20 +202,20 @@ public void testNonPartitionedCollectionOperations() throws Exception { String upsertedItemId = UUID.randomUUID().toString(); - Mono upsertMono = createdContainer.upsertItem(new CosmosItemSettings("{'id':'" + upsertedItemId + "'}")); + Mono upsertMono = createdContainer.upsertItem(new CosmosItemProperties("{'id':'" + upsertedItemId + "'}")); validator = new CosmosResponseValidator.Builder() .withId(upsertedItemId).build(); validateSuccess(upsertMono, validator); // one document was created during setup, one with create (which was replaced) and one with upsert FeedOptions feedOptions = new FeedOptions(); - feedOptions.setPartitionKey(PartitionKey.None); + feedOptions.partitionKey(PartitionKey.None); ArrayList expectedIds = new ArrayList(); expectedIds.add(NON_PARTITIONED_CONTAINER_DOCUEMNT_ID); expectedIds.add(replacedItemId); expectedIds.add(upsertedItemId); - Flux> queryFlux = createdContainer.queryItems("SELECT * from c", feedOptions); - FeedResponseListValidator queryValidator = new FeedResponseListValidator.Builder() + Flux> queryFlux = createdContainer.queryItems("SELECT * from c", feedOptions); + FeedResponseListValidator queryValidator = new FeedResponseListValidator.Builder() .totalSize(3) .numberOfPages(1) .containsExactlyIds(expectedIds) @@ -230,7 +223,7 @@ public void testNonPartitionedCollectionOperations() throws Exception { validateQuerySuccess(queryFlux, queryValidator); queryFlux = createdContainer.listItems(feedOptions); - queryValidator = new FeedResponseListValidator.Builder() + queryValidator = new FeedResponseListValidator.Builder() .totalSize(3) .numberOfPages(1) .containsExactlyIds(expectedIds) @@ -244,26 +237,26 @@ public void testNonPartitionedCollectionOperations() throws Exception { " 'body':'" + " function() {" + " var client = getContext().getCollection();" + - " var doc = client.createDocument(client.getSelfLink(), { \\'id\\': \\'" + documentCreatedBySprocId + "\\'}, {}, function(err, docCreated, options) { " + + " var doc = client.createDocument(client.selfLink(), { \\'id\\': \\'" + documentCreatedBySprocId + "\\'}, {}, function(err, docCreated, options) { " + " if(err) throw new Error(\\'Error while creating document: \\' + err.message);" + " else {" + - " getContext().getResponse().setBody(1);" + + " getContext().getResponse().body(1);" + " }" + " });" + "}'" + "}"); - CosmosStoredProcedure createdSproc = createdContainer.createStoredProcedure(sproc).block().getStoredProcedure(); + CosmosStoredProcedure createdSproc = createdContainer.createStoredProcedure(sproc).block().storedProcedure(); // Partiton Key value same as what is specified in the stored procedure body RequestOptions options = new RequestOptions(); options.setPartitionKey(PartitionKey.None); - int result = Integer.parseInt(createdSproc.execute(null, options).block().getResponseAsString()); + int result = Integer.parseInt(createdSproc.execute(null, options).block().responseAsString()); assertThat(result).isEqualTo(1); // 3 previous items + 1 created from the sproc expectedIds.add(documentCreatedBySprocId); queryFlux = createdContainer.listItems(feedOptions); - queryValidator = new FeedResponseListValidator.Builder() + queryValidator = new FeedResponseListValidator.Builder() .totalSize(4) .numberOfPages(1) .containsExactlyIds(expectedIds) @@ -291,7 +284,7 @@ public void testNonPartitionedCollectionOperations() throws Exception { validateSuccess(deleteMono, validator); queryFlux = createdContainer.listItems(feedOptions); - queryValidator = new FeedResponseListValidator.Builder() + queryValidator = new FeedResponseListValidator.Builder() .totalSize(0) .numberOfPages(1) .build(); @@ -303,12 +296,12 @@ public void testMultiPartitionCollectionReadDocumentWithNoPk() throws Interrupte String partitionedCollectionId = "PartitionedCollection" + UUID.randomUUID().toString(); String IdOfDocumentWithNoPk = UUID.randomUUID().toString(); CosmosContainerSettings containerSettings = new CosmosContainerSettings(partitionedCollectionId, "/mypk"); - CosmosContainer createdContainer = createdDatabase.createContainer(containerSettings).block().getContainer(); - CosmosItemSettings cosmosItemSettings = new CosmosItemSettings(); - cosmosItemSettings.setId(IdOfDocumentWithNoPk); - CosmosItem createdItem = createdContainer.createItem(cosmosItemSettings).block().getCosmosItem(); + CosmosContainer createdContainer = createdDatabase.createContainer(containerSettings).block().container(); + CosmosItemProperties cosmosItemProperties = new CosmosItemProperties(); + cosmosItemProperties.id(IdOfDocumentWithNoPk); + CosmosItem createdItem = createdContainer.createItem(cosmosItemProperties).block().item(); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(PartitionKey.None); + options.partitionKey(PartitionKey.None); Mono readMono = createdItem.read(options); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(IdOfDocumentWithNoPk).build(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java similarity index 77% rename from sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java index 91a319718fb18..f3e6d41eda935 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosResponseValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java @@ -1,269 +1,256 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.CompositePath; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.IndexingMode; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.SpatialSpec; -import com.microsoft.azure.cosmosdb.SpatialType; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.Trigger; -import com.microsoft.azure.cosmosdb.TriggerOperation; -import com.microsoft.azure.cosmosdb.TriggerType; -import com.microsoft.azure.cosmosdb.UserDefinedFunction; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; - -import static org.assertj.core.api.Assertions.assertThat; - -public interface CosmosResponseValidator { - void validate(T cosmosResponse); - - class Builder { - private List> validators = new ArrayList<>(); - - public CosmosResponseValidator build() { - return new CosmosResponseValidator() { - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public void validate(T resourceResponse) { - for (CosmosResponseValidator validator : validators) { - validator.validate(resourceResponse); - } - } - }; - } - - public Builder withId(final String resourceId) { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(T resourceResponse) { - assertThat(getResource(resourceResponse)).isNotNull(); - assertThat(getResource(resourceResponse).getId()).as("check Resource Id").isEqualTo(resourceId); - } - }); - return this; - } - - private Resource getResource(T resourceResponse) { - if (resourceResponse instanceof CosmosDatabaseResponse) { - return ((CosmosDatabaseResponse)resourceResponse).getCosmosDatabaseSettings(); - } else if (resourceResponse instanceof CosmosContainerResponse) { - return ((CosmosContainerResponse)resourceResponse).getCosmosContainerSettings(); - } else if (resourceResponse instanceof CosmosItemResponse) { - return ((CosmosItemResponse)resourceResponse).getCosmosItemSettings(); - } else if (resourceResponse instanceof CosmosStoredProcedureResponse) { - return ((CosmosStoredProcedureResponse)resourceResponse).getStoredProcedureSettings(); - } else if (resourceResponse instanceof CosmosTriggerResponse) { - return ((CosmosTriggerResponse)resourceResponse).getCosmosTriggerSettings(); - } else if (resourceResponse instanceof CosmosUserDefinedFunctionResponse) { - return ((CosmosUserDefinedFunctionResponse)resourceResponse).getCosmosUserDefinedFunctionSettings(); - } else if (resourceResponse instanceof CosmosUserResponse) { - return ((CosmosUserResponse)resourceResponse).getCosmosUserSettings(); - } - return null; - } - - public Builder nullResource() { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(T resourceResponse) { - assertThat(getResource(resourceResponse)).isNull(); - } - }); - return this; - } - - public Builder indexingMode(IndexingMode mode) { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(CosmosContainerResponse resourceResponse) { - assertThat(resourceResponse.getCosmosContainerSettings()).isNotNull(); - assertThat(resourceResponse.getCosmosContainerSettings().getIndexingPolicy()).isNotNull(); - assertThat(resourceResponse.getCosmosContainerSettings().getIndexingPolicy().getIndexingMode()).isEqualTo(mode); - } - }); - return this; - } - - public Builder withProperty(String propertyName, String value) { - validators.add(new CosmosResponseValidator() { - @Override - public void validate(T cosmosResponse) { - assertThat(getResource(cosmosResponse)).isNotNull(); - assertThat(getResource(cosmosResponse).get(propertyName)).isEqualTo(value); - } - }); - return this; - } - - public Builder withCompositeIndexes(Collection> compositeIndexesWritten) { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(CosmosContainerResponse resourceResponse) { - Iterator> compositeIndexesReadIterator = resourceResponse.getCosmosContainerSettings() - .getIndexingPolicy().getCompositeIndexes().iterator(); - Iterator> compositeIndexesWrittenIterator = compositeIndexesWritten.iterator(); - - ArrayList readIndexesStrings = new ArrayList(); - ArrayList writtenIndexesStrings = new ArrayList(); - - while (compositeIndexesReadIterator.hasNext() && compositeIndexesWrittenIterator.hasNext()) { - Iterator compositeIndexReadIterator = compositeIndexesReadIterator.next().iterator(); - Iterator compositeIndexWrittenIterator = compositeIndexesWrittenIterator.next().iterator(); - - StringBuilder readIndexesString = new StringBuilder(); - StringBuilder writtenIndexesString = new StringBuilder(); - - while (compositeIndexReadIterator.hasNext() && compositeIndexWrittenIterator.hasNext()) { - CompositePath compositePathRead = compositeIndexReadIterator.next(); - CompositePath compositePathWritten = compositeIndexWrittenIterator.next(); - - readIndexesString.append(compositePathRead.getPath() + ":" + compositePathRead.getOrder() + ";"); - writtenIndexesString.append(compositePathWritten.getPath() + ":" + compositePathRead.getOrder() + ";"); - } - - readIndexesStrings.add(readIndexesString.toString()); - writtenIndexesStrings.add(writtenIndexesString.toString()); - } - - assertThat(readIndexesStrings).containsExactlyInAnyOrderElementsOf(writtenIndexesStrings); - } - - }); - return this; - } - - public Builder withSpatialIndexes(Collection spatialIndexes) { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(CosmosContainerResponse resourceResponse) { - Iterator spatialIndexesReadIterator = resourceResponse.getCosmosContainerSettings() - .getIndexingPolicy().getSpatialIndexes().iterator(); - Iterator spatialIndexesWrittenIterator = spatialIndexes.iterator(); - - HashMap> readIndexMap = new HashMap>(); - HashMap> writtenIndexMap = new HashMap>(); - - while (spatialIndexesReadIterator.hasNext() && spatialIndexesWrittenIterator.hasNext()) { - SpatialSpec spatialSpecRead = spatialIndexesReadIterator.next(); - SpatialSpec spatialSpecWritten = spatialIndexesWrittenIterator.next(); - - String readPath = spatialSpecRead.getPath() + ":"; - String writtenPath = spatialSpecWritten.getPath() + ":"; - - ArrayList readSpatialTypes = new ArrayList(); - ArrayList writtenSpatialTypes = new ArrayList(); - - Iterator spatialTypesReadIterator = spatialSpecRead.getSpatialTypes().iterator(); - Iterator spatialTypesWrittenIterator = spatialSpecWritten.getSpatialTypes().iterator(); - - while (spatialTypesReadIterator.hasNext() && spatialTypesWrittenIterator.hasNext()) { - readSpatialTypes.add(spatialTypesReadIterator.next()); - writtenSpatialTypes.add(spatialTypesWrittenIterator.next()); - } - - readIndexMap.put(readPath, readSpatialTypes); - writtenIndexMap.put(writtenPath, writtenSpatialTypes); - } - - for (Entry> entry : readIndexMap.entrySet()) { - assertThat(entry.getValue()) - .containsExactlyInAnyOrderElementsOf(writtenIndexMap.get(entry.getKey())); - } - } - }); - return this; - } - - public Builder withStoredProcedureBody(String storedProcedureBody) { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(CosmosStoredProcedureResponse resourceResponse) { - assertThat(resourceResponse.getStoredProcedureSettings().getBody()).isEqualTo(storedProcedureBody); - } - }); - return this; - } - - public Builder notNullEtag() { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(T resourceResponse) { - assertThat(resourceResponse.getResourceSettings()).isNotNull(); - assertThat(resourceResponse.getResourceSettings().getETag()).isNotNull(); - } - }); - return this; - } - - public Builder withTriggerBody(String functionBody) { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(CosmosTriggerResponse resourceResponse) { - assertThat(resourceResponse.getCosmosTriggerSettings().getBody()).isEqualTo(functionBody); - } - }); - return this; - } - - public Builder withTriggerInternals(TriggerType type, TriggerOperation op) { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(CosmosTriggerResponse resourceResponse) { - assertThat(resourceResponse.getCosmosTriggerSettings().getTriggerType()).isEqualTo(type); - assertThat(resourceResponse.getCosmosTriggerSettings().getTriggerOperation()).isEqualTo(op); - } - }); - return this; - } - - public Builder withUserDefinedFunctionBody(String functionBody) { - validators.add(new CosmosResponseValidator() { - - @Override - public void validate(CosmosUserDefinedFunctionResponse resourceResponse) { - assertThat(resourceResponse.getCosmosUserDefinedFunctionSettings().getBody()).isEqualTo(functionBody); - } - }); - return this; - } - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; + +import static org.assertj.core.api.Assertions.assertThat; + +public interface CosmosResponseValidator { + void validate(T cosmosResponse); + + class Builder { + private List> validators = new ArrayList<>(); + + public CosmosResponseValidator build() { + return new CosmosResponseValidator() { + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void validate(T resourceResponse) { + for (CosmosResponseValidator validator : validators) { + validator.validate(resourceResponse); + } + } + }; + } + + public Builder withId(final String resourceId) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(T resourceResponse) { + assertThat(getResource(resourceResponse)).isNotNull(); + assertThat(getResource(resourceResponse).id()).as("check Resource Id").isEqualTo(resourceId); + } + }); + return this; + } + + private Resource getResource(T resourceResponse) { + if (resourceResponse instanceof CosmosDatabaseResponse) { + return ((CosmosDatabaseResponse)resourceResponse).settings(); + } else if (resourceResponse instanceof CosmosContainerResponse) { + return ((CosmosContainerResponse)resourceResponse).settings(); + } else if (resourceResponse instanceof CosmosItemResponse) { + return ((CosmosItemResponse)resourceResponse).properties(); + } else if (resourceResponse instanceof CosmosStoredProcedureResponse) { + return ((CosmosStoredProcedureResponse)resourceResponse).settings(); + } else if (resourceResponse instanceof CosmosTriggerResponse) { + return ((CosmosTriggerResponse)resourceResponse).settings(); + } else if (resourceResponse instanceof CosmosUserDefinedFunctionResponse) { + return ((CosmosUserDefinedFunctionResponse)resourceResponse).settings(); + } else if (resourceResponse instanceof CosmosUserResponse) { + return ((CosmosUserResponse)resourceResponse).settings(); + } + return null; + } + + public Builder nullResource() { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(T resourceResponse) { + assertThat(getResource(resourceResponse)).isNull(); + } + }); + return this; + } + + public Builder indexingMode(IndexingMode mode) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosContainerResponse resourceResponse) { + assertThat(resourceResponse.settings()).isNotNull(); + assertThat(resourceResponse.settings().indexingPolicy()).isNotNull(); + assertThat(resourceResponse.settings().indexingPolicy().indexingMode()).isEqualTo(mode); + } + }); + return this; + } + + public Builder withProperty(String propertyName, String value) { + validators.add(new CosmosResponseValidator() { + @Override + public void validate(T cosmosResponse) { + assertThat(getResource(cosmosResponse)).isNotNull(); + assertThat(getResource(cosmosResponse).get(propertyName)).isEqualTo(value); + } + }); + return this; + } + + public Builder withCompositeIndexes(Collection> compositeIndexesWritten) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosContainerResponse resourceResponse) { + Iterator> compositeIndexesReadIterator = resourceResponse.settings() + .indexingPolicy().compositeIndexes().iterator(); + Iterator> compositeIndexesWrittenIterator = compositeIndexesWritten.iterator(); + + ArrayList readIndexesStrings = new ArrayList(); + ArrayList writtenIndexesStrings = new ArrayList(); + + while (compositeIndexesReadIterator.hasNext() && compositeIndexesWrittenIterator.hasNext()) { + Iterator compositeIndexReadIterator = compositeIndexesReadIterator.next().iterator(); + Iterator compositeIndexWrittenIterator = compositeIndexesWrittenIterator.next().iterator(); + + StringBuilder readIndexesString = new StringBuilder(); + StringBuilder writtenIndexesString = new StringBuilder(); + + while (compositeIndexReadIterator.hasNext() && compositeIndexWrittenIterator.hasNext()) { + CompositePath compositePathRead = compositeIndexReadIterator.next(); + CompositePath compositePathWritten = compositeIndexWrittenIterator.next(); + + readIndexesString.append(compositePathRead.path() + ":" + compositePathRead.order() + ";"); + writtenIndexesString.append(compositePathWritten.path() + ":" + compositePathRead.order() + ";"); + } + + readIndexesStrings.add(readIndexesString.toString()); + writtenIndexesStrings.add(writtenIndexesString.toString()); + } + + assertThat(readIndexesStrings).containsExactlyInAnyOrderElementsOf(writtenIndexesStrings); + } + + }); + return this; + } + + public Builder withSpatialIndexes(Collection spatialIndexes) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosContainerResponse resourceResponse) { + Iterator spatialIndexesReadIterator = resourceResponse.settings() + .indexingPolicy().spatialIndexes().iterator(); + Iterator spatialIndexesWrittenIterator = spatialIndexes.iterator(); + + HashMap> readIndexMap = new HashMap>(); + HashMap> writtenIndexMap = new HashMap>(); + + while (spatialIndexesReadIterator.hasNext() && spatialIndexesWrittenIterator.hasNext()) { + SpatialSpec spatialSpecRead = spatialIndexesReadIterator.next(); + SpatialSpec spatialSpecWritten = spatialIndexesWrittenIterator.next(); + + String readPath = spatialSpecRead.path() + ":"; + String writtenPath = spatialSpecWritten.path() + ":"; + + ArrayList readSpatialTypes = new ArrayList(); + ArrayList writtenSpatialTypes = new ArrayList(); + + Iterator spatialTypesReadIterator = spatialSpecRead.spatialTypes().iterator(); + Iterator spatialTypesWrittenIterator = spatialSpecWritten.spatialTypes().iterator(); + + while (spatialTypesReadIterator.hasNext() && spatialTypesWrittenIterator.hasNext()) { + readSpatialTypes.add(spatialTypesReadIterator.next()); + writtenSpatialTypes.add(spatialTypesWrittenIterator.next()); + } + + readIndexMap.put(readPath, readSpatialTypes); + writtenIndexMap.put(writtenPath, writtenSpatialTypes); + } + + for (Entry> entry : readIndexMap.entrySet()) { + assertThat(entry.getValue()) + .containsExactlyInAnyOrderElementsOf(writtenIndexMap.get(entry.getKey())); + } + } + }); + return this; + } + + public Builder withStoredProcedureBody(String storedProcedureBody) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosStoredProcedureResponse resourceResponse) { + assertThat(resourceResponse.settings().body()).isEqualTo(storedProcedureBody); + } + }); + return this; + } + + public Builder notNullEtag() { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(T resourceResponse) { + assertThat(resourceResponse.resourceSettings()).isNotNull(); + assertThat(resourceResponse.resourceSettings().etag()).isNotNull(); + } + }); + return this; + } + + public Builder withTriggerBody(String functionBody) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosTriggerResponse resourceResponse) { + assertThat(resourceResponse.settings().body()).isEqualTo(functionBody); + } + }); + return this; + } + + public Builder withTriggerInternals(TriggerType type, TriggerOperation op) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosTriggerResponse resourceResponse) { + assertThat(resourceResponse.settings().triggerType()).isEqualTo(type); + assertThat(resourceResponse.settings().triggerOperation()).isEqualTo(op); + } + }); + return this; + } + + public Builder withUserDefinedFunctionBody(String functionBody) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosUserDefinedFunctionResponse resourceResponse) { + assertThat(resourceResponse.settings().body()).isEqualTo(functionBody); + } + }); + return this; + } + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosTestSuiteBase.java similarity index 86% rename from sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java rename to sdk/src/test/java/com/azure/data/cosmos/CosmosTestSuiteBase.java index 6f8f672407638..8ef6db8816829 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmos/CosmosTestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosTestSuiteBase.java @@ -20,17 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmos; - -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.RetryOptions; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientImpl; +package com.azure.data.cosmos; + +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.RxDocumentClientImpl; import io.reactivex.subscribers.TestSubscriber; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -101,37 +95,37 @@ public static Object[][] clientBuilders() { static protected CosmosClientBuilder createGatewayRxCosmosClient() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); RetryOptions options = new RetryOptions(); - options.setMaxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); - connectionPolicy.setRetryOptions(options); + options.maxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); + connectionPolicy.retryOptions(options); return CosmosClient.builder().connectionPolicy(connectionPolicy) .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) - .consistencyLevel(ConsistencyLevel.Session); + .consistencyLevel(ConsistencyLevel.SESSION); } static protected CosmosDatabase safeCreateDatabase(CosmosClient client, CosmosDatabaseSettings databaseSettings) { - safeDeleteDatabase(client, databaseSettings.getId()); + safeDeleteDatabase(client, databaseSettings.id()); return createDatabase(client, databaseSettings); } static protected CosmosDatabase createDatabase(CosmosClient client, String databaseId) { Mono databaseSingle = client.createDatabase(databaseId); - return databaseSingle.block().getDatabase(); + return databaseSingle.block().database(); } static protected CosmosContainer createContainerInDB(CosmosClient client, String containerID, String databaseId) { CosmosDatabase cosmosDatabaseProxy = client.getDatabase(databaseId); Mono containerSingle = cosmosDatabaseProxy.createContainer(containerID, "/mypk"); - return containerSingle.block().getContainer(); + return containerSingle.block().container(); } static private CosmosDatabase createDatabase(CosmosClient client, CosmosDatabaseSettings databaseSettings) { Mono databaseSingle = client.createDatabase(databaseSettings, new CosmosDatabaseRequestOptions()); - return databaseSingle.block().getDatabase(); + return databaseSingle.block().database(); } static protected void safeDeleteDatabase(CosmosClient client, String databaseId) { @@ -158,7 +152,7 @@ static protected CosmosContainerSettings getContainerSettings() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); CosmosContainerSettings settings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); return settings; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SpyClientBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/SpyClientBuilder.java similarity index 94% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SpyClientBuilder.java rename to sdk/src/test/java/com/azure/data/cosmos/SpyClientBuilder.java index 7e575659681e6..4c4f11b107dae 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SpyClientBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/SpyClientBuilder.java @@ -20,9 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos; -import com.microsoft.azure.cosmosdb.rx.internal.SpyClientUnderTestFactory; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; public class SpyClientBuilder extends AsyncDocumentClient.Builder { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressValidator.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/AddressValidator.java similarity index 93% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/directconnectivity/AddressValidator.java index bb19bcfbe40b7..7284988311ec2 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/AddressValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/AddressValidator.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import org.assertj.core.api.Condition; @@ -56,7 +56,7 @@ public Builder withId(final String resourceId) { @Override public void validate(Address address) { - assertThat(address.getId()).as("check Resource Id").isEqualTo(resourceId); + assertThat(address.id()).as("check Resource Id").isEqualTo(resourceId); } }); return this; @@ -115,9 +115,9 @@ public Builder protocol(Protocol protocol) { @Override public void validate(Address address) { - if (protocol == Protocol.Https) { + if (protocol == Protocol.HTTPS) { assertThat(address.getProtocolScheme()).isEqualTo("https"); - } else if (protocol == Protocol.Tcp){ + } else if (protocol == Protocol.TCP){ assertThat(address.getProtocolScheme()).isEqualTo("rntbd"); } } @@ -130,7 +130,7 @@ public Builder withRid(String rid) { @Override public void validate(Address address) { - assertThat(address.getResourceId()).isEqualTo(rid); + assertThat(address.resourceId()).isEqualTo(rid); } }); return this; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/BarrierRequestHelperTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java similarity index 91% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/BarrierRequestHelperTest.java rename to sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java index 57f6a4f79d0eb..8de8df0a2b3d2 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/BarrierRequestHelperTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java @@ -21,18 +21,18 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientImpl; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RxDocumentClientImpl; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -51,7 +51,7 @@ public void barrierBasic() { for (OperationType operationType : OperationType.values()) { Document randomResource = new Document(); - randomResource.setId(UUID.randomUUID().toString()); + randomResource.id(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, resourceType, "/dbs/7mVFAA==/colls/7mVFAP1jpeU=", randomResource, (Map) null); @@ -79,7 +79,7 @@ public void barrierDBFeed() { OperationType operationType = OperationType.Query; Document randomResource = new Document(); - randomResource.setId(UUID.randomUUID().toString()); + randomResource.id(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, resourceType, "/dbs/7mVFAA==/colls/7mVFAP1jpeU=", randomResource, (Map) null); @@ -101,7 +101,7 @@ public void barrierDocumentQueryNameBasedRequest() { OperationType operationType = OperationType.Query; Document randomResource = new Document(); - randomResource.setId(UUID.randomUUID().toString()); + randomResource.id(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, resourceType, "/dbs/dbname/colls/collname", randomResource, (Map) null); @@ -123,7 +123,7 @@ public void barrierDocumentReadNameBasedRequest() { OperationType operationType = OperationType.Read; Document randomResource = new Document(); - randomResource.setId(UUID.randomUUID().toString()); + randomResource.id(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, resourceType, "/dbs/dbname/colls/collname", randomResource, (Map) null); @@ -147,7 +147,7 @@ public void barrierDocumentReadRidBasedRequest() { OperationType operationType = OperationType.Read; Document randomResource = new Document(); - randomResource.setId(UUID.randomUUID().toString()); + randomResource.id(UUID.randomUUID().toString()); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, "7mVFAA==", resourceType, (Map) null); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/DCDocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java similarity index 82% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/DCDocumentCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java index a6d5286aab9d5..3b11d51f6206c 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java @@ -20,33 +20,32 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; - -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.StoredProcedureResponse; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.rx.DocumentServiceRequestValidator; -import com.microsoft.azure.cosmosdb.rx.FeedResponseListValidator; -import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.SpyClientUnderTestFactory; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +package com.azure.data.cosmos.directconnectivity; + +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.StoredProcedure; +import com.azure.data.cosmos.StoredProcedureResponse; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.rx.DocumentServiceRequestValidator; +import com.azure.data.cosmos.rx.FeedResponseListValidator; +import com.azure.data.cosmos.rx.ResourceResponseValidator; +import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; +import com.azure.data.cosmos.internal.TestSuiteBase; import org.mockito.stubbing.Answer; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -83,13 +82,13 @@ public class DCDocumentCrudTest extends TestSuiteBase { @DataProvider public static Object[][] directClientBuilder() { - return new Object[][] { { createDCBuilder(Protocol.Https) }, { createDCBuilder(Protocol.Tcp) } }; + return new Object[][] { { createDCBuilder(Protocol.HTTPS) }, { createDCBuilder(Protocol.TCP) } }; } static Builder createDCBuilder(Protocol protocol) { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); Configs configs = spy(new Configs()); doAnswer((Answer) invocation -> protocol).when(configs).getProtocol(); @@ -98,7 +97,7 @@ static Builder createDCBuilder(Protocol protocol) { .withServiceEndpoint(TestConfigurations.HOST) .withConfigs(configs) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY); } @@ -110,14 +109,14 @@ public DCDocumentCrudTest(Builder clientBuilder) { @Test(groups = { "direct" }, timeOut = TIMEOUT) public void executeStoredProc() { StoredProcedure storedProcedure = new StoredProcedure(); - storedProcedure.setId(UUID.randomUUID().toString()); + storedProcedure.id(UUID.randomUUID().toString()); storedProcedure.setBody("function() {var x = 10;}"); Observable> createObservable = client .createStoredProcedure(getCollectionLink(), storedProcedure, null); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(storedProcedure.getId()) + .withId(storedProcedure.id()) .build(); validateSuccess(createObservable, validator, TIMEOUT); @@ -127,7 +126,7 @@ public void executeStoredProc() { client.getCapturedRequests().clear(); // execute the created storedProc and ensure it goes through direct connectivity stack - String storedProcLink = "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId() + "/sprocs/" + storedProcedure.getId(); + String storedProcLink = "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id() + "/sprocs/" + storedProcedure.id(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey("dummy")); @@ -151,7 +150,7 @@ public void create() { this.getCollectionLink(), docDefinition, null, false); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(docDefinition.getId()) + .withId(docDefinition.id()) .build(); validateSuccess(createObservable, validator, TIMEOUT); @@ -176,10 +175,10 @@ public void read() throws Exception { options.setPartitionKey(new PartitionKey(pkValue)); String docLink = - String.format("dbs/%s/colls/%s/docs/%s", createdDatabase.getId(), createdCollection.getId(), document.getId()); + String.format("dbs/%s/colls/%s/docs/%s", createdDatabase.id(), createdCollection.id(), document.id()); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(docDefinition.getId()) + .withId(docDefinition.id()) .build(); validateSuccess(client.readDocument(docLink, options), validator, TIMEOUT); @@ -240,14 +239,14 @@ public void crossPartitionQuery() { waitIfNeededForReplicasToCatchUp(clientBuilder); FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setMaxDegreeOfParallelism(-1); - options.setMaxItemCount(100); + options.enableCrossPartitionQuery(true); + options.maxDegreeOfParallelism(-1); + options.maxItemCount(100); Observable> results = client.queryDocuments(getCollectionLink(), "SELECT * FROM r", options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(documentList.size()) - .exactlyContainsInAnyOrder(documentList.stream().map(Document::getResourceId).collect(Collectors.toList())).build(); + .exactlyContainsInAnyOrder(documentList.stream().map(Document::resourceId).collect(Collectors.toList())).build(); try { validateQuerySuccess(results, validator, QUERY_TIMEOUT); @@ -255,8 +254,8 @@ public void crossPartitionQuery() { // validates only the first query for fetching query plan goes to gateway. assertThat(client.getCapturedRequests().stream().filter(r -> r.getResourceType() == ResourceType.Document)).hasSize(1); } catch (Throwable error) { - if (clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -318,7 +317,7 @@ public void beforeClass() { RequestOptions options = new RequestOptions(); options.setOfferThroughput(10100); createdDatabase = SHARED_DATABASE; - createdCollection = createCollection(createdDatabase.getId(), getCollectionDefinition(), options); + createdCollection = createCollection(createdDatabase.id(), getCollectionDefinition(), options); client = SpyClientUnderTestFactory.createClientWithGatewaySpy(clientBuilder); assertThat(client.getCapturedRequests()).isNotEmpty(); @@ -336,12 +335,12 @@ public void beforeMethod(Method method) { } private String getCollectionLink() { - return String.format("/dbs/%s/colls/%s", createdDatabase.getId(), createdCollection.getId()); + return String.format("/dbs/%s/colls/%s", createdDatabase.id(), createdCollection.id()); } private Document getDocumentDefinition() { Document doc = new Document(); - doc.setId(UUID.randomUUID().toString()); + doc.id(UUID.randomUUID().toString()); doc.set(PARTITION_KEY_FIELD_NAME, UUID.randomUUID().toString()); doc.set("name", "Hafez"); return doc; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayAddressCacheTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java similarity index 94% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayAddressCacheTest.java rename to sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java index 9357869954706..b3962d3e10d72 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayAddressCacheTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java @@ -20,28 +20,28 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import com.microsoft.azure.cosmosdb.ConfigsBuilder; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; -import com.microsoft.azure.cosmosdb.rx.internal.HttpClientFactory; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientImpl; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +import com.azure.data.cosmos.ConfigsBuilder; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.HttpClientFactory; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RxDocumentClientImpl; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.TestSuiteBase; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import org.mockito.Matchers; @@ -84,23 +84,23 @@ public GatewayAddressCacheTest(Builder clientBuilder) { public Object[][] partitionsKeyRangeListAndCollectionLinkParams() { return new Object[][] { // target partition key range ids, collection link - { ImmutableList.of("0"), getNameBasedCollectionLink(), Protocol.Tcp }, - { ImmutableList.of("0"), getNameBasedCollectionLink(), Protocol.Https }, + { ImmutableList.of("0"), getNameBasedCollectionLink(), Protocol.TCP}, + { ImmutableList.of("0"), getNameBasedCollectionLink(), Protocol.HTTPS}, - { ImmutableList.of("1"), getNameBasedCollectionLink(), Protocol.Https }, - { ImmutableList.of("1"), getCollectionSelfLink(), Protocol.Https }, - { ImmutableList.of("3"), getNameBasedCollectionLink(), Protocol.Https }, + { ImmutableList.of("1"), getNameBasedCollectionLink(), Protocol.HTTPS}, + { ImmutableList.of("1"), getCollectionSelfLink(), Protocol.HTTPS}, + { ImmutableList.of("3"), getNameBasedCollectionLink(), Protocol.HTTPS}, - { ImmutableList.of("0", "1"), getNameBasedCollectionLink(), Protocol.Https }, - { ImmutableList.of("1", "3"), getNameBasedCollectionLink(), Protocol.Https }, + { ImmutableList.of("0", "1"), getNameBasedCollectionLink(), Protocol.HTTPS}, + { ImmutableList.of("1", "3"), getNameBasedCollectionLink(), Protocol.HTTPS}, }; } @DataProvider(name = "protocolProvider") public Object[][] protocolProvider() { return new Object[][]{ - { Protocol.Https }, - { Protocol.Tcp }, + { Protocol.HTTPS}, + { Protocol.TCP}, }; } @@ -125,7 +125,7 @@ public void getServerAddressesViaGateway(List partitionKeyRangeIds, getDocumentDefinition(), new HashMap<>()); Single> addresses = cache.getServerAddressesViaGatewayAsync( - req, createdCollection.getResourceId(), partitionKeyRangeIds, false); + req, createdCollection.resourceId(), partitionKeyRangeIds, false); PartitionReplicasAddressesValidator validator = new PartitionReplicasAddressesValidator.Builder() .withProtocol(protocol) @@ -168,12 +168,12 @@ public void getMasterAddressesViaGatewayAsync(Protocol protocol) throws Exceptio public Object[][] partitionsKeyRangeAndCollectionLinkParams() { return new Object[][] { // target partition key range ids, collection link, protocol - { "0", getNameBasedCollectionLink(), Protocol.Tcp }, - { "0", getNameBasedCollectionLink(), Protocol.Https }, + { "0", getNameBasedCollectionLink(), Protocol.TCP}, + { "0", getNameBasedCollectionLink(), Protocol.HTTPS}, - { "1", getNameBasedCollectionLink(), Protocol.Https} , - { "1", getCollectionSelfLink(), Protocol.Https }, - { "3", getNameBasedCollectionLink(), Protocol.Https }, + { "1", getNameBasedCollectionLink(), Protocol.HTTPS} , + { "1", getCollectionSelfLink(), Protocol.HTTPS}, + { "3", getNameBasedCollectionLink(), Protocol.HTTPS}, }; } @@ -194,7 +194,7 @@ public void tryGetAddresses_ForDataPartitions(String partitionKeyRangeId, String collectionLink, new Database(), new HashMap<>()); - String collectionRid = createdCollection.getResourceId(); + String collectionRid = createdCollection.resourceId(); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, partitionKeyRangeId); boolean forceRefreshPartitionAddresses = false; @@ -232,12 +232,12 @@ public void tryGetAddresses_ForDataPartitions_AddressCachedByOpenAsync_NoHttpReq IAuthorizationTokenProvider authorizationTokenProvider = (RxDocumentClientImpl) client; GatewayAddressCache cache = new GatewayAddressCache(serviceEndpoint, - Protocol.Https, + Protocol.HTTPS, authorizationTokenProvider, null, httpClientWrapper.getSpyHttpClient()); - String collectionRid = createdCollection.getResourceId(); + String collectionRid = createdCollection.resourceId(); List pkriList = allPartitionKeyRangeIds.stream().map( pkri -> new PartitionKeyRangeIdentity(collectionRid, pkri)).collect(Collectors.toList()); @@ -287,12 +287,12 @@ public void tryGetAddresses_ForDataPartitions_ForceRefresh( IAuthorizationTokenProvider authorizationTokenProvider = (RxDocumentClientImpl) client; GatewayAddressCache cache = new GatewayAddressCache(serviceEndpoint, - Protocol.Https, + Protocol.HTTPS, authorizationTokenProvider, null, httpClientWrapper.getSpyHttpClient()); - String collectionRid = createdCollection.getResourceId(); + String collectionRid = createdCollection.resourceId(); List pkriList = allPartitionKeyRangeIds.stream().map( pkri -> new PartitionKeyRangeIdentity(collectionRid, pkri)).collect(Collectors.toList()); @@ -343,13 +343,13 @@ public void tryGetAddresses_ForDataPartitions_Suboptimal_Refresh( int suboptimalRefreshTime = 2; GatewayAddressCache origCache = new GatewayAddressCache(serviceEndpoint, - Protocol.Https, + Protocol.HTTPS, authorizationTokenProvider, null, httpClientWrapper.getSpyHttpClient(), suboptimalRefreshTime); - String collectionRid = createdCollection.getResourceId(); + String collectionRid = createdCollection.resourceId(); List pkriList = allPartitionKeyRangeIds.stream().map( pkri -> new PartitionKeyRangeIdentity(collectionRid, pkri)).collect(Collectors.toList()); @@ -490,7 +490,7 @@ public void tryGetAddresses_ForMasterPartition_MasterPartitionAddressAlreadyCach GatewayAddressCache cache = new GatewayAddressCache(serviceEndpoint, - Protocol.Https, + Protocol.HTTPS, authorizationTokenProvider, null, clientWrapper.getSpyHttpClient(), @@ -537,7 +537,7 @@ public void tryGetAddresses_ForMasterPartition_ForceRefresh() throws Exception { IAuthorizationTokenProvider authorizationTokenProvider = (RxDocumentClientImpl) client; GatewayAddressCache cache = new GatewayAddressCache(serviceEndpoint, - Protocol.Https, + Protocol.HTTPS, authorizationTokenProvider, null, clientWrapper.getSpyHttpClient()); @@ -587,7 +587,7 @@ public void tryGetAddresses_SuboptimalMasterPartition_NotStaleEnough_NoRefresh() int refreshPeriodInSeconds = 10; GatewayAddressCache origCache = new GatewayAddressCache(serviceEndpoint, - Protocol.Https, + Protocol.HTTPS, authorizationTokenProvider, null, clientWrapper.getSpyHttpClient(), refreshPeriodInSeconds); @@ -677,7 +677,7 @@ public void tryGetAddresses_SuboptimalMasterPartition_Stale_DoRefresh() throws E int refreshPeriodInSeconds = 1; GatewayAddressCache origCache = new GatewayAddressCache(serviceEndpoint, - Protocol.Https, + Protocol.HTTPS, authorizationTokenProvider, null, clientWrapper.getSpyHttpClient(), refreshPeriodInSeconds); @@ -826,7 +826,7 @@ public void beforeClass() { RequestOptions options = new RequestOptions(); options.setOfferThroughput(30000); - createdCollection = createCollection(client, createdDatabase.getId(), getCollectionDefinition(), options); + createdCollection = createCollection(client, createdDatabase.id(), getCollectionDefinition(), options); } @AfterClass(groups = { "direct" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) @@ -839,10 +839,10 @@ static protected DocumentCollection getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId("mycol"); + collectionDefinition.id("mycol"); collectionDefinition.setPartitionKey(partitionKeyDef); return collectionDefinition; @@ -860,11 +860,11 @@ private HttpClientUnderTestWrapper getHttpClientUnderTestWrapper(Configs configs } public String getNameBasedCollectionLink() { - return "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(); } public String getCollectionSelfLink() { - return createdCollection.getSelfLink(); + return createdCollection.selfLink(); } private Document getDocumentDefinition() { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java similarity index 91% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java rename to sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java index 0f28160d1f3da..445edc273f271 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import static org.assertj.core.api.Assertions.assertThat; @@ -38,16 +38,16 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.DatabaseAccount; -import com.microsoft.azure.cosmosdb.internal.BaseAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; -import com.microsoft.azure.cosmosdb.rx.internal.SpyClientUnderTestFactory; -import com.microsoft.azure.cosmosdb.rx.internal.SpyClientUnderTestFactory.ClientUnderTest; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.DatabaseAccount; +import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.TestSuiteBase; +import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; +import com.azure.data.cosmos.internal.SpyClientUnderTestFactory.ClientUnderTest; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; @@ -92,7 +92,7 @@ public void setup() throws Exception { ClientUnderTest clientUnderTest = SpyClientUnderTestFactory.createClientUnderTest(this.clientBuilder); httpClient = clientUnderTest.getSpyHttpClient(); baseAuthorizationTokenProvider = new BaseAuthorizationTokenProvider(TestConfigurations.MASTER_KEY); - connectionPolicy = ConnectionPolicy.GetDefault(); + connectionPolicy = ConnectionPolicy.defaultPolicy(); mockGatewayServiceConfigurationReader = new GatewayServiceConfigurationReader(new URI(TestConfigurations.HOST), false, TestConfigurations.MASTER_KEY, connectionPolicy, baseAuthorizationTokenProvider, mockHttpClient); @@ -166,7 +166,7 @@ public static void validateSuccess(Single observable, DatabaseA testSubscriber.assertNoErrors(); testSubscriber.assertCompleted(); testSubscriber.assertValueCount(1); - assertThat(testSubscriber.getOnNextEvents().get(0).getId()).isEqualTo(expectedDatabaseAccount.getId()); + assertThat(testSubscriber.getOnNextEvents().get(0).id()).isEqualTo(expectedDatabaseAccount.id()); assertThat(testSubscriber.getOnNextEvents().get(0).getAddressesLink()) .isEqualTo(expectedDatabaseAccount.getAddressesLink()); assertThat(testSubscriber.getOnNextEvents().get(0).getWritableLocations().iterator().next().getEndpoint()) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionReplicasAddressesValidator.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionReplicasAddressesValidator.java similarity index 97% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionReplicasAddressesValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionReplicasAddressesValidator.java index fbd37eb5da7d0..0a3e2f4fd37c4 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/internal/directconnectivity/PartitionReplicasAddressesValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionReplicasAddressesValidator.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.internal.directconnectivity; +package com.azure.data.cosmos.directconnectivity; import java.util.ArrayList; import java.util.Collection; @@ -101,7 +101,7 @@ public void validate(Collection

addresses) { AddressValidator validator = new AddressValidator.Builder() .withPartitionKeyRangeId(partitionKeyRangeId) - .withRid(a.getResourceId()) + .withRid(a.resourceId()) .build(); for (Address address : addresses) { @@ -125,7 +125,7 @@ public void validate(Collection
addresses) { AddressValidator validator = new AddressValidator.Builder() .withPartitionKeyRangeId(a.getParitionKeyRangeId()) - .withRid(a.getResourceId()) + .withRid(a.resourceId()) .build(); for (Address address : addresses) { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConnectionPoolExhaustedRetryTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetryTest.java similarity index 94% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConnectionPoolExhaustedRetryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetryTest.java index 395a8a19d8055..0f42898f0b14e 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConnectionPoolExhaustedRetryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetryTest.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.RetryOptions; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.RetryOptions; import io.reactivex.netty.client.PoolExhaustedException; import org.mockito.Mockito; import org.testng.annotations.DataProvider; @@ -41,7 +41,7 @@ public class ConnectionPoolExhaustedRetryTest { public Object[][] exceptionProvider() { return new Object[][]{ {Mockito.mock(PoolExhaustedException.class)}, - {new DocumentClientException(-1, Mockito.mock(PoolExhaustedException.class))}, + {new CosmosClientException(-1, Mockito.mock(PoolExhaustedException.class))}, }; } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTests1.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java similarity index 79% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTests1.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java index 4d06338211b9d..61910b16193a3 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTests1.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java @@ -21,24 +21,23 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.PartitionKind; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.PartitionKind; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.rx.ResourceResponseValidator; +import com.azure.data.cosmos.rx.TestConfigurations; import org.testng.SkipException; import org.testng.annotations.Test; import rx.Observable; @@ -53,24 +52,24 @@ public class ConsistencyTests1 extends ConsistencyTestsBase { @Test(groups = {"direct"}, timeOut = CONSISTENCY_TEST_TIMEOUT) public void validateStrongConsistencyOnSyncReplication() throws Exception { - if (!TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.Strong.toString())) { + if (!TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.STRONG.toString())) { throw new SkipException("Endpoint does not have strong consistency"); } ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); this.writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Strong).build(); + .withConsistencyLevel(ConsistencyLevel.STRONG).build(); this.readClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Strong).build(); + .withConsistencyLevel(ConsistencyLevel.STRONG).build(); User userDefinition = getUserDefinition(); - userDefinition.setId(userDefinition.getId() + "validateStrongConsistencyOnSyncReplication"); - User user = safeCreateUser(this.initClient, createdDatabase.getId(), userDefinition); + userDefinition.id(userDefinition.id() + "validateStrongConsistencyOnSyncReplication"); + User user = safeCreateUser(this.initClient, createdDatabase.id(), userDefinition); validateStrongConsistency(user); } @@ -80,7 +79,7 @@ public void validateConsistentLSNForDirectTCPClient() { //TODO Need to test with TCP protocol // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355057 ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); this.writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) @@ -96,7 +95,7 @@ public void validateConsistentLSNForDirectTCPClient() { @Test(groups = {"direct"}, timeOut = CONSISTENCY_TEST_TIMEOUT) public void validateConsistentLSNForDirectHttpsClient() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); this.writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) @@ -114,7 +113,7 @@ public void validateConsistentLSNAndQuorumAckedLSNForDirectTCPClient() { //TODO Need to test with TCP protocol //https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355057 ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); this.writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) @@ -129,26 +128,26 @@ public void validateConsistentLSNAndQuorumAckedLSNForDirectTCPClient() { @Test(groups = {"direct"}, timeOut = CONSISTENCY_TEST_TIMEOUT) public void validateStrongDynamicQuorum() { - if (!TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.Strong.toString())) { + if (!TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.STRONG.toString())) { throw new SkipException("Endpoint does not have strong consistency"); } - validateReadQuorum(ConsistencyLevel.Strong, ResourceType.Document, false); + validateReadQuorum(ConsistencyLevel.STRONG, ResourceType.Document, false); } @Test(groups = {"direct"}, timeOut = CONSISTENCY_TEST_TIMEOUT) public void validateBoundedStalenessDynamicQuorumSyncReplication() { - if (!(TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.Strong.toString()) || TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.BoundedStaleness.toString()))) { + if (!(TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.STRONG.toString()) || TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.BOUNDED_STALENESS.toString()))) { throw new SkipException("Endpoint does not have strong consistency"); } - validateReadQuorum(ConsistencyLevel.BoundedStaleness, ResourceType.Document, true); + validateReadQuorum(ConsistencyLevel.BOUNDED_STALENESS, ResourceType.Document, true); } @Test(groups = {"direct"}, timeOut = CONSISTENCY_TEST_TIMEOUT) public void validateConsistentLSNAndQuorumAckedLSNForDirectHttpsClient() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); this.writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) @@ -175,54 +174,54 @@ public void validateStrongConsistencyOnAsyncReplicationDirect() throws Interrupt public void validateSessionContainerAfterCollectionCreateReplace() { //TODO Need to test with TCP protocol // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355057 - //validateSessionContainerAfterCollectionCreateReplace(false, Protocol.Tcp); + //validateSessionContainerAfterCollectionCreateReplace(false, Protocol.TCP); validateSessionContainerAfterCollectionCreateReplace(false); validateSessionContainerAfterCollectionCreateReplace(true); } @Test(groups = {"direct"}, timeOut = CONSISTENCY_TEST_TIMEOUT) public void validateConsistentPrefixOnSyncReplication() throws InterruptedException { - if (!(TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.Strong.toString()) || TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.BoundedStaleness.toString()))) { + if (!(TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.STRONG.toString()) || TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.BOUNDED_STALENESS.toString()))) { throw new SkipException("Endpoint does not have strong consistency"); } ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); this.writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.BoundedStaleness).build(); + .withConsistencyLevel(ConsistencyLevel.BOUNDED_STALENESS).build(); this.readClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.BoundedStaleness).build(); - User user = safeCreateUser(this.initClient, createdDatabase.getId(), getUserDefinition()); + .withConsistencyLevel(ConsistencyLevel.BOUNDED_STALENESS).build(); + User user = safeCreateUser(this.initClient, createdDatabase.id(), getUserDefinition()); boolean readLagging = validateConsistentPrefix(user); assertThat(readLagging).isFalse(); } @Test(groups = {"direct"}, timeOut = CONSISTENCY_TEST_TIMEOUT) public void validateConsistentPrefixOnAsyncReplication() throws InterruptedException { - if (!(TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.Strong.toString()) || TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.BoundedStaleness.toString()))) { + if (!(TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.STRONG.toString()) || TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.BOUNDED_STALENESS.toString()))) { throw new SkipException("Endpoint does not have strong consistency"); } ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); this.writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.BoundedStaleness) + .withConsistencyLevel(ConsistencyLevel.BOUNDED_STALENESS) .build(); this.readClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.BoundedStaleness) + .withConsistencyLevel(ConsistencyLevel.BOUNDED_STALENESS) .build(); Document documentDefinition = getDocumentDefinition(); - Document document = createDocument(this.initClient, createdDatabase.getId(), createdCollection.getId(), documentDefinition); + Document document = createDocument(this.initClient, createdDatabase.id(), createdCollection.id(), documentDefinition); boolean readLagging = validateConsistentPrefix(document); //assertThat(readLagging).isTrue(); //Will fail if batch repl is turned off } @@ -258,38 +257,38 @@ private void validateSubstatusCodeOnNotFoundExceptionInSessionReadAsync(boolean ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (useGateway) { - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); } else { - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); } AsyncDocumentClient client = new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); try { DocumentCollection documentCollection = new DocumentCollection(); - documentCollection.setId(UUID.randomUUID().toString()); + documentCollection.id(UUID.randomUUID().toString()); PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); - partitionKeyDefinition.setKind(PartitionKind.Hash); + partitionKeyDefinition.kind(PartitionKind.HASH); ArrayList paths = new ArrayList(); paths.add("/id"); - partitionKeyDefinition.setPaths(paths); + partitionKeyDefinition.paths(paths); documentCollection.setPartitionKey(partitionKeyDefinition); - DocumentCollection collection = client.createCollection(createdDatabase.getSelfLink(), documentCollection, null).toBlocking().first().getResource(); + DocumentCollection collection = client.createCollection(createdDatabase.selfLink(), documentCollection, null).toBlocking().first().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey("1")); Document documentDefinition = new Document(); - documentDefinition.setId("1"); - Document document = client.createDocument(collection.getSelfLink(), documentDefinition, requestOptions, false).toBlocking().first().getResource(); + documentDefinition.id("1"); + Document document = client.createDocument(collection.selfLink(), documentDefinition, requestOptions, false).toBlocking().first().getResource(); - Observable> deleteObservable = client.deleteDocument(document.getSelfLink(), requestOptions); + Observable> deleteObservable = client.deleteDocument(document.selfLink(), requestOptions); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .nullResource().build(); validateSuccess(deleteObservable, validator); - Observable> readObservable = client.readDocument(document.getSelfLink(), requestOptions); + Observable> readObservable = client.readDocument(document.selfLink(), requestOptions); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().unknownSubStatusCode().build(); validateFailure(readObservable, notFoundValidator); @@ -300,7 +299,7 @@ private void validateSubstatusCodeOnNotFoundExceptionInSessionReadAsync(boolean private static User getUserDefinition() { User user = new User(); - user.setId(USER_NAME); + user.id(USER_NAME); return user; } } \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTests2.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java similarity index 76% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTests2.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java index 0d61a14ed5286..80edae86fa7a8 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTests2.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java @@ -21,26 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.ISessionToken; -import com.microsoft.azure.cosmosdb.internal.SessionTokenHelper; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.WFConstants; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternal; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.rx.TestConfigurations; import org.apache.commons.lang3.Range; import org.testng.annotations.Test; import rx.Completable; @@ -58,18 +45,18 @@ public class ConsistencyTests2 extends ConsistencyTestsBase { @Test(groups = {"direct"}, timeOut = CONSISTENCY_TEST_TIMEOUT) public void validateReadSessionOnAsyncReplication() throws InterruptedException { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); this.writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session).build(); + .withConsistencyLevel(ConsistencyLevel.SESSION).build(); this.readClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session).build(); + .withConsistencyLevel(ConsistencyLevel.SESSION).build(); - Document document = this.initClient.createDocument(createdCollection.getSelfLink(), getDocumentDefinition(), null, false).toBlocking().first().getResource(); + Document document = this.initClient.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, false).toBlocking().first().getResource(); Thread.sleep(5000);//WaitForServerReplication boolean readLagging = this.validateReadSession(document); //assertThat(readLagging).isTrue(); //Will fail if batch repl is turned off @@ -78,18 +65,18 @@ public void validateReadSessionOnAsyncReplication() throws InterruptedException @Test(groups = {"direct"}, timeOut = CONSISTENCY_TEST_TIMEOUT) public void validateWriteSessionOnAsyncReplication() throws InterruptedException { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); this.writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session).build(); + .withConsistencyLevel(ConsistencyLevel.SESSION).build(); this.readClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session).build(); + .withConsistencyLevel(ConsistencyLevel.SESSION).build(); - Document document = this.initClient.createDocument(createdCollection.getSelfLink(), getDocumentDefinition(), null, false).toBlocking().first().getResource(); + Document document = this.initClient.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, false).toBlocking().first().getResource(); Thread.sleep(5000);//WaitForServerReplication boolean readLagging = this.validateWriteSession(document); //assertThat(readLagging).isTrue(); //Will fail if batch repl is turned off @@ -114,7 +101,7 @@ public void validateSessionContainerAfterCollectionDeletion() throws Exception { //TODO Need to test with TCP protocol // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355057 // Verify the collection deletion will trigger the session token clean up (even for different client) - //this.ValidateSessionContainerAfterCollectionDeletion(true, Protocol.Tcp); + //this.ValidateSessionContainerAfterCollectionDeletion(true, Protocol.TCP); this.validateSessionContainerAfterCollectionDeletion(true); this.validateSessionContainerAfterCollectionDeletion(false); } @@ -128,7 +115,7 @@ public void validateReadDistributionForSessionReads() { public void validateSessionTokenWithPreConditionFailure() throws Exception { //TODO Need to test with TCP protocol // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355057 - //this.validateSessionTokenWithPreConditionFailure(false, Protocol.Tcp); + //this.validateSessionTokenWithPreConditionFailure(false, Protocol.TCP); this.validateSessionTokenWithPreConditionFailure(false); this.validateSessionTokenWithPreConditionFailure(true); } @@ -137,7 +124,7 @@ public void validateSessionTokenWithPreConditionFailure() throws Exception { public void validateSessionTokenWithDocumentNotFound() throws Exception { //TODO Need to test with TCP protocol // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355057 - //this.validateSessionTokenWithDocumentNotFoundException(false, Protocol.Tcp); + //this.validateSessionTokenWithDocumentNotFoundException(false, Protocol.TCP); this.validateSessionTokenWithDocumentNotFoundException(false); this.validateSessionTokenWithDocumentNotFoundException(true); } @@ -146,7 +133,7 @@ public void validateSessionTokenWithDocumentNotFound() throws Exception { public void validateSessionTokenWithExpectedException() throws Exception { //TODO Need to test with TCP protocol // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355057 - //this.validateSessionTokenWithExpectedException(false, Protocol.Tcp); + //this.validateSessionTokenWithExpectedException(false, Protocol.TCP); this.validateSessionTokenWithExpectedException(false); this.validateSessionTokenWithExpectedException(true); } @@ -155,7 +142,7 @@ public void validateSessionTokenWithExpectedException() throws Exception { public void validateSessionTokenWithConflictException() { //TODO Need to test with TCP protocol // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355057 - //this.validateSessionTokenWithConflictException(false, Protocol.Tcp); + //this.validateSessionTokenWithConflictException(false, Protocol.TCP); this.validateSessionTokenWithConflictException(false); this.validateSessionTokenWithConflictException(true); } @@ -164,7 +151,7 @@ public void validateSessionTokenWithConflictException() { public void validateSessionTokenMultiPartitionCollection() throws Exception { //TODO Need to test with TCP protocol // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355057 - //this.validateSessionTokenMultiPartitionCollection(false, Protocol.Tcp); + //this.validateSessionTokenMultiPartitionCollection(false, Protocol.TCP); this.validateSessionTokenMultiPartitionCollection(false); this.validateSessionTokenMultiPartitionCollection(true); } @@ -173,7 +160,7 @@ public void validateSessionTokenMultiPartitionCollection() throws Exception { public void validateSessionTokenFromCollectionReplaceIsServerToken() { //TODO Need to test with TCP protocol // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355057 - //this.validateSessionTokenFromCollectionReplaceIsServerToken(false, Protocol.Tcp); + //this.validateSessionTokenFromCollectionReplaceIsServerToken(false, Protocol.TCP); this.validateSessionTokenFromCollectionReplaceIsServerToken(false); this.validateSessionTokenFromCollectionReplaceIsServerToken(true); } @@ -182,37 +169,37 @@ public void validateSessionTokenFromCollectionReplaceIsServerToken() { //https://msdata.visualstudio.com/CosmosDB/_workitems/edit/358715 @Test(groups = {"direct"}, enabled = false, timeOut = CONSISTENCY_TEST_TIMEOUT) public void validateNoChargeOnFailedSessionRead() throws Exception { - // Direct clients for read and write operations + // DIRECT clients for read and write operations ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); RxDocumentClientImpl writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); // Client locked to replica for pause/resume RxDocumentClientImpl readSecondaryClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); try { - // Create collection - DocumentCollection parentResource = writeClient.createCollection(createdDatabase.getSelfLink(), getCollectionDefinition(), null).toBlocking().first().getResource(); + // CREATE collection + DocumentCollection parentResource = writeClient.createCollection(createdDatabase.selfLink(), getCollectionDefinition(), null).toBlocking().first().getResource(); // Document to lock pause/resume clients Document documentDefinition = getDocumentDefinition(); - documentDefinition.setId("test" + documentDefinition.getId()); - ResourceResponse childResource = writeClient.createDocument(parentResource.getSelfLink(), documentDefinition, null, true).toBlocking().first(); - logger.info("Created {} child resource", childResource.getResource().getResourceId()); + documentDefinition.id("test" + documentDefinition.id()); + ResourceResponse childResource = writeClient.createDocument(parentResource.selfLink(), documentDefinition, null, true).toBlocking().first(); + logger.info("Created {} child resource", childResource.getResource().resourceId()); String token = childResource.getSessionToken().split(":")[0] + ":" + this.createSessionToken(SessionTokenHelper.parse(childResource.getSessionToken()), 100000000).convertToString(); FeedOptions feedOptions = new FeedOptions(); - feedOptions.setPartitionKey(new PartitionKey(PartitionKeyInternal.Empty.toJson())); - feedOptions.setSessionToken(token); + feedOptions.partitionKey(new PartitionKey(PartitionKeyInternal.Empty.toJson())); + feedOptions.sessionToken(token); FailureValidator validator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.NOTFOUND).subStatusCode(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE).build(); - Observable> feedObservable = readSecondaryClient.readDocuments(parentResource.getSelfLink(), feedOptions); + Observable> feedObservable = readSecondaryClient.readDocuments(parentResource.selfLink(), feedOptions); validateQueryFailure(feedObservable, validator); } finally { safeClose(writeClient); @@ -227,7 +214,7 @@ public void validateStrongReadOnOldDocument() { // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/355053 } - // TODO: DANOBLE: Investigate Direct TCP performance issue + // TODO: DANOBLE: Investigate DIRECT TCP performance issue // Note that we need multiple CONSISTENCY_TEST_TIMEOUT // SEE: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 @@ -243,15 +230,15 @@ public void validateSessionTokenAsync() { } ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); RxDocumentClientImpl client = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); try { - Document lastDocument = client.createDocument(createdCollection.getSelfLink(), getDocumentDefinition(), null, true) + Document lastDocument = client.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, true) .toBlocking() .first() .getResource(); @@ -259,7 +246,7 @@ public void validateSessionTokenAsync() { Completable task1 = ParallelAsync.forEachAsync(Range.between(0, 1000), 5, new Action1() { @Override public void call(Integer index) { - client.createDocument(createdCollection.getSelfLink(), documents.get(index % documents.size()), null, true).toBlocking().first(); + client.createDocument(createdCollection.selfLink(), documents.get(index % documents.size()), null, true).toBlocking().first(); } }); @@ -268,26 +255,26 @@ public void call(Integer index) { public void call(Integer index) { try { FeedOptions feedOptions = new FeedOptions(); - feedOptions.setEnableCrossPartitionQuery(true); - FeedResponse queryResponse = client.queryDocuments(createdCollection.getSelfLink(), "SELECT * FROM c WHERE c.Id = 'foo'", feedOptions).toBlocking().first(); - String lsnHeaderValue = queryResponse.getResponseHeaders().get(WFConstants.BackendHeaders.LSN); + feedOptions.enableCrossPartitionQuery(true); + FeedResponse queryResponse = client.queryDocuments(createdCollection.selfLink(), "SELECT * FROM c WHERE c.Id = 'foo'", feedOptions).toBlocking().first(); + String lsnHeaderValue = queryResponse.responseHeaders().get(WFConstants.BackendHeaders.LSN); long lsn = Long.valueOf(lsnHeaderValue); - String sessionTokenHeaderValue = queryResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); + String sessionTokenHeaderValue = queryResponse.responseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); ISessionToken sessionToken = SessionTokenHelper.parse(sessionTokenHeaderValue); - logger.info("Session Token = {}, LSN = {}", sessionToken.convertToString(), lsn); + logger.info("SESSION Token = {}, LSN = {}", sessionToken.convertToString(), lsn); assertThat(lsn).isEqualTo(sessionToken.getLSN()); } catch (Exception ex) { - DocumentClientException clientException = (DocumentClientException) ex.getCause(); - if (clientException.getStatusCode() != 0) { - if (clientException.getStatusCode() == HttpConstants.StatusCodes.REQUEST_TIMEOUT) { + CosmosClientException clientException = (CosmosClientException) ex.getCause(); + if (clientException.statusCode() != 0) { + if (clientException.statusCode() == HttpConstants.StatusCodes.REQUEST_TIMEOUT) { // ignore - } else if (clientException.getStatusCode() == HttpConstants.StatusCodes.NOTFOUND) { - String lsnHeaderValue = clientException.getResponseHeaders().get(WFConstants.BackendHeaders.LSN); + } else if (clientException.statusCode() == HttpConstants.StatusCodes.NOTFOUND) { + String lsnHeaderValue = clientException.responseHeaders().get(WFConstants.BackendHeaders.LSN); long lsn = Long.valueOf(lsnHeaderValue); - String sessionTokenHeaderValue = clientException.getResponseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); + String sessionTokenHeaderValue = clientException.responseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); ISessionToken sessionToken = SessionTokenHelper.parse(sessionTokenHeaderValue); - logger.info("Session Token = {}, LSN = {}", sessionToken.convertToString(), lsn); + logger.info("SESSION Token = {}, LSN = {}", sessionToken.convertToString(), lsn); assertThat(lsn).isEqualTo(sessionToken.getLSN()); } else { throw ex; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java similarity index 78% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java index fd02c4a8989c2..9433155abbf6b 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ConsistencyTestsBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java @@ -22,37 +22,31 @@ */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.microsoft.azure.cosmosdb.AccessCondition; -import com.microsoft.azure.cosmosdb.AccessConditionType; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.PartitionKind; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.ISessionToken; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.SessionContainer; -import com.microsoft.azure.cosmosdb.internal.SessionTokenHelper; -import com.microsoft.azure.cosmosdb.internal.VectorSessionToken; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.WFConstants; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternalHelper; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.AccessCondition; +import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.PartitionKind; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; +import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.rx.ResourceResponseValidator; +import com.azure.data.cosmos.rx.TestConfigurations; import org.apache.commons.collections4.map.UnmodifiableMap; import org.apache.commons.lang3.StringUtils; import org.testng.SkipException; @@ -90,20 +84,20 @@ void validateStrongConsistency(Resource resourceToWorkWith) throws Exception { Resource writeResource = resourceToWorkWith; while (numberOfTestIteration-- > 0) //Write from a client and do point read through second client and ensure TS matches. { - OffsetDateTime sourceTimestamp = writeResource.getTimestamp(); + OffsetDateTime sourceTimestamp = writeResource.timestamp(); Thread.sleep(1000); //Timestamp is in granularity of seconds. Resource updatedResource = null; if (resourceToWorkWith instanceof User) { - updatedResource = this.writeClient.upsertUser(createdDatabase.getSelfLink(), (User) writeResource, null).toBlocking().first().getResource(); + updatedResource = this.writeClient.upsertUser(createdDatabase.selfLink(), (User) writeResource, null).toBlocking().first().getResource(); } else if (resourceToWorkWith instanceof Document) { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(resourceToWorkWith.get("mypk"))); - updatedResource = this.writeClient.upsertDocument(createdCollection.getSelfLink(), (Document) writeResource, options, false).toBlocking().first().getResource(); + updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), (Document) writeResource, options, false).toBlocking().first().getResource(); } - assertThat(updatedResource.getTimestamp().isAfter(sourceTimestamp)).isTrue(); + assertThat(updatedResource.timestamp().isAfter(sourceTimestamp)).isTrue(); - User readResource = this.readClient.readUser(resourceToWorkWith.getSelfLink(), null).toBlocking().first().getResource(); - assertThat(updatedResource.getTimestamp().equals(readResource.getTimestamp())); + User readResource = this.readClient.readUser(resourceToWorkWith.selfLink(), null).toBlocking().first().getResource(); + assertThat(updatedResource.timestamp().equals(readResource.timestamp())); } } @@ -111,14 +105,14 @@ void validateConsistentLSN() { Document documentDefinition = getDocumentDefinition(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentDefinition.get("mypk"))); - Document document = createDocument(this.writeClient, createdDatabase.getId(), createdCollection.getId(), documentDefinition); - ResourceResponse response = this.writeClient.deleteDocument(document.getSelfLink(), options).toBlocking().single(); + Document document = createDocument(this.writeClient, createdDatabase.id(), createdCollection.id(), documentDefinition); + ResourceResponse response = this.writeClient.deleteDocument(document.selfLink(), options).toBlocking().single(); assertThat(response.getStatusCode()).isEqualTo(204); long quorumAckedLSN = Long.parseLong((String) response.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); assertThat(quorumAckedLSN > 0).isTrue(); FailureValidator validator = new FailureValidator.Builder().statusCode(404).lsnGreaterThan(quorumAckedLSN).build(); - Observable> readObservable = this.readClient.readDocument(document.getSelfLink(), options); + Observable> readObservable = this.readClient.readDocument(document.selfLink(), options); validateFailure(readObservable, validator); } @@ -126,15 +120,15 @@ void validateConsistentLSNAndQuorumAckedLSN() { Document documentDefinition = getDocumentDefinition(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentDefinition.get("mypk"))); - Document document = createDocument(this.writeClient, createdDatabase.getId(), createdCollection.getId(), documentDefinition); - ResourceResponse response = this.writeClient.deleteDocument(document.getSelfLink(), options).toBlocking().single(); + Document document = createDocument(this.writeClient, createdDatabase.id(), createdCollection.id(), documentDefinition); + ResourceResponse response = this.writeClient.deleteDocument(document.selfLink(), options).toBlocking().single(); assertThat(response.getStatusCode()).isEqualTo(204); long quorumAckedLSN = Long.parseLong((String) response.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); assertThat(quorumAckedLSN > 0).isTrue(); FailureValidator validator = new FailureValidator.Builder().statusCode(404).lsnGreaterThanEqualsTo(quorumAckedLSN).exceptionQuorumAckedLSNInNotNull().build(); - Observable> readObservable = this.readClient.deleteDocument(document.getSelfLink(), options); + Observable> readObservable = this.readClient.deleteDocument(document.selfLink(), options); validateFailure(readObservable, validator); } @@ -146,27 +140,27 @@ void validateReadQuorum(ConsistencyLevel consistencyLevel, ResourceType childRes } void validateStrongConsistencyOnAsyncReplication(boolean useGateway) throws InterruptedException { - if (!TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.Strong.toString())) { + if (!TestConfigurations.CONSISTENCY.equalsIgnoreCase(ConsistencyLevel.STRONG.toString())) { throw new SkipException("Endpoint does not have strong consistency"); } ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (useGateway) { - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); } this.writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Strong).build(); + .withConsistencyLevel(ConsistencyLevel.STRONG).build(); this.readClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Strong).build(); + .withConsistencyLevel(ConsistencyLevel.STRONG).build(); Document documentDefinition = getDocumentDefinition(); - Document document = createDocument(this.writeClient, createdDatabase.getId(), createdCollection.getId(), documentDefinition); + Document document = createDocument(this.writeClient, createdDatabase.id(), createdCollection.id(), documentDefinition); validateStrongConsistency(document); } @@ -174,72 +168,72 @@ void validateStrongConsistency(Document documentToWorkWith) throws InterruptedEx int numberOfTestIteration = 5; Document writeDocument = documentToWorkWith; while (numberOfTestIteration-- > 0) { - OffsetDateTime sourceTimestamp = writeDocument.getTimestamp(); + OffsetDateTime sourceTimestamp = writeDocument.timestamp(); Thread.sleep(1000);//Timestamp is in granularity of seconds. RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentToWorkWith.get("mypk"))); Document updatedDocument = this.writeClient.replaceDocument(writeDocument, options).toBlocking().first().getResource(); - assertThat(updatedDocument.getTimestamp().isAfter(sourceTimestamp)).isTrue(); + assertThat(updatedDocument.timestamp().isAfter(sourceTimestamp)).isTrue(); - Document readDocument = this.readClient.readDocument(documentToWorkWith.getSelfLink(), options).toBlocking().first().getResource(); - assertThat(updatedDocument.getTimestamp().equals(readDocument.getTimestamp())); + Document readDocument = this.readClient.readDocument(documentToWorkWith.selfLink(), options).toBlocking().first().getResource(); + assertThat(updatedDocument.timestamp().equals(readDocument.timestamp())); } } void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { - // Direct clients for read and write operations + // DIRECT clients for read and write operations ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (useGateway) { - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); } else { - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); } RxDocumentClientImpl writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session).build(); + .withConsistencyLevel(ConsistencyLevel.SESSION).build(); try { PartitionKeyDefinition partitionKey = new PartitionKeyDefinition(); - partitionKey.setPaths(Arrays.asList("/customerid")); - partitionKey.setKind(PartitionKind.Hash); + partitionKey.paths(Arrays.asList("/customerid")); + partitionKey.kind(PartitionKind.HASH); DocumentCollection coll = null; { // self link - ResourceResponse collection = writeClient.createCollection(createdDatabase.getSelfLink(), getCollectionDefinition(), null).toBlocking().first(); - String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(collection.getResource().getSelfLink()); + ResourceResponse collection = writeClient.createCollection(createdDatabase.selfLink(), getCollectionDefinition(), null).toBlocking().first(); + String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(collection.getResource().selfLink()); String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(BridgeInternal.getAltLink(collection.getResource())); System.out.println("BridgeInternal.getAltLink(collection.getResource()) " + BridgeInternal.getAltLink(collection.getResource())); assertThat(collection.getSessionToken()).isEqualTo(globalSessionToken1); assertThat(collection.getSessionToken()).isEqualTo(globalSessionToken2); coll = collection.getResource(); - ResourceResponse collectionRead = writeClient.readCollection(coll.getSelfLink(), null).toBlocking().first(); + ResourceResponse collectionRead = writeClient.readCollection(coll.selfLink(), null).toBlocking().first(); // timesync might bump the version, comment out the check - //assertThat(collection.getSessionToken()).isEqualTo(collectionRead.getSessionToken()); + //assertThat(collection.sessionToken()).isEqualTo(collectionRead.sessionToken()); } { // name link ResourceResponse collection = writeClient.createCollection(BridgeInternal.getAltLink(createdDatabase), getCollectionDefinition(), null).toBlocking().first(); - String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(collection.getResource().getSelfLink()); + String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(collection.getResource().selfLink()); String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(BridgeInternal.getAltLink(collection.getResource())); assertThat(collection.getSessionToken()).isEqualTo(globalSessionToken1); - //assertThat(collection.getSessionToken()).isEqualTo(globalSessionToken2); + //assertThat(collection.sessionToken()).isEqualTo(globalSessionToken2); ResourceResponse collectionRead = writeClient.readCollection(BridgeInternal.getAltLink(collection.getResource()), null).toBlocking().first(); // timesync might bump the version, comment out the check - //assertThat(collection.getSessionToken()).isEqualTo(collectionRead.getSessionToken()); + //assertThat(collection.sessionToken()).isEqualTo(collectionRead.sessionToken()); } { Document document2 = new Document(); - document2.setId("test" + UUID.randomUUID().toString()); + document2.id("test" + UUID.randomUUID().toString()); document2.set("customerid", 2); // name link ResourceResponse document = writeClient.createDocument(BridgeInternal.getAltLink(coll), document2, null, false).toBlocking().first(); - String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(coll.getSelfLink()); + String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(coll.selfLink()); String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(BridgeInternal.getAltLink(coll)); assertThat(globalSessionToken1.indexOf(document.getSessionToken())).isNotNegative(); @@ -247,11 +241,11 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { } { Document document2 = new Document(); - document2.setId("test" + UUID.randomUUID().toString()); + document2.id("test" + UUID.randomUUID().toString()); document2.set("customerid", 3); // name link ResourceResponse document = writeClient.createDocument(BridgeInternal.getAltLink(coll), document2, null, false).toBlocking().first(); - String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(coll.getSelfLink()); + String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(coll.selfLink()); String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(BridgeInternal.getAltLink(coll)); assertThat(globalSessionToken1.indexOf(document.getSessionToken())).isNotNegative(); @@ -264,33 +258,33 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { boolean validateConsistentPrefix(Resource resourceToWorkWith) throws InterruptedException { int numberOfTestIteration = 5; - OffsetDateTime lastReadDateTime = resourceToWorkWith.getTimestamp(); + OffsetDateTime lastReadDateTime = resourceToWorkWith.timestamp(); boolean readLagging = false; Resource writeResource = resourceToWorkWith; while (numberOfTestIteration-- > 0) { //Write from a client and do point read through second client and ensure TS monotonically increases. - OffsetDateTime sourceTimestamp = writeResource.getTimestamp(); + OffsetDateTime sourceTimestamp = writeResource.timestamp(); Thread.sleep(1000); //Timestamp is in granularity of seconds. Resource updatedResource = null; if (resourceToWorkWith instanceof User) { - updatedResource = this.writeClient.upsertUser(createdDatabase.getSelfLink(), (User) writeResource, null).toBlocking().first().getResource(); + updatedResource = this.writeClient.upsertUser(createdDatabase.selfLink(), (User) writeResource, null).toBlocking().first().getResource(); } else if (resourceToWorkWith instanceof Document) { - updatedResource = this.writeClient.upsertDocument(createdCollection.getSelfLink(), (Document) writeResource, null, false).toBlocking().first().getResource(); + updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), (Document) writeResource, null, false).toBlocking().first().getResource(); } - assertThat(updatedResource.getTimestamp().isAfter(sourceTimestamp)).isTrue(); + assertThat(updatedResource.timestamp().isAfter(sourceTimestamp)).isTrue(); writeResource = updatedResource; Resource readResource = null; if (resourceToWorkWith instanceof User) { - readResource = this.readClient.readUser(resourceToWorkWith.getSelfLink(), null).toBlocking().first().getResource(); + readResource = this.readClient.readUser(resourceToWorkWith.selfLink(), null).toBlocking().first().getResource(); } else if (resourceToWorkWith instanceof Document) { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(resourceToWorkWith.get("mypk"))); - readResource = this.readClient.readDocument(resourceToWorkWith.getSelfLink(), options).toBlocking().first().getResource(); + readResource = this.readClient.readDocument(resourceToWorkWith.selfLink(), options).toBlocking().first().getResource(); } - assertThat(readResource.getTimestamp().compareTo(lastReadDateTime) >= 0).isTrue(); - lastReadDateTime = readResource.getTimestamp(); - if (readResource.getTimestamp().isBefore(updatedResource.getTimestamp())) { + assertThat(readResource.timestamp().compareTo(lastReadDateTime) >= 0).isTrue(); + lastReadDateTime = readResource.timestamp(); + if (readResource.timestamp().isBefore(updatedResource.timestamp())) { readLagging = true; } } @@ -304,25 +298,25 @@ boolean validateReadSession(Resource resourceToWorkWith) throws InterruptedExcep Resource writeResource = resourceToWorkWith; while (numberOfTestIteration-- > 0) { - OffsetDateTime sourceTimestamp = writeResource.getTimestamp(); + OffsetDateTime sourceTimestamp = writeResource.timestamp(); Thread.sleep(1000); Resource updatedResource = null; if (resourceToWorkWith instanceof Document) { - updatedResource = this.writeClient.upsertDocument(createdCollection.getSelfLink(), writeResource, null, false).toBlocking().single().getResource(); + updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), writeResource, null, false).toBlocking().single().getResource(); } - assertThat(updatedResource.getTimestamp().isAfter(sourceTimestamp)).isTrue(); + assertThat(updatedResource.timestamp().isAfter(sourceTimestamp)).isTrue(); writeResource = updatedResource; Resource readResource = null; RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceToWorkWith.get("mypk"))); if (resourceToWorkWith instanceof Document) { - readResource = this.readClient.readDocument(resourceToWorkWith.getSelfLink(), requestOptions).toBlocking().first().getResource(); + readResource = this.readClient.readDocument(resourceToWorkWith.selfLink(), requestOptions).toBlocking().first().getResource(); } - assertThat(readResource.getTimestamp().compareTo(lastReadDateTime) >= 0).isTrue(); - lastReadDateTime = readResource.getTimestamp(); + assertThat(readResource.timestamp().compareTo(lastReadDateTime) >= 0).isTrue(); + lastReadDateTime = readResource.timestamp(); - if (readResource.getTimestamp().isBefore(updatedResource.getTimestamp())) { + if (readResource.timestamp().isBefore(updatedResource.timestamp())) { readLagging = true; } } @@ -336,34 +330,34 @@ boolean validateWriteSession(Resource resourceToWorkWith) throws InterruptedExce Resource writeResource = resourceToWorkWith; while (numberOfTestIteration-- > 0) { - OffsetDateTime sourceTimestamp = writeResource.getTimestamp(); + OffsetDateTime sourceTimestamp = writeResource.timestamp(); Thread.sleep(1000); Resource updatedResource = null; if (resourceToWorkWith instanceof Document) { - updatedResource = this.writeClient.upsertDocument(createdCollection.getSelfLink(), writeResource, null, false).toBlocking().single().getResource(); + updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), writeResource, null, false).toBlocking().single().getResource(); } - assertThat(updatedResource.getTimestamp().isAfter(sourceTimestamp)).isTrue(); + assertThat(updatedResource.timestamp().isAfter(sourceTimestamp)).isTrue(); writeResource = updatedResource; Resource readResource = null; RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceToWorkWith.get("mypk"))); if (resourceToWorkWith instanceof Document) { - readResource = this.readClient.readDocument(resourceToWorkWith.getSelfLink(), requestOptions).toBlocking().first().getResource(); + readResource = this.readClient.readDocument(resourceToWorkWith.selfLink(), requestOptions).toBlocking().first().getResource(); } - assertThat(readResource.getTimestamp().compareTo(lastReadDateTime) >= 0).isTrue(); - lastReadDateTime = readResource.getTimestamp(); + assertThat(readResource.timestamp().compareTo(lastReadDateTime) >= 0).isTrue(); + lastReadDateTime = readResource.timestamp(); - if (readResource.getTimestamp().isBefore(updatedResource.getTimestamp())) { + if (readResource.timestamp().isBefore(updatedResource.timestamp())) { readLagging = true; } //Now perform write on session and update our session token and lastReadTS Thread.sleep(1000); if (resourceToWorkWith instanceof Document) { - readResource = this.writeClient.upsertDocument(createdCollection.getSelfLink(), readResource, requestOptions, false).toBlocking().first().getResource(); //Now perform write on session + readResource = this.writeClient.upsertDocument(createdCollection.selfLink(), readResource, requestOptions, false).toBlocking().first().getResource(); //Now perform write on session } - assertThat(readResource.getTimestamp().isAfter(lastReadDateTime)); + assertThat(readResource.timestamp().isAfter(lastReadDateTime)); this.readClient.setSession(this.writeClient.getSession()); } @@ -373,86 +367,86 @@ boolean validateWriteSession(Resource resourceToWorkWith) throws InterruptedExce void validateSessionContainerAfterCollectionDeletion(boolean useGateway) throws Exception { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (useGateway) { - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); } else { - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); } RxDocumentClientImpl client1 = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); RxDocumentClientImpl client2 = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); String collectionId = UUID.randomUUID().toString(); try { DocumentCollection collectionDefinition = getCollectionDefinition(); - collectionDefinition.setId(collectionId); - DocumentCollection collection = createCollection(client2, createdDatabase.getId(), collectionDefinition, null); + collectionDefinition.id(collectionId); + DocumentCollection collection = createCollection(client2, createdDatabase.id(), collectionDefinition, null); ResourceResponseValidator successValidatorCollection = new ResourceResponseValidator.Builder() - .withId(collection.getId()) + .withId(collection.id()) .build(); - Observable> readObservableCollection = client2.readCollection(collection.getSelfLink(), null); + Observable> readObservableCollection = client2.readCollection(collection.selfLink(), null); validateSuccess(readObservableCollection, successValidatorCollection); for (int i = 0; i < 5; i++) { String documentId = "Generation1-" + i; Document documentDefinition = getDocumentDefinition(); - documentDefinition.setId(documentId); - Document documentCreated = client2.createDocument(collection.getSelfLink(), documentDefinition, null, true).toBlocking().first().getResource(); + documentDefinition.id(documentId); + Document documentCreated = client2.createDocument(collection.selfLink(), documentDefinition, null, true).toBlocking().first().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(documentCreated.get("mypk"))); client2.readDocument(BridgeInternal.getAltLink(documentCreated), requestOptions).toBlocking().first(); - client2.readDocument(documentCreated.getSelfLink(), requestOptions).toBlocking().first(); + client2.readDocument(documentCreated.selfLink(), requestOptions).toBlocking().first(); } { // just create the second for fun - DocumentCollection collection2 = createCollection(client2, createdDatabase.getId(), getCollectionDefinition(), null); + DocumentCollection collection2 = createCollection(client2, createdDatabase.id(), getCollectionDefinition(), null); successValidatorCollection = new ResourceResponseValidator.Builder() - .withId(collection2.getId()) + .withId(collection2.id()) .build(); - readObservableCollection = client2.readCollection(collection2.getSelfLink(), null); + readObservableCollection = client2.readCollection(collection2.selfLink(), null); validateSuccess(readObservableCollection, successValidatorCollection); } // verify the client2 has the same token. { String token1 = ((SessionContainer) client2.getSession()).getSessionToken(BridgeInternal.getAltLink(collection)); - String token2 = ((SessionContainer) client2.getSession()).getSessionToken(collection.getSelfLink()); + String token2 = ((SessionContainer) client2.getSession()).getSessionToken(collection.selfLink()); assertThat(token1).isEqualTo(token2); } // now delete collection use different client - client1.deleteCollection(collection.getSelfLink(), null).toBlocking().first(); + client1.deleteCollection(collection.selfLink(), null).toBlocking().first(); - DocumentCollection collectionRandom1 = createCollection(client2, createdDatabase.getId(), getCollectionDefinition()); + DocumentCollection collectionRandom1 = createCollection(client2, createdDatabase.id(), getCollectionDefinition()); DocumentCollection documentCollection = getCollectionDefinition(); - collectionDefinition.setId(collectionId); - DocumentCollection collectionSameName = createCollection(client2, createdDatabase.getId(), collectionDefinition); + collectionDefinition.id(collectionId); + DocumentCollection collectionSameName = createCollection(client2, createdDatabase.id(), collectionDefinition); String documentId1 = "Generation2-" + 0; Document databaseDefinition2 = getDocumentDefinition(); - databaseDefinition2.setId(documentId1); - Document createdDocument = client1.createDocument(collectionSameName.getSelfLink(), databaseDefinition2, null, true).toBlocking().first().getResource(); + databaseDefinition2.id(documentId1); + Document createdDocument = client1.createDocument(collectionSameName.selfLink(), databaseDefinition2, null, true).toBlocking().first().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(createdDocument.get("mypk"))); ResourceResponseValidator successValidator = new ResourceResponseValidator.Builder() - .withId(createdDocument.getId()) + .withId(createdDocument.id()) .build(); - Observable> readObservable = client1.readDocument(createdDocument.getSelfLink(), requestOptions); + Observable> readObservable = client1.readDocument(createdDocument.selfLink(), requestOptions); validateSuccess(readObservable, successValidator); { String token1 = ((SessionContainer) client1.getSession()).getSessionToken(BridgeInternal.getAltLink(collectionSameName)); - String token2 = ((SessionContainer) client1.getSession()).getSessionToken(collectionSameName.getSelfLink()); + String token2 = ((SessionContainer) client1.getSession()).getSessionToken(collectionSameName.selfLink()); assertThat(token1).isEqualTo(token2); } { // Client2 read using name link should fail with higher LSN. - String token = ((SessionContainer) client1.getSession()).getSessionToken(collectionSameName.getSelfLink()); + String token = ((SessionContainer) client1.getSession()).getSessionToken(collectionSameName.selfLink()); // artificially bump to higher LSN String higherLsnToken = this.getDifferentLSNToken(token, 2000); RequestOptions requestOptions1 = new RequestOptions(); @@ -466,7 +460,7 @@ void validateSessionContainerAfterCollectionDeletion(boolean useGateway) throws { // verify token by altlink is gone! String token1 = ((SessionContainer) client2.getSession()).getSessionToken(BridgeInternal.getAltLink(collectionSameName)); - String token2 = ((SessionContainer) client2.getSession()).getSessionToken(collection.getSelfLink()); + String token2 = ((SessionContainer) client2.getSession()).getSessionToken(collection.selfLink()); assertThat(token1).isEmpty(); //assertThat(token2).isNotEmpty(); In java both SelfLink and AltLink token remain in sync. } @@ -482,14 +476,14 @@ void validateSessionContainerAfterCollectionDeletion(boolean useGateway) throws RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentTest.get("mypk"))); successValidator = new ResourceResponseValidator.Builder() - .withId(documentTest.getId()) + .withId(documentTest.id()) .build(); - readObservable = client1.readDocument(documentTest.getSelfLink(), options); + readObservable = client1.readDocument(documentTest.selfLink(), options); validateSuccess(readObservable, successValidator); - client1.deleteCollection(collectionSameName.getSelfLink(), null).toBlocking().first(); + client1.deleteCollection(collectionSameName.selfLink(), null).toBlocking().first(); String token1 = ((SessionContainer) client2.getSession()).getSessionToken(BridgeInternal.getAltLink(collectionSameName)); - String token2 = ((SessionContainer) client2.getSession()).getSessionToken(collectionSameName.getSelfLink()); + String token2 = ((SessionContainer) client2.getSession()).getSessionToken(collectionSameName.selfLink()); // currently we can't delete the token from Altlink when deleting using selflink assertThat(token1).isNotEmpty(); //assertThat(token2).isEmpty(); In java both SelfLink and AltLink token remain in sync. @@ -504,19 +498,19 @@ void validateSessionContainerAfterCollectionDeletion(boolean useGateway) throws void validateSessionTokenWithPreConditionFailure(boolean useGateway) throws Exception { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (useGateway) { - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); } else { - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); } RxDocumentClientImpl writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); RxDocumentClientImpl validationClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); try { // write a document, and upsert to it to update etag. @@ -528,8 +522,8 @@ void validateSessionTokenWithPreConditionFailure(boolean useGateway) throws Exce // create a conditioned read request, with first write request's etag, so the read fails with PreconditionFailure AccessCondition ac = new AccessCondition(); - ac.setCondition(documentResponse.getResource().getETag()); - ac.setType(AccessConditionType.IfMatch); + ac.condition(documentResponse.getResource().etag()); + ac.type(AccessConditionType.IF_MATCH); RequestOptions requestOptions1 = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(documentResponse.getResource().get("mypk"))); requestOptions1.setAccessCondition(ac); @@ -548,23 +542,23 @@ void validateSessionTokenWithPreConditionFailure(boolean useGateway) throws Exce void validateSessionTokenWithDocumentNotFoundException(boolean useGateway) throws Exception { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (useGateway) { - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); } else { - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); } RxDocumentClientImpl writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); RxDocumentClientImpl validationClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); try { DocumentCollection collectionDefinition = getCollectionDefinition(); - collectionDefinition.setId("TestCollection"); + collectionDefinition.id("TestCollection"); ResourceResponse documentResponse = writeClient.createDocument(BridgeInternal.getAltLink(createdCollection), getDocumentDefinition(), null, true).toBlocking().first(); @@ -584,14 +578,14 @@ void validateSessionTokenWithDocumentNotFoundException(boolean useGateway) throw void validateSessionTokenWithExpectedException(boolean useGateway) throws Exception { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (useGateway) { - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); } else { - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); } RxDocumentClientImpl writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); try { ResourceResponse documentResponse = @@ -617,19 +611,19 @@ void validateSessionTokenWithExpectedException(boolean useGateway) throws Except void validateSessionTokenWithConflictException(boolean useGateway) { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (useGateway) { - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); } else { - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); } RxDocumentClientImpl writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); RxDocumentClientImpl validationClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); try { Document documentDefinition = getDocumentDefinition(); @@ -650,14 +644,14 @@ void validateSessionTokenWithConflictException(boolean useGateway) { void validateSessionTokenMultiPartitionCollection(boolean useGateway) throws Exception { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (useGateway) { - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); } else { - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); } RxDocumentClientImpl writeClient = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); try { @@ -665,27 +659,27 @@ void validateSessionTokenMultiPartitionCollection(boolean useGateway) throws Exc PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, true, false); IRoutingMapProvider routingMapProvider = writeClient.getPartitionKeyRangeCache(); - // assertThat(routingMapProvider.tryGetOverlappingRangesAsync(collection.getResourceId(), fullRange, false).toBlocking().value().size()).isEqualTo(5); + // assertThat(routingMapProvider.tryGetOverlappingRangesAsync(collection.resourceId(), fullRange, false).toBlocking().value().size()).isEqualTo(5); // Document to lock pause/resume clients Document document1 = new Document(); - document1.setId("test" + UUID.randomUUID().toString()); + document1.id("test" + UUID.randomUUID().toString()); document1.set("mypk", 1); - ResourceResponse childResource1 = writeClient.createDocument(createdCollection.getSelfLink(), document1, null, true).toBlocking().first(); - logger.info("Created {} child resource", childResource1.getResource().getResourceId()); + ResourceResponse childResource1 = writeClient.createDocument(createdCollection.selfLink(), document1, null, true).toBlocking().first(); + logger.info("Created {} child resource", childResource1.getResource().resourceId()); assertThat(childResource1.getSessionToken()).isNotNull(); assertThat(childResource1.getSessionToken().contains(":")).isTrue(); - String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(createdCollection.getSelfLink()); + String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(createdCollection.selfLink()); assertThat(globalSessionToken1.contains(childResource1.getSessionToken())); // Document to lock pause/resume clients Document document2 = new Document(); - document2.setId("test" + UUID.randomUUID().toString()); + document2.id("test" + UUID.randomUUID().toString()); document2.set("mypk", 2); - ResourceResponse childResource2 = writeClient.createDocument(createdCollection.getSelfLink(), document2, null, true).toBlocking().first(); + ResourceResponse childResource2 = writeClient.createDocument(createdCollection.selfLink(), document2, null, true).toBlocking().first(); assertThat(childResource2.getSessionToken()).isNotNull(); assertThat(childResource2.getSessionToken().contains(":")).isTrue(); - String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(createdCollection.getSelfLink()); + String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(createdCollection.selfLink()); logger.info("globalsessiontoken2 {}, childtoken1 {}, childtoken2 {}", globalSessionToken2, childResource1.getSessionToken(), childResource2.getSessionToken()); assertThat(globalSessionToken2.contains(childResource2.getSessionToken())).isTrue(); @@ -696,31 +690,31 @@ void validateSessionTokenMultiPartitionCollection(boolean useGateway) throws Exc RequestOptions option = new RequestOptions(); option.setSessionToken(sessionToken); option.setPartitionKey(new PartitionKey(2)); - writeClient.readDocument(childResource2.getResource().getSelfLink(), option).toBlocking().first(); + writeClient.readDocument(childResource2.getResource().selfLink(), option).toBlocking().first(); option = new RequestOptions(); option.setSessionToken(StringUtils.EMPTY); option.setPartitionKey(new PartitionKey(1)); - writeClient.readDocument(childResource1.getResource().getSelfLink(), option).toBlocking().first(); + writeClient.readDocument(childResource1.getResource().selfLink(), option).toBlocking().first(); option = new RequestOptions(); option.setSessionToken(sessionToken); option.setPartitionKey(new PartitionKey(1)); - Observable> readObservable = writeClient.readDocument(childResource1.getResource().getSelfLink(), option); + Observable> readObservable = writeClient.readDocument(childResource1.getResource().selfLink(), option); FailureValidator failureValidator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.NOTFOUND).subStatusCode(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE).build(); validateFailure(readObservable, failureValidator); - readObservable = writeClient.readDocument(childResource2.getResource().getSelfLink(), option); + readObservable = writeClient.readDocument(childResource2.getResource().selfLink(), option); failureValidator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.NOTFOUND).subStatusCode(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE).build(); validateFailure(readObservable, failureValidator); - assertThat(((SessionContainer) writeClient.getSession()).getSessionToken(createdCollection.getSelfLink())).isEqualTo + assertThat(((SessionContainer) writeClient.getSession()).getSessionToken(createdCollection.selfLink())).isEqualTo (((SessionContainer) writeClient.getSession()).getSessionToken(BridgeInternal.getAltLink(createdCollection))); assertThat(((SessionContainer) writeClient.getSession()).getSessionToken("asdfasdf")).isEmpty(); - assertThat(((SessionContainer) writeClient.getSession()).getSessionToken(createdDatabase.getSelfLink())).isEmpty(); + assertThat(((SessionContainer) writeClient.getSession()).getSessionToken(createdDatabase.selfLink())).isEmpty(); } finally { safeClose(writeClient); } @@ -729,30 +723,30 @@ void validateSessionTokenMultiPartitionCollection(boolean useGateway) throws Exc void validateSessionTokenFromCollectionReplaceIsServerToken(boolean useGateway) { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); if (useGateway) { - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); } else { - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); } RxDocumentClientImpl client1 = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); RxDocumentClientImpl client2 = null; try { - Document doc = client1.createDocument(createdCollection.getSelfLink(), getDocumentDefinition(), null, true).toBlocking().first().getResource(); + Document doc = client1.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, true).toBlocking().first().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(doc.get("mypk"))); Document doc1 = client1.readDocument(BridgeInternal.getAltLink(doc), requestOptions).toBlocking().first().getResource(); - String token1 = ((SessionContainer) client1.getSession()).getSessionToken(createdCollection.getSelfLink()); + String token1 = ((SessionContainer) client1.getSession()).getSessionToken(createdCollection.selfLink()); client2 = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); client2.replaceCollection(createdCollection, null).toBlocking().first(); - String token2 = ((SessionContainer) client2.getSession()).getSessionToken(createdCollection.getSelfLink()); + String token2 = ((SessionContainer) client2.getSession()).getSessionToken(createdCollection.selfLink()); logger.info("Token after document and after collection replace {} = {}", token1, token2); } finally { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentQuerySpyWireContentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java similarity index 82% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentQuerySpyWireContentTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java index 0e623bda8e3ff..869c24c02f64d 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/DocumentQuerySpyWireContentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java @@ -20,12 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -36,19 +35,16 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; -import com.microsoft.azure.cosmosdb.rx.SpyClientBuilder; -import com.microsoft.azure.cosmosdb.rx.Utils; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.SpyClientBuilder; +import com.azure.data.cosmos.rx.Utils; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; @@ -65,11 +61,11 @@ public class DocumentQuerySpyWireContentTest extends TestSuiteBase { private SpyClientUnderTestFactory.ClientUnderTest client; public String getSinglePartitionCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdSinglePartitionCollection.getId()); + return Utils.getCollectionNameLink(createdDatabase.id(), createdSinglePartitionCollection.id()); } public String getMultiPartitionCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdMultiPartitionCollection.getId()); + return Utils.getCollectionNameLink(createdDatabase.id(), createdMultiPartitionCollection.id()); } @Factory(dataProvider = "clientBuilders") @@ -81,28 +77,28 @@ public DocumentQuerySpyWireContentTest(Builder clientBuilder) { public static Object[][] responseContinuationTokenLimitParamProvider() { FeedOptions options1 = new FeedOptions(); - options1.setMaxItemCount(1); - options1.setResponseContinuationTokenLimitInKb(5); - options1.setPartitionKey(new PartitionKey("99")); + options1.maxItemCount(1); + options1.responseContinuationTokenLimitInKb(5); + options1.partitionKey(new PartitionKey("99")); String query1 = "Select * from r"; boolean multiPartitionCollection1 = true; FeedOptions options2 = new FeedOptions(); - options2.setMaxItemCount(1); - options2.setResponseContinuationTokenLimitInKb(5); - options2.setPartitionKey(new PartitionKey("99")); + options2.maxItemCount(1); + options2.responseContinuationTokenLimitInKb(5); + options2.partitionKey(new PartitionKey("99")); String query2 = "Select * from r order by r.prop"; boolean multiPartitionCollection2 = false; FeedOptions options3 = new FeedOptions(); - options3.setMaxItemCount(1); - options3.setResponseContinuationTokenLimitInKb(5); - options3.setPartitionKey(new PartitionKey("99")); + options3.maxItemCount(1); + options3.responseContinuationTokenLimitInKb(5); + options3.partitionKey(new PartitionKey("99")); String query3 = "Select * from r"; boolean multiPartitionCollection3 = false; FeedOptions options4 = new FeedOptions(); - options4.setPartitionKey(new PartitionKey("99")); + options4.partitionKey(new PartitionKey("99")); String query4 = "Select * from r order by r.prop"; boolean multiPartitionCollection4 = false; @@ -128,7 +124,7 @@ public void queryWithContinuationTokenLimit(FeedOptions options, String query, b Observable> queryObservable = client .queryDocuments(collectionLink, query, options); - List results = queryObservable.flatMap(p -> Observable.from(p.getResults())) + List results = queryObservable.flatMap(p -> Observable.from(p.results())) .toList().toBlocking().single(); assertThat(results.size()).describedAs("total results").isGreaterThanOrEqualTo(1); @@ -136,7 +132,7 @@ public void queryWithContinuationTokenLimit(FeedOptions options, String query, b List> requests = client.getCapturedRequests(); for(HttpClientRequest req: requests) { - validateRequestHasContinuationTokenLimit(req, options.getResponseContinuationTokenLimitInKb()); + validateRequestHasContinuationTokenLimit(req, options.responseContinuationTokenLimitInKb()); } } @@ -186,7 +182,7 @@ public void beforeClass() throws Exception { TimeUnit.SECONDS.sleep(1); FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); // do the query once to ensure the collection is cached. client.queryDocuments(getMultiPartitionCollectionLink(), "select * from root", options) diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/NetworkFailureTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java similarity index 88% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/NetworkFailureTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java index 81ffc4d664447..3ae77fac0f85f 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/NetworkFailureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java @@ -21,14 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.rx.FailureValidator; import org.mockito.Mockito; import org.testng.annotations.AfterClass; import org.testng.annotations.Factory; @@ -60,7 +59,7 @@ public void createCollectionWithUnreachableHost() { Database database = SHARED_DATABASE; Observable> createObservable = client - .createCollection(database.getSelfLink(), collectionDefinition, null); + .createCollection(database.selfLink(), collectionDefinition, null); final RxGatewayStoreModel origGatewayStoreModel = client.getOrigGatewayStoreModel(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ParallelAsync.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java similarity index 97% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ParallelAsync.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java index 47e7987673f13..c6b940a8da28f 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/ParallelAsync.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import org.apache.commons.lang3.Range; import rx.Completable; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryCreateDocumentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java similarity index 82% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryCreateDocumentTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java index 64fb216cc7624..c59ab2195c325 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryCreateDocumentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java @@ -21,21 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.Error; import com.google.common.collect.ImmutableMap; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.rx.ResourceResponseValidator; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -46,7 +38,6 @@ import org.testng.annotations.Test; import rx.Observable; -import javax.net.ssl.SSLException; import java.lang.reflect.Method; import java.util.Map; import java.util.UUID; @@ -71,12 +62,12 @@ public RetryCreateDocumentTest(AsyncDocumentClient.Builder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void retryDocumentCreate() throws Exception { // create a document to ensure collection is cached - client.createDocument(collection.getSelfLink(), getDocumentDefinition(), null, false).toBlocking().single(); + client.createDocument(collection.selfLink(), getDocumentDefinition(), null, false).toBlocking().single(); Document docDefinition = getDocumentDefinition(); Observable> createObservable = client - .createDocument(collection.getSelfLink(), docDefinition, null, false); + .createDocument(collection.selfLink(), docDefinition, null, false); AtomicInteger count = new AtomicInteger(); doAnswer(new Answer< Observable>() { @@ -93,7 +84,7 @@ public Observable answer(InvocationOnMock invocation) HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_MISMATCH)); - return Observable.error(new DocumentClientException(HttpConstants.StatusCodes.BADREQUEST, new Error() , header)); + return Observable.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, new Error() , header)); } else { return client.getOrigGatewayStoreModel().processMessage(req); } @@ -102,7 +93,7 @@ public Observable answer(InvocationOnMock invocation) // validate ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(docDefinition.getId()).build(); + .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator); } @@ -127,20 +118,20 @@ public Observable answer(InvocationOnMock invocation) HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(2)); - return Observable.error(new DocumentClientException(1, new Error() , header)); + return Observable.error(new CosmosClientException(1, new Error() , header)); } } }).when(client.getSpyGatewayStoreModel()).processMessage(anyObject()); // create a document to ensure collection is cached - client.createDocument(collection.getSelfLink(), getDocumentDefinition(), null, false) + client.createDocument(collection.selfLink(), getDocumentDefinition(), null, false) .toBlocking() .single(); Document docDefinition = getDocumentDefinition(); Observable> createObservable = client - .createDocument(collection.getSelfLink(), docDefinition, null, false); + .createDocument(collection.selfLink(), docDefinition, null, false); // validate FailureValidator validator = new FailureValidator.Builder().statusCode(1).subStatusCode(2).build(); @@ -150,7 +141,7 @@ public Observable answer(InvocationOnMock invocation) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createDocument_failImmediatelyOnNonRetriable() throws Exception { // create a document to ensure collection is cached - client.createDocument(collection.getSelfLink(), getDocumentDefinition(), null, false).toBlocking().single(); + client.createDocument(collection.selfLink(), getDocumentDefinition(), null, false).toBlocking().single(); AtomicInteger count = new AtomicInteger(); doAnswer(new Answer< Observable>() { @@ -166,7 +157,7 @@ public Observable answer(InvocationOnMock invocation) HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(2)); - return Observable.error(new DocumentClientException(1, new Error() , header)); + return Observable.error(new CosmosClientException(1, new Error() , header)); } else { return client.getOrigGatewayStoreModel().processMessage(req); } @@ -176,7 +167,7 @@ public Observable answer(InvocationOnMock invocation) Document docDefinition = getDocumentDefinition(); Observable> createObservable = client - .createDocument(collection.getSelfLink(), docDefinition, null, false); + .createDocument(collection.selfLink(), docDefinition, null, false); // validate FailureValidator validator = new FailureValidator.Builder().statusCode(1).subStatusCode(2).build(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java similarity index 82% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java index efc3b44043e54..38b4a8fd1ead5 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RetryThrottleTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.anyObject; @@ -39,20 +39,17 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.RetryOptions; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.RetryOptions; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.rx.ResourceResponseValidator; +import com.azure.data.cosmos.rx.TestConfigurations; import rx.Observable; @@ -69,15 +66,15 @@ public class RetryThrottleTest extends TestSuiteBase { public void retryCreateDocumentsOnSpike() throws Exception { ConnectionPolicy policy = new ConnectionPolicy(); RetryOptions retryOptions = new RetryOptions(); - retryOptions.setMaxRetryAttemptsOnThrottledRequests(Integer.MAX_VALUE); - retryOptions.setMaxRetryWaitTimeInSeconds(LARGE_TIMEOUT); - policy.setRetryOptions(retryOptions); + retryOptions.maxRetryAttemptsOnThrottledRequests(Integer.MAX_VALUE); + retryOptions.maxRetryWaitTimeInSeconds(LARGE_TIMEOUT); + policy.retryOptions(retryOptions); AsyncDocumentClient.Builder builder = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(policy) - .withConsistencyLevel(ConsistencyLevel.Eventual); + .withConsistencyLevel(ConsistencyLevel.EVENTUAL); client = SpyClientUnderTestFactory.createClientWithGatewaySpy(builder); @@ -99,7 +96,7 @@ public void retryCreateDocumentsOnSpike() throws Exception { public Observable answer(InvocationOnMock invocation) throws Throwable { RxDocumentServiceRequest req = (RxDocumentServiceRequest) invocation.getArguments()[0]; if (req.getResourceType() == ResourceType.Document && req.getOperationType() == OperationType.Create) { - // increment the counter per Document Create operations + // increment the counter per Document CREATE operations totalCount.incrementAndGet(); } return client.getOrigGatewayStoreModel().processMessage(req).doOnNext(rsp -> successCount.incrementAndGet()); @@ -123,7 +120,7 @@ public void retryDocumentCreate() throws Exception { Document docDefinition = getDocumentDefinition(); Observable> createObservable = client - .createDocument(collection.getSelfLink(), docDefinition, null, false); + .createDocument(collection.selfLink(), docDefinition, null, false); AtomicInteger count = new AtomicInteger(); doAnswer(new Answer< Observable>() { @@ -135,7 +132,7 @@ public Observable answer(InvocationOnMock invocation) } int currentAttempt = count.getAndIncrement(); if (currentAttempt == 0) { - return Observable.error(new DocumentClientException(HttpConstants.StatusCodes.TOO_MANY_REQUESTS)); + return Observable.error(new CosmosClientException(HttpConstants.StatusCodes.TOO_MANY_REQUESTS)); } else { return client.getOrigGatewayStoreModel().processMessage(req); } @@ -144,7 +141,7 @@ public Observable answer(InvocationOnMock invocation) // validate ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(docDefinition.getId()).build(); + .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator, TIMEOUT); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientUnderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java similarity index 90% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientUnderTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java index a59078f224f73..61b458a0095b2 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/RxDocumentClientUnderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java @@ -20,14 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.microsoft.azure.cosmos.ClientUnderTestBuilder; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.QueryCompatibilityMode; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.ClientUnderTestBuilder; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.ISessionContainer; import io.netty.buffer.ByteBuf; import io.reactivex.netty.client.RxClient; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/SessionTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java similarity index 85% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/SessionTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java index 7cb4c83c7b319..af911c74c10b5 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/SessionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java @@ -20,17 +20,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.AsyncDocumentClient; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; @@ -88,18 +87,18 @@ public void beforeClass() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); DocumentCollection collection = new DocumentCollection(); - collection.setId(collectionId); + collection.id(collectionId); collection.setPartitionKey(partitionKeyDef); - createdCollection = createCollection(createGatewayHouseKeepingDocumentClient().build(), createdDatabase.getId(), + createdCollection = createCollection(createGatewayHouseKeepingDocumentClient().build(), createdDatabase.id(), collection, null); houseKeepingClient = clientBuilder.build(); - connectionMode = houseKeepingClient.getConnectionPolicy().getConnectionMode(); + connectionMode = houseKeepingClient.getConnectionPolicy().connectionMode(); - if (connectionMode == ConnectionMode.Direct) { + if (connectionMode == ConnectionMode.DIRECT) { spyClient = SpyClientUnderTestFactory.createDirectHttpsClientUnderTest(clientBuilder); } else { spyClient = SpyClientUnderTestFactory.createClientUnderTest(clientBuilder); @@ -138,8 +137,8 @@ public void sessionConsistency_ReadYourWrites(boolean isNameBased) { Document documentCreated = spyClient.createDocument(getCollectionLink(isNameBased), new Document(), null, false) .toBlocking().single().getResource(); - // We send session tokens on Writes in Gateway mode - if (connectionMode == ConnectionMode.Gateway) { + // We send session tokens on Writes in GATEWAY mode + if (connectionMode == ConnectionMode.GATEWAY) { assertThat(getSessionTokensInRequests()).hasSize(3 * i + 1); assertThat(getSessionTokensInRequests().get(3 * i + 0)).isNotEmpty(); } @@ -159,7 +158,7 @@ public void sessionConsistency_ReadYourWrites(boolean isNameBased) { @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "sessionTestArgProvider") public void sessionTokenInDocumentRead(boolean isNameBased) throws UnsupportedEncodingException { Document document = new Document(); - document.setId(UUID.randomUUID().toString()); + document.id(UUID.randomUUID().toString()); document.set("pk", "pk"); document = spyClient.createDocument(getCollectionLink(isNameBased), document, null, false).toBlocking().single() .getResource(); @@ -179,14 +178,14 @@ public void sessionTokenInDocumentRead(boolean isNameBased) throws UnsupportedEn } }).collect(Collectors.toList()); - // Direct mode may make more than one call (multiple replicas) + // DIRECT mode may make more than one call (multiple replicas) assertThat(documentReadHttpRequests.size() >= 1).isTrue(); assertThat(documentReadHttpRequests.get(0).getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN)).isNotEmpty(); } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "sessionTestArgProvider") public void sessionTokenRemovedForMasterResource(boolean isNameBased) throws UnsupportedEncodingException { - if (connectionMode == ConnectionMode.Direct) { + if (connectionMode == ConnectionMode.DIRECT) { throw new SkipException("Master resource access is only through gateway"); } String collectionLink = getCollectionLink(isNameBased); @@ -209,12 +208,12 @@ public void sessionTokenRemovedForMasterResource(boolean isNameBased) throws Uns } private String getCollectionLink(boolean isNameBased) { - return isNameBased ? "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(): - createdCollection.getSelfLink(); + return isNameBased ? "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(): + createdCollection.selfLink(); } private String getDocumentLink(Document doc, boolean isNameBased) { - return isNameBased ? "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId() + "/docs/" + doc.getId() : - "dbs/" + createdDatabase.getResourceId() + "/colls/" + createdCollection.getResourceId() + "/docs/" + doc.getResourceId() + "/"; + return isNameBased ? "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id() + "/docs/" + doc.id() : + "dbs/" + createdDatabase.resourceId() + "/colls/" + createdCollection.resourceId() + "/docs/" + doc.resourceId() + "/"; } } \ No newline at end of file diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/SpyClientUnderTestFactory.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java similarity index 95% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/SpyClientUnderTestFactory.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java index b9082124c0910..a1e6b617966a4 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/SpyClientUnderTestFactory.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java @@ -20,17 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; - -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.ISessionContainer; -import com.microsoft.azure.cosmosdb.internal.QueryCompatibilityMode; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.SpyClientBuilder; -import com.microsoft.azure.cosmosdb.rx.internal.directconnectivity.ReflectionUtils; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.internal.directconnectivity.ReflectionUtils; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.SpyClientBuilder; import io.netty.buffer.ByteBuf; import io.reactivex.netty.client.RxClient; @@ -198,9 +196,9 @@ public static class DirectHttpsClientUnderTest extends SpyBaseClass, Future>>()); DirectHttpsClientUnderTest(URI serviceEndpoint, String masterKey, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel) { - // TODO: DANOBLE: ensure the configs instance instantiated here specifies Protocol.Https + // TODO: DANOBLE: ensure the configs instance instantiated here specifies Protocol.HTTPS super(serviceEndpoint, masterKey, connectionPolicy, consistencyLevel, new Configs()); - assert connectionPolicy.getConnectionMode() == ConnectionMode.Direct; + assert connectionPolicy.connectionMode() == ConnectionMode.DIRECT; init(); this.origHttpClient = ReflectionUtils.getDirectHttpsHttpClient(this); this.spyHttpClient = Mockito.spy(this.origHttpClient); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/StoreHeaderTests.java b/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java similarity index 82% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/StoreHeaderTests.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java index c7efac21b137d..386166ea381f7 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/StoreHeaderTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -50,15 +50,15 @@ public StoreHeaderTests(AsyncDocumentClient.Builder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void validateStoreHeader() { Document docDefinition1 = getDocumentDefinition(); - Document responseDoc1 = createDocument(client, createdDatabase.getId(), createdCollection.getId(), docDefinition1); - Assert.assertNotNull(responseDoc1.getSelfLink()); + Document responseDoc1 = createDocument(client, createdDatabase.id(), createdCollection.id(), docDefinition1); + Assert.assertNotNull(responseDoc1.selfLink()); Assert.assertNotNull(responseDoc1.get("_attachments")); Document docDefinition2 = getDocumentDefinition(); RequestOptions requestOptions = new RequestOptions(); - requestOptions.setHeader("x-ms-exclude-system-properties", "true"); - Document responseDoc2 = createDocument(client, createdDatabase.getId(), createdCollection.getId(), docDefinition2, requestOptions); - Assert.assertNull(responseDoc2.getSelfLink()); + requestOptions.setHeader("x-ms-exclude-system-item", "true"); + Document responseDoc2 = createDocument(client, createdDatabase.id(), createdCollection.id(), docDefinition2, requestOptions); + Assert.assertNull(responseDoc2.selfLink()); Assert.assertNull(responseDoc2.get("_attachments")); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java similarity index 80% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index 6465e8ed135e8..8234891696a5c 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal; +package com.azure.data.cosmos.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doAnswer; @@ -36,23 +36,13 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import com.azure.data.cosmos.*; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.Index; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.RetryOptions; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.Undefined; -import com.microsoft.azure.cosmosdb.internal.PathParser; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; +import com.azure.data.cosmos.directconnectivity.Protocol; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.mockito.stubbing.Answer; @@ -64,29 +54,12 @@ import org.testng.annotations.BeforeSuite; import org.testng.annotations.DataProvider; -import com.microsoft.azure.cosmosdb.CompositePath; -import com.microsoft.azure.cosmosdb.CompositePathSortOrder; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; -import com.microsoft.azure.cosmosdb.rx.FailureValidator; -import com.microsoft.azure.cosmosdb.rx.FeedResponseListValidator; -import com.microsoft.azure.cosmosdb.rx.ResourceResponseValidator; -import com.microsoft.azure.cosmosdb.rx.TestConfigurations; -import com.microsoft.azure.cosmosdb.rx.Utils; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.rx.FeedResponseListValidator; +import com.azure.data.cosmos.rx.ResourceResponseValidator; +import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.rx.Utils; import org.testng.annotations.Test; import rx.Observable; @@ -126,7 +99,7 @@ public class TestSuiteBase { allEqualOrLowerConsistencies(accountConsistency))); preferredLocations = immutableListOrNull(parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS)); protocols = ObjectUtils.defaultIfNull(immutableListOrNull(parseProtocols(TestConfigurations.PROTOCOLS)), - ImmutableList.of(Protocol.Https, Protocol.Tcp)); + ImmutableList.of(Protocol.HTTPS, Protocol.TCP)); } protected TestSuiteBase() { @@ -146,7 +119,7 @@ public void beforeMethod(Method method) { if (this.clientBuilder != null) { logger.info("Starting {}::{} using {} {} mode with {} consistency", method.getDeclaringClass().getSimpleName(), method.getName(), - this.clientBuilder.getConnectionPolicy().getConnectionMode(), + this.clientBuilder.getConnectionPolicy().connectionMode(), this.clientBuilder.getConfigs().getProtocol(), this.clientBuilder.getDesiredConsistencyLevel()); return; @@ -197,9 +170,9 @@ public static void beforeSuite() { SHARED_DATABASE = dbForTest.createdDatabase; RequestOptions options = new RequestOptions(); options.setOfferThroughput(10100); - SHARED_MULTI_PARTITION_COLLECTION = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinitionWithRangeRangeIndex(), options); - SHARED_SINGLE_PARTITION_COLLECTION = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinition(), null); - SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES = createCollection(houseKeepingClient, SHARED_DATABASE.getId(), getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes(), options); + SHARED_MULTI_PARTITION_COLLECTION = createCollection(houseKeepingClient, SHARED_DATABASE.id(), getCollectionDefinitionWithRangeRangeIndex(), options); + SHARED_SINGLE_PARTITION_COLLECTION = createCollection(houseKeepingClient, SHARED_DATABASE.id(), getCollectionDefinition(), null); + SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES = createCollection(houseKeepingClient, SHARED_DATABASE.id(), getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes(), options); } finally { houseKeepingClient.close(); } @@ -218,20 +191,20 @@ public static void afterSuite() { } protected static void truncateCollection(DocumentCollection collection) { - logger.info("Truncating collection {} ...", collection.getId()); + logger.info("Truncating collection {} ...", collection.id()); AsyncDocumentClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); try { - List paths = collection.getPartitionKey().getPaths(); + List paths = collection.getPartitionKey().paths(); FeedOptions options = new FeedOptions(); - options.setMaxDegreeOfParallelism(-1); - options.setEnableCrossPartitionQuery(true); - options.setMaxItemCount(100); + options.maxDegreeOfParallelism(-1); + options.enableCrossPartitionQuery(true); + options.maxItemCount(100); - logger.info("Truncating collection {} documents ...", collection.getId()); + logger.info("Truncating collection {} documents ...", collection.id()); - houseKeepingClient.queryDocuments(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) + houseKeepingClient.queryDocuments(collection.selfLink(), "SELECT * FROM root", options) + .flatMap(page -> Observable.from(page.results())) .flatMap(doc -> { RequestOptions requestOptions = new RequestOptions(); @@ -245,66 +218,66 @@ protected static void truncateCollection(DocumentCollection collection) { requestOptions.setPartitionKey(new PartitionKey(propertyValue)); } - return houseKeepingClient.deleteDocument(doc.getSelfLink(), requestOptions); + return houseKeepingClient.deleteDocument(doc.selfLink(), requestOptions); }).toCompletable().await(); - logger.info("Truncating collection {} triggers ...", collection.getId()); + logger.info("Truncating collection {} triggers ...", collection.id()); - houseKeepingClient.queryTriggers(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) + houseKeepingClient.queryTriggers(collection.selfLink(), "SELECT * FROM root", options) + .flatMap(page -> Observable.from(page.results())) .flatMap(trigger -> { RequestOptions requestOptions = new RequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = trigger.getObjectByPath(PathParser.getPathParts(paths.get(0))); -// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); +// requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return houseKeepingClient.deleteTrigger(trigger.getSelfLink(), requestOptions); + return houseKeepingClient.deleteTrigger(trigger.selfLink(), requestOptions); }).toCompletable().await(); - logger.info("Truncating collection {} storedProcedures ...", collection.getId()); + logger.info("Truncating collection {} storedProcedures ...", collection.id()); - houseKeepingClient.queryStoredProcedures(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) + houseKeepingClient.queryStoredProcedures(collection.selfLink(), "SELECT * FROM root", options) + .flatMap(page -> Observable.from(page.results())) .flatMap(storedProcedure -> { RequestOptions requestOptions = new RequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = storedProcedure.getObjectByPath(PathParser.getPathParts(paths.get(0))); -// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); +// requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return houseKeepingClient.deleteStoredProcedure(storedProcedure.getSelfLink(), requestOptions); + return houseKeepingClient.deleteStoredProcedure(storedProcedure.selfLink(), requestOptions); }).toCompletable().await(); - logger.info("Truncating collection {} udfs ...", collection.getId()); + logger.info("Truncating collection {} udfs ...", collection.id()); - houseKeepingClient.queryUserDefinedFunctions(collection.getSelfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.getResults())) + houseKeepingClient.queryUserDefinedFunctions(collection.selfLink(), "SELECT * FROM root", options) + .flatMap(page -> Observable.from(page.results())) .flatMap(udf -> { RequestOptions requestOptions = new RequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = udf.getObjectByPath(PathParser.getPathParts(paths.get(0))); -// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); +// requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return houseKeepingClient.deleteUserDefinedFunction(udf.getSelfLink(), requestOptions); + return houseKeepingClient.deleteUserDefinedFunction(udf.selfLink(), requestOptions); }).toCompletable().await(); } finally { houseKeepingClient.close(); } - logger.info("Finished truncating collection {}.", collection.getId()); + logger.info("Finished truncating collection {}.", collection.id()); } protected static void waitIfNeededForReplicasToCatchUp(Builder clientBuilder) { switch (clientBuilder.getDesiredConsistencyLevel()) { - case Eventual: - case ConsistentPrefix: - logger.info(" additional wait in Eventual mode so the replica catch up"); + case EVENTUAL: + case CONSISTENT_PREFIX: + logger.info(" additional wait in EVENTUAL mode so the replica catch up"); // give times to replicas to catch up after a write try { TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); @@ -312,9 +285,9 @@ protected static void waitIfNeededForReplicasToCatchUp(Builder clientBuilder) { logger.error("unexpected failure", e); } - case Session: - case BoundedStaleness: - case Strong: + case SESSION: + case BOUNDED_STALENESS: + case STRONG: default: break; } @@ -363,12 +336,12 @@ private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompo //Simple ArrayList compositeIndexSimple = new ArrayList(); CompositePath compositePath1 = new CompositePath(); - compositePath1.setPath("/" + NUMBER_FIELD); - compositePath1.setOrder(CompositePathSortOrder.Ascending); + compositePath1.path("/" + NUMBER_FIELD); + compositePath1.order(CompositePathSortOrder.ASCENDING); CompositePath compositePath2 = new CompositePath(); - compositePath2.setPath("/" + STRING_FIELD); - compositePath2.setOrder(CompositePathSortOrder.Descending); + compositePath2.path("/" + STRING_FIELD); + compositePath2.order(CompositePathSortOrder.DESCENDING); compositeIndexSimple.add(compositePath1); compositeIndexSimple.add(compositePath2); @@ -376,20 +349,20 @@ private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompo //Max Columns ArrayList compositeIndexMaxColumns = new ArrayList(); CompositePath compositePath3 = new CompositePath(); - compositePath3.setPath("/" + NUMBER_FIELD); - compositePath3.setOrder(CompositePathSortOrder.Descending); + compositePath3.path("/" + NUMBER_FIELD); + compositePath3.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath4 = new CompositePath(); - compositePath4.setPath("/" + STRING_FIELD); - compositePath4.setOrder(CompositePathSortOrder.Ascending); + compositePath4.path("/" + STRING_FIELD); + compositePath4.order(CompositePathSortOrder.ASCENDING); CompositePath compositePath5 = new CompositePath(); - compositePath5.setPath("/" + NUMBER_FIELD_2); - compositePath5.setOrder(CompositePathSortOrder.Descending); + compositePath5.path("/" + NUMBER_FIELD_2); + compositePath5.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath6 = new CompositePath(); - compositePath6.setPath("/" + STRING_FIELD_2); - compositePath6.setOrder(CompositePathSortOrder.Ascending); + compositePath6.path("/" + STRING_FIELD_2); + compositePath6.order(CompositePathSortOrder.ASCENDING); compositeIndexMaxColumns.add(compositePath3); compositeIndexMaxColumns.add(compositePath4); @@ -399,20 +372,20 @@ private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompo //Primitive Values ArrayList compositeIndexPrimitiveValues = new ArrayList(); CompositePath compositePath7 = new CompositePath(); - compositePath7.setPath("/" + NUMBER_FIELD); - compositePath7.setOrder(CompositePathSortOrder.Descending); + compositePath7.path("/" + NUMBER_FIELD); + compositePath7.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath8 = new CompositePath(); - compositePath8.setPath("/" + STRING_FIELD); - compositePath8.setOrder(CompositePathSortOrder.Ascending); + compositePath8.path("/" + STRING_FIELD); + compositePath8.order(CompositePathSortOrder.ASCENDING); CompositePath compositePath9 = new CompositePath(); - compositePath9.setPath("/" + BOOL_FIELD); - compositePath9.setOrder(CompositePathSortOrder.Descending); + compositePath9.path("/" + BOOL_FIELD); + compositePath9.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath10 = new CompositePath(); - compositePath10.setPath("/" + NULL_FIELD); - compositePath10.setOrder(CompositePathSortOrder.Ascending); + compositePath10.path("/" + NULL_FIELD); + compositePath10.order(CompositePathSortOrder.ASCENDING); compositeIndexPrimitiveValues.add(compositePath7); compositeIndexPrimitiveValues.add(compositePath8); @@ -422,16 +395,16 @@ private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompo //Long Strings ArrayList compositeIndexLongStrings = new ArrayList(); CompositePath compositePath11 = new CompositePath(); - compositePath11.setPath("/" + STRING_FIELD); + compositePath11.path("/" + STRING_FIELD); CompositePath compositePath12 = new CompositePath(); - compositePath12.setPath("/" + SHORT_STRING_FIELD); + compositePath12.path("/" + SHORT_STRING_FIELD); CompositePath compositePath13 = new CompositePath(); - compositePath13.setPath("/" + MEDIUM_STRING_FIELD); + compositePath13.path("/" + MEDIUM_STRING_FIELD); CompositePath compositePath14 = new CompositePath(); - compositePath14.setPath("/" + LONG_STRING_FIELD); + compositePath14.path("/" + LONG_STRING_FIELD); compositeIndexLongStrings.add(compositePath11); compositeIndexLongStrings.add(compositePath12); @@ -443,16 +416,16 @@ private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompo compositeIndexes.add(compositeIndexPrimitiveValues); compositeIndexes.add(compositeIndexLongStrings); - indexingPolicy.setCompositeIndexes(compositeIndexes); + indexingPolicy.compositeIndexes(compositeIndexes); documentCollection.setIndexingPolicy(indexingPolicy); PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); ArrayList partitionKeyPaths = new ArrayList(); partitionKeyPaths.add("/" + PARTITION_KEY); - partitionKeyDefinition.setPaths(partitionKeyPaths); + partitionKeyDefinition.paths(partitionKeyPaths); documentCollection.setPartitionKey(partitionKeyDefinition); - documentCollection.setId(UUID.randomUUID().toString()); + documentCollection.id(UUID.randomUUID().toString()); return documentCollection; } @@ -502,27 +475,27 @@ public static User createUser(AsyncDocumentClient client, String databaseId, Use } public static User safeCreateUser(AsyncDocumentClient client, String databaseId, User user) { - deleteUserIfExists(client, databaseId, user.getId()); + deleteUserIfExists(client, databaseId, user.id()); return createUser(client, databaseId, user); } private static DocumentCollection safeCreateCollection(AsyncDocumentClient client, String databaseId, DocumentCollection collection, RequestOptions options) { - deleteCollectionIfExists(client, databaseId, collection.getId()); + deleteCollectionIfExists(client, databaseId, collection.id()); return createCollection(client, databaseId, collection, options); } public static String getCollectionLink(DocumentCollection collection) { - return collection.getSelfLink(); + return collection.selfLink(); } static protected DocumentCollection getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); collectionDefinition.setPartitionKey(partitionKeyDef); return collectionDefinition; @@ -532,26 +505,26 @@ static protected DocumentCollection getCollectionDefinitionWithRangeRangeIndex() PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); + includedPath.path("/*"); Collection indexes = new ArrayList<>(); - Index stringIndex = Index.Range(DataType.String); + Index stringIndex = Index.Range(DataType.STRING); stringIndex.set("precision", -1); indexes.add(stringIndex); - Index numberIndex = Index.Range(DataType.Number); + Index numberIndex = Index.Range(DataType.NUMBER); numberIndex.set("precision", -1); indexes.add(numberIndex); - includedPath.setIndexes(indexes); + includedPath.indexes(indexes); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.setIndexingPolicy(indexingPolicy); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); collectionDefinition.setPartitionKey(partitionKeyDef); return collectionDefinition; @@ -560,7 +533,7 @@ static protected DocumentCollection getCollectionDefinitionWithRangeRangeIndex() public static void deleteCollectionIfExists(AsyncDocumentClient client, String databaseId, String collectionId) { List res = client.queryCollections("dbs/" + databaseId, String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null).toBlocking().single() - .getResults(); + .results(); if (!res.isEmpty()) { deleteCollection(client, Utils.getCollectionNameLink(databaseId, collectionId)); } @@ -572,10 +545,10 @@ public static void deleteCollection(AsyncDocumentClient client, String collectio public static void deleteDocumentIfExists(AsyncDocumentClient client, String databaseId, String collectionId, String docId) { FeedOptions options = new FeedOptions(); - options.setPartitionKey(new PartitionKey(docId)); + options.partitionKey(new PartitionKey(docId)); List res = client .queryDocuments(Utils.getCollectionNameLink(databaseId, collectionId), String.format("SELECT * FROM root r where r.id = '%s'", docId), options) - .toBlocking().single().getResults(); + .toBlocking().single().results(); if (!res.isEmpty()) { deleteDocument(client, Utils.getDocumentNameLink(databaseId, collectionId, docId)); } @@ -586,8 +559,8 @@ public static void safeDeleteDocument(AsyncDocumentClient client, String documen try { client.deleteDocument(documentLink, options).toBlocking().single(); } catch (Exception e) { - DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e, DocumentClientException.class); - if (dce == null || dce.getStatusCode() != 404) { + CosmosClientException dce = com.azure.data.cosmos.internal.Utils.as(e, CosmosClientException.class); + if (dce == null || dce.statusCode() != 404) { throw e; } } @@ -601,7 +574,7 @@ public static void deleteDocument(AsyncDocumentClient client, String documentLin public static void deleteUserIfExists(AsyncDocumentClient client, String databaseId, String userId) { List res = client .queryUsers("dbs/" + databaseId, String.format("SELECT * FROM root r where r.id = '%s'", userId), null) - .toBlocking().single().getResults(); + .toBlocking().single().results(); if (!res.isEmpty()) { deleteUser(client, Utils.getUserNameLink(databaseId, userId)); } @@ -612,11 +585,11 @@ public static void deleteUser(AsyncDocumentClient client, String userLink) { } public static String getDatabaseLink(Database database) { - return database.getSelfLink(); + return database.selfLink(); } static private Database safeCreateDatabase(AsyncDocumentClient client, Database database) { - safeDeleteDatabase(client, database.getId()); + safeDeleteDatabase(client, database.id()); return createDatabase(client, database); } @@ -627,16 +600,16 @@ static protected Database createDatabase(AsyncDocumentClient client, Database da static protected Database createDatabase(AsyncDocumentClient client, String databaseId) { Database databaseDefinition = new Database(); - databaseDefinition.setId(databaseId); + databaseDefinition.id(databaseId); return createDatabase(client, databaseDefinition); } static protected Database createDatabaseIfNotExists(AsyncDocumentClient client, String databaseId) { - return client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null).flatMap(p -> Observable.from(p.getResults())).switchIfEmpty( + return client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null).flatMap(p -> Observable.from(p.results())).switchIfEmpty( Observable.defer(() -> { Database databaseDefinition = new Database(); - databaseDefinition.setId(databaseId); + databaseDefinition.id(databaseId); return client.createDatabase(databaseDefinition, null).map(ResourceResponse::getResource); }) @@ -645,7 +618,7 @@ static protected Database createDatabaseIfNotExists(AsyncDocumentClient client, static protected void safeDeleteDatabase(AsyncDocumentClient client, Database database) { if (database != null) { - safeDeleteDatabase(client, database.getId()); + safeDeleteDatabase(client, database.id()); } } @@ -660,14 +633,14 @@ static protected void safeDeleteDatabase(AsyncDocumentClient client, String data static protected void safeDeleteAllCollections(AsyncDocumentClient client, Database database) { if (database != null) { - List collections = client.readCollections(database.getSelfLink(), null) - .flatMap(p -> Observable.from(p.getResults())) + List collections = client.readCollections(database.selfLink(), null) + .flatMap(p -> Observable.from(p.results())) .toList() .toBlocking() .single(); for (DocumentCollection collection : collections) { - client.deleteCollection(collection.getSelfLink(), null).toBlocking().single().getResource(); + client.deleteCollection(collection.selfLink(), null).toBlocking().single().getResource(); } } } @@ -675,7 +648,7 @@ static protected void safeDeleteAllCollections(AsyncDocumentClient client, Datab static protected void safeDeleteCollection(AsyncDocumentClient client, DocumentCollection collection) { if (client != null && collection != null) { try { - client.deleteCollection(collection.getSelfLink(), null).toBlocking().single(); + client.deleteCollection(collection.selfLink(), null).toBlocking().single(); } catch (Exception e) { } } @@ -785,15 +758,15 @@ public static void validateQueryFailure(Observable parsePreferredLocation(String preferredLocations) { @@ -819,8 +792,8 @@ static List parsePreferredLocation(String preferredLocations) { return objectMapper.readValue(preferredLocations, new TypeReference>() { }); } catch (Exception e) { - logger.error("Invalid configured test preferredLocations [{}].", preferredLocations); - throw new IllegalStateException("Invalid configured test preferredLocations " + preferredLocations); + logger.error("INVALID configured test preferredLocations [{}].", preferredLocations); + throw new IllegalStateException("INVALID configured test preferredLocations " + preferredLocations); } } @@ -833,8 +806,8 @@ static List parseProtocols(String protocols) { return objectMapper.readValue(protocols, new TypeReference>() { }); } catch (Exception e) { - logger.error("Invalid configured test protocols [{}].", protocols); - throw new IllegalStateException("Invalid configured test protocols " + protocols); + logger.error("INVALID configured test protocols [{}].", protocols); + throw new IllegalStateException("INVALID configured test protocols " + protocols); } } @@ -845,17 +818,17 @@ public static Object[][] simpleClientBuildersWithDirect() { @DataProvider public static Object[][] simpleClientBuildersWithDirectHttps() { - return simpleClientBuildersWithDirect(Protocol.Https); + return simpleClientBuildersWithDirect(Protocol.HTTPS); } private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); - List testConsistencies = ImmutableList.of(ConsistencyLevel.Eventual); + List testConsistencies = ImmutableList.of(ConsistencyLevel.EVENTUAL); - boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.Session; + boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List builders = new ArrayList<>(); - builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null)); + builders.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null)); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> builders.add(createDirectRxDocumentClient(consistencyLevel, @@ -865,7 +838,7 @@ private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) } builders.forEach(b -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", - b.getConnectionPolicy().getConnectionMode(), + b.getConnectionPolicy().connectionMode(), b.getDesiredConsistencyLevel(), b.getConfigs().getProtocol() )); @@ -880,7 +853,7 @@ public static Object[][] clientBuildersWithDirect() { @DataProvider public static Object[][] clientBuildersWithDirectHttps() { - return clientBuildersWithDirectAllConsistencies(Protocol.Https); + return clientBuildersWithDirectAllConsistencies(Protocol.HTTPS); } @DataProvider @@ -894,7 +867,7 @@ static Protocol[] toArray(List protocols) { private static Object[][] clientBuildersWithDirectSession(Protocol... protocols) { return clientBuildersWithDirect(new ArrayList() {{ - add(ConsistencyLevel.Session); + add(ConsistencyLevel.SESSION); }}, protocols); } @@ -912,36 +885,36 @@ static List parseDesiredConsistencies(String consistencies) { return objectMapper.readValue(consistencies, new TypeReference>() { }); } catch (Exception e) { - logger.error("Invalid consistency test desiredConsistencies [{}].", consistencies); - throw new IllegalStateException("Invalid configured test desiredConsistencies " + consistencies); + logger.error("INVALID consistency test desiredConsistencies [{}].", consistencies); + throw new IllegalStateException("INVALID configured test desiredConsistencies " + consistencies); } } static List allEqualOrLowerConsistencies(ConsistencyLevel accountConsistency) { List testConsistencies = new ArrayList<>(); switch (accountConsistency) { - case Strong: - testConsistencies.add(ConsistencyLevel.Strong); - case BoundedStaleness: - testConsistencies.add(ConsistencyLevel.BoundedStaleness); - case Session: - testConsistencies.add(ConsistencyLevel.Session); - case ConsistentPrefix: - testConsistencies.add(ConsistencyLevel.ConsistentPrefix); - case Eventual: - testConsistencies.add(ConsistencyLevel.Eventual); + case STRONG: + testConsistencies.add(ConsistencyLevel.STRONG); + case BOUNDED_STALENESS: + testConsistencies.add(ConsistencyLevel.BOUNDED_STALENESS); + case SESSION: + testConsistencies.add(ConsistencyLevel.SESSION); + case CONSISTENT_PREFIX: + testConsistencies.add(ConsistencyLevel.CONSISTENT_PREFIX); + case EVENTUAL: + testConsistencies.add(ConsistencyLevel.EVENTUAL); break; default: - throw new IllegalStateException("Invalid configured test consistency " + accountConsistency); + throw new IllegalStateException("INVALID configured test consistency " + accountConsistency); } return testConsistencies; } private static Object[][] clientBuildersWithDirect(List testConsistencies, Protocol... protocols) { - boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.Session; + boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List builders = new ArrayList<>(); - builders.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, isMultiMasterEnabled, preferredLocations)); + builders.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations)); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> builders.add(createDirectRxDocumentClient(consistencyLevel, @@ -951,7 +924,7 @@ private static Object[][] clientBuildersWithDirect(List testCo } builders.forEach(b -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", - b.getConnectionPolicy().getConnectionMode(), + b.getConnectionPolicy().connectionMode(), b.getDesiredConsistencyLevel(), b.getConfigs().getProtocol() )); @@ -961,21 +934,21 @@ private static Object[][] clientBuildersWithDirect(List testCo static protected Builder createGatewayHouseKeepingDocumentClient() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); RetryOptions options = new RetryOptions(); - options.setMaxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); - connectionPolicy.setRetryOptions(options); + options.maxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); + connectionPolicy.retryOptions(options); return new Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session); + .withConsistencyLevel(ConsistencyLevel.SESSION); } static protected Builder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List preferredLocations) { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); - connectionPolicy.setUsingMultipleWriteLocations(multiMasterEnabled); - connectionPolicy.setPreferredLocations(preferredLocations); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); + connectionPolicy.usingMultipleWriteLocations(multiMasterEnabled); + connectionPolicy.preferredLocations(preferredLocations); return new Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) @@ -983,7 +956,7 @@ static protected Builder createGatewayRxDocumentClient(ConsistencyLevel consiste } static protected Builder createGatewayRxDocumentClient() { - return createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null); + return createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null); } static protected Builder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, @@ -991,14 +964,14 @@ static protected Builder createDirectRxDocumentClient(ConsistencyLevel consisten boolean multiMasterEnabled, List preferredLocations) { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); if (preferredLocations != null) { - connectionPolicy.setPreferredLocations(preferredLocations); + connectionPolicy.preferredLocations(preferredLocations); } - if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.Session) { - connectionPolicy.setUsingMultipleWriteLocations(true); + if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.SESSION) { + connectionPolicy.usingMultipleWriteLocations(true); } Configs configs = spy(new Configs()); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/GlobalAddressResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java similarity index 82% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/GlobalAddressResolverTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java index badd57df6db53..a51126ca66e45 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/GlobalAddressResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java @@ -21,26 +21,26 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.directconnectivity; - - -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.OperationType; -import com.microsoft.azure.cosmosdb.internal.ResourceType; -import com.microsoft.azure.cosmosdb.internal.UserAgentContainer; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.GatewayAddressCache; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.GatewayServiceConfigurationReader; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.internal.routing.CollectionRoutingMap; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyInternalHelper; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.rx.internal.GlobalEndpointManager; -import com.microsoft.azure.cosmosdb.rx.internal.IAuthorizationTokenProvider; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxCollectionCache; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxPartitionKeyRangeCache; +package com.azure.data.cosmos.internal.directconnectivity; + + +import com.azure.data.cosmos.internal.GlobalEndpointManager; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.directconnectivity.GatewayAddressCache; +import com.azure.data.cosmos.directconnectivity.GatewayServiceConfigurationReader; +import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import org.apache.commons.collections4.list.UnmodifiableList; @@ -90,7 +90,7 @@ public void setup() throws Exception { urlforWrite3 = new URL("http://testWrite3.com/"); connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setEnableReadRequestsFallback(true); + connectionPolicy.enableReadRequestsFallback(true); httpClient = Mockito.mock(CompositeHttpClient.class); endpointManager = Mockito.mock(GlobalEndpointManager.class); @@ -112,7 +112,7 @@ public void setup() throws Exception { authorizationTokenProvider = Mockito.mock(IAuthorizationTokenProvider.class); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); collectionCache = Mockito.mock(RxCollectionCache.class); Mockito.when(collectionCache.resolveCollectionAsync(Matchers.any(RxDocumentServiceRequest.class))).thenReturn(Single.just(collectionDefinition)); routingMapProvider = Mockito.mock(RxPartitionKeyRangeCache.class); @@ -124,7 +124,7 @@ public void setup() throws Exception { @Test(groups = "unit") public void resolveAsync() throws Exception { - GlobalAddressResolver globalAddressResolver = new GlobalAddressResolver(httpClient, endpointManager, Protocol.Https, authorizationTokenProvider, collectionCache, routingMapProvider, + GlobalAddressResolver globalAddressResolver = new GlobalAddressResolver(httpClient, endpointManager, Protocol.HTTPS, authorizationTokenProvider, collectionCache, routingMapProvider, userAgentContainer, serviceConfigReader, connectionPolicy); RxDocumentServiceRequest request; @@ -149,7 +149,7 @@ public void resolveAsync() throws Exception { @Test(groups = "unit") public void openAsync() throws Exception { - GlobalAddressResolver globalAddressResolver = new GlobalAddressResolver(httpClient, endpointManager, Protocol.Https, authorizationTokenProvider, collectionCache, routingMapProvider, + GlobalAddressResolver globalAddressResolver = new GlobalAddressResolver(httpClient, endpointManager, Protocol.HTTPS, authorizationTokenProvider, collectionCache, routingMapProvider, userAgentContainer, serviceConfigReader, connectionPolicy); Map addressCacheByEndpoint = Mockito.spy(globalAddressResolver.addressCacheByEndpoint); @@ -163,8 +163,8 @@ public void openAsync() throws Exception { DocumentCollection documentCollection = new DocumentCollection(); - documentCollection.setId("TestColl"); - documentCollection.setResourceId("IXYFAOHEBPM="); + documentCollection.id("TestColl"); + documentCollection.resourceId("IXYFAOHEBPM="); CollectionRoutingMap collectionRoutingMap = Mockito.mock(CollectionRoutingMap.class); PartitionKeyRange range = new PartitionKeyRange("0", PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey); @@ -176,7 +176,7 @@ public void openAsync() throws Exception { List ranges = new ArrayList<>(); for (PartitionKeyRange partitionKeyRange : (List) collectionRoutingMap.getOrderedPartitionKeyRanges()) { - PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(documentCollection.getResourceId(), partitionKeyRange.getId()); + PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(documentCollection.resourceId(), partitionKeyRange.id()); ranges.add(partitionKeyRangeIdentity); } Completable completable = Completable.fromAction(new Action0() { diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/ReflectionUtils.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java similarity index 87% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/ReflectionUtils.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java index 80f31b9cc3f63..1fc211630cdcb 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/directconnectivity/ReflectionUtils.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java @@ -21,15 +21,15 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.HttpTransportClient; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.ServerStoreModel; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.StoreClient; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.TransportClient; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientImpl; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.internal.RxDocumentClientImpl; +import com.azure.data.cosmos.directconnectivity.HttpTransportClient; +import com.azure.data.cosmos.directconnectivity.ServerStoreModel; +import com.azure.data.cosmos.directconnectivity.StoreClient; +import com.azure.data.cosmos.directconnectivity.TransportClient; +import com.azure.data.cosmos.AsyncDocumentClient; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import org.apache.commons.lang3.reflect.FieldUtils; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentProducerTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java similarity index 92% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentProducerTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java index 479fe761b0cc9..65195bcaaeefb 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/query/DocumentProducerTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java @@ -20,31 +20,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; - +package com.azure.data.cosmos.internal.query; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.internal.GlobalEndpointManager; +import com.azure.data.cosmos.internal.IRetryPolicyFactory; +import com.azure.data.cosmos.internal.RetryPolicy; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedListMultimap; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.Error; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.internal.query.QueryItem; -import com.microsoft.azure.cosmosdb.internal.query.SortOrder; -import com.microsoft.azure.cosmosdb.internal.query.orderbyquery.OrderByRowResult; -import com.microsoft.azure.cosmosdb.internal.query.orderbyquery.OrderbyRowComparer; -import com.microsoft.azure.cosmosdb.internal.routing.PartitionKeyRangeIdentity; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.internal.GlobalEndpointManager; -import com.microsoft.azure.cosmosdb.rx.internal.IRetryPolicyFactory; -import com.microsoft.azure.cosmosdb.rx.internal.RetryPolicy; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; -import com.microsoft.azure.cosmosdb.rx.internal.caches.RxPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; +import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.routing.Range; import org.apache.commons.lang3.RandomUtils; import org.mockito.Matchers; import org.mockito.Mockito; @@ -125,7 +119,7 @@ private IRetryPolicyFactory mockDocumentClientIRetryPolicyFactory() { GlobalEndpointManager globalEndpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(url).when(globalEndpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); doReturn(false).when(globalEndpointManager).isClosed(); - return new RetryPolicy(globalEndpointManager, ConnectionPolicy.GetDefault()); + return new RetryPolicy(globalEndpointManager, ConnectionPolicy.defaultPolicy()); } @Test(groups = { "unit" }, dataProvider = "splitParamProvider", timeOut = TIMEOUT) @@ -375,7 +369,7 @@ public void simple() { assertThat(requestCreator.invocations.get(0).continuationToken).isEqualTo(initialContinuationToken); assertThat(requestCreator.invocations.stream().skip(1).map(i -> i.continuationToken) .collect(Collectors.toList())).containsExactlyElementsOf( - responses.stream().limit(9).map(r -> r.getResponseContinuation()).collect(Collectors.toList())); + responses.stream().limit(9).map(r -> r.continuationToken()).collect(Collectors.toList())); // source partition assertThat(requestCreator.invocations.stream().map(i -> i.sourcePartition).distinct() @@ -442,11 +436,11 @@ public void retries() { .collect(Collectors.toList())).containsExactlyElementsOf(Collections.singletonList(targetRange)); List resultContinuationToken = subscriber.getOnNextEvents() - .stream().map(r -> r.pageResult.getResponseContinuation()).collect(Collectors.toList()); + .stream().map(r -> r.pageResult.continuationToken()).collect(Collectors.toList()); List beforeExceptionContinuationTokens = responsesBeforeThrottle.stream() - .map(r -> r.getResponseContinuation()).collect(Collectors.toList()); + .map(r -> r.continuationToken()).collect(Collectors.toList()); List afterExceptionContinuationTokens = responsesAfterThrottle.stream() - .map(r -> r.getResponseContinuation()).collect(Collectors.toList()); + .map(r -> r.continuationToken()).collect(Collectors.toList()); assertThat(resultContinuationToken).containsExactlyElementsOf( Iterables.concat(beforeExceptionContinuationTokens, afterExceptionContinuationTokens)); @@ -512,10 +506,10 @@ public void retriesExhausted() { subscriber.assertValueCount(responsesBeforeThrottle.size()); } - private DocumentClientException mockThrottlingException(long retriesAfter) { - DocumentClientException throttleException = mock(DocumentClientException.class); - doReturn(429).when(throttleException).getStatusCode(); - doReturn(retriesAfter).when(throttleException).getRetryAfterInMilliseconds(); + private CosmosClientException mockThrottlingException(long retriesAfter) { + CosmosClientException throttleException = mock(CosmosClientException.class); + doReturn(429).when(throttleException).statusCode(); + doReturn(retriesAfter).when(throttleException).retryAfterInMilliseconds(); return throttleException; } @@ -594,7 +588,7 @@ private List> mockFeedResponsesPartiallySorted(String par private int getLastValueInAsc(int initialValue, List> responsesList) { Integer value = null; for(FeedResponse page: responsesList) { - for(Document d: page.getResults()) { + for(Document d: page.results()) { Integer tmp = d.getInt(OrderByIntFieldName); if (tmp != null) { value = tmp; @@ -619,7 +613,7 @@ private IDocumentQueryClient mockQueryClient(List replacement private PartitionKeyRange mockPartitionKeyRange(String partitionKeyRangeId) { PartitionKeyRange pkr = Mockito.mock(PartitionKeyRange.class); - doReturn(partitionKeyRangeId).when(pkr).getId(); + doReturn(partitionKeyRangeId).when(pkr).id(); doReturn(partitionKeyRangeId + ":AA").when(pkr).getMinInclusive(); doReturn(partitionKeyRangeId + ":FF").when(pkr).getMaxExclusive(); return pkr; @@ -648,24 +642,24 @@ private static void validateSplitCaptureRequests( // numberOfResultPagesFromParentBeforeSplit + 1 requests to parent partition assertThat(capturedInvocationList.stream().limit(numberOfResultPagesFromParentBeforeSplit + 1) - .filter(i -> i.sourcePartition.getId().equals(parentPartitionId))) + .filter(i -> i.sourcePartition.id().equals(parentPartitionId))) .hasSize(numberOfResultPagesFromParentBeforeSplit + 1); assertThat(capturedInvocationList.stream().skip(numberOfResultPagesFromParentBeforeSplit + 1) - .filter(i -> i.sourcePartition.getId().equals(leftChildPartitionId))) + .filter(i -> i.sourcePartition.id().equals(leftChildPartitionId))) .hasSize(numberOfResultPagesFromLeftChildAfterSplit); assertThat(capturedInvocationList.stream().skip(numberOfResultPagesFromParentBeforeSplit + 1) - .filter(i -> i.sourcePartition.getId().equals(rightChildPartitionId))) + .filter(i -> i.sourcePartition.id().equals(rightChildPartitionId))) .hasSize(numberOfResultPagesFromRightChildAfterSplit); BiFunction, String, Stream> filterByPartition = (stream, partitionId) - -> stream.filter(i -> i.sourcePartition.getId().equals(partitionId)); + -> stream.filter(i -> i.sourcePartition.id().equals(partitionId)); Function>, Stream> extractContinuationToken = - (list) -> list.stream().map(p -> p.getResponseContinuation()); + (list) -> list.stream().map(p -> p.continuationToken()); assertThat(filterByPartition.apply(capturedInvocationList.stream(), parentPartitionId) .map(r -> r.continuationToken)).containsExactlyElementsOf( @@ -677,7 +671,7 @@ private static void validateSplitCaptureRequests( expectedResultPagesFromParentPartitionBeforeSplit.size() > 0 ? expectedResultPagesFromParentPartitionBeforeSplit.get( expectedResultPagesFromParentPartitionBeforeSplit.size() - 1) - .getResponseContinuation() :initialContinuationToken; + .continuationToken() :initialContinuationToken; assertThat( filterByPartition.andThen(s -> s.map(r -> r.continuationToken)) @@ -721,20 +715,20 @@ private static void sanityCheckSplitValidation(String parentPartitionId, assertThat(resultFromRightChild).hasSize(numberOfResultPagesFromRightChildAfterSplit); //validate expected result continuation token - assertThat(toList(resultFromParent.stream().map(p -> p.getResponseContinuation()) + assertThat(toList(resultFromParent.stream().map(p -> p.continuationToken()) .filter(cp -> Strings.isNullOrEmpty(cp)))).isEmpty(); - assertThat(toList(resultFromLeftChild.stream().map(p -> p.getResponseContinuation()) + assertThat(toList(resultFromLeftChild.stream().map(p -> p.continuationToken()) .limit(resultFromLeftChild.size() - 1) .filter(cp -> Strings.isNullOrEmpty(cp)))).isEmpty(); - assertThat(resultFromLeftChild.get(resultFromLeftChild.size() - 1).getResponseContinuation()).isNullOrEmpty(); + assertThat(resultFromLeftChild.get(resultFromLeftChild.size() - 1).continuationToken()).isNullOrEmpty(); - assertThat(toList(resultFromRightChild.stream().map(p -> p.getResponseContinuation()) + assertThat(toList(resultFromRightChild.stream().map(p -> p.continuationToken()) .limit(resultFromRightChild.size() - 1) .filter(cp -> Strings.isNullOrEmpty(cp)))).isEmpty(); - assertThat(resultFromRightChild.get(resultFromRightChild.size() - 1).getResponseContinuation()).isNullOrEmpty(); + assertThat(resultFromRightChild.get(resultFromRightChild.size() - 1).continuationToken()).isNullOrEmpty(); } private void validateSplitResults(List.DocumentProducerFeedResponse> actualPages, @@ -748,7 +742,7 @@ private void validateSplitResults(List.DocumentProduc if (isOrderby) { Supplier> getStreamOfActualDocuments = - () -> actualPages.stream().flatMap(p -> p.pageResult.getResults().stream()); + () -> actualPages.stream().flatMap(p -> p.pageResult.results().stream()); Comparator comparator = new Comparator() { @Override @@ -769,13 +763,13 @@ public int compare(Document o1, Document o2) { List expectedDocuments = Stream.concat(Stream.concat(resultFromParent.stream(), resultFromLeftChild.stream()), resultFromRightChild.stream()) - .flatMap(p -> p.getResults().stream()) + .flatMap(p -> p.results().stream()) .sorted(comparator) .collect(Collectors.toList()); - List actualDocuments = getStreamOfActualDocuments.get().map(d -> d.getId()).collect(Collectors.toList()); + List actualDocuments = getStreamOfActualDocuments.get().map(d -> d.id()).collect(Collectors.toList()); assertThat(actualDocuments) - .containsExactlyElementsOf(expectedDocuments.stream().map(d -> d.getId()).collect(Collectors.toList())); + .containsExactlyElementsOf(expectedDocuments.stream().map(d -> d.id()).collect(Collectors.toList())); } else { assertThat(actualPages).hasSize(resultFromParent.size() @@ -812,7 +806,7 @@ private static List toList(Stream stream) { } private static List partitionKeyRangeIds(List.DocumentProducerFeedResponse> responses) { - return responses.stream().map(dpFR -> dpFR.sourcePartitionKeyRange.getId()).collect(Collectors.toList()); + return responses.stream().map(dpFR -> dpFR.sourcePartitionKeyRange.id()).collect(Collectors.toList()); } private static void validateResults(List> captured, List>> expectedResponsesFromPartitions) { @@ -827,13 +821,13 @@ private static void validateResults(List> captured, List< } private static void assertEqual(FeedResponse actualPage, FeedResponse expectedPage) { - assertThat(actualPage.getResults()).hasSameSizeAs(actualPage.getResults()); - assertThat(actualPage.getResponseContinuation()).isEqualTo(expectedPage.getResponseContinuation()); + assertThat(actualPage.results()).hasSameSizeAs(actualPage.results()); + assertThat(actualPage.continuationToken()).isEqualTo(expectedPage.continuationToken()); - for(int i = 0; i < actualPage.getResults().size(); i++) { - Document actualDoc = actualPage.getResults().get(i); - Document expectedDoc = expectedPage.getResults().get(i); - assertThat(actualDoc.getId()).isEqualTo(expectedDoc.getId()); + for(int i = 0; i < actualPage.results().size(); i++) { + Document actualDoc = actualPage.results().get(i); + Document expectedDoc = expectedPage.results().get(i); + assertThat(actualDoc.id()).isEqualTo(expectedDoc.id()); assertThat(actualDoc.getString("prop")).isEqualTo(expectedDoc.getString("prop")); } } @@ -860,11 +854,11 @@ public CapturedInvocation(RxDocumentServiceRequest request, PartitionAnswer.Resp } } - private static DocumentClientException partitionKeyRangeGoneException() { + private static CosmosClientException partitionKeyRangeGoneException() { Map headers = new HashMap<>(); headers.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)); - return new DocumentClientException(HttpConstants.StatusCodes.GONE, new Error(), headers); + return new CosmosClientException(HttpConstants.StatusCodes.GONE, new Error(), headers); } protected void capture(String partitionId, CapturedInvocation captureInvocation) { @@ -1029,7 +1023,7 @@ public static RequestCreator simpleMock() { public RxDocumentServiceRequest call(PartitionKeyRange pkr, String cp, Integer ps) { synchronized (this) { RxDocumentServiceRequest req = Mockito.mock(RxDocumentServiceRequest.class); - PartitionKeyRangeIdentity pkri = new PartitionKeyRangeIdentity(pkr.getId()); + PartitionKeyRangeIdentity pkri = new PartitionKeyRangeIdentity(pkr.id()); doReturn(pkri).when(req).getPartitionKeyRangeIdentity(); doReturn(cp).when(req).getContinuation(); invocations.add(new CapturedInvocation(pkr, cp, ps, req)); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/query/FeedResponseBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java similarity index 89% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/query/FeedResponseBuilder.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java index 60be8309a2c60..d136b62fcd48c 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/query/FeedResponseBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java @@ -21,14 +21,13 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.BridgeUtils; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.HttpConstants; import java.util.Arrays; import java.util.HashMap; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/query/FetcherTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java similarity index 87% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/query/FetcherTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java index f81bda40d3eb1..84574f9261f54 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/internal/query/FetcherTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.internal.query; +package com.azure.data.cosmos.internal.query; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -30,15 +30,15 @@ import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedOptionsBase; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedOptionsBase; +import com.azure.data.cosmos.FeedResponse; import rx.Observable; import rx.functions.Func1; @@ -51,23 +51,23 @@ public class FetcherTest { public static Object[][] queryParamProvider() { FeedOptions options1 = new FeedOptions(); - options1.setMaxItemCount(100); - options1.setRequestContinuation("cp-init"); // initial continuation token + options1.maxItemCount(100); + options1.requestContinuation("cp-init"); // initial continuation token int top1 = -1; // no top // no continuation token FeedOptions options2 = new FeedOptions(); - options2.setMaxItemCount(100); + options2.maxItemCount(100); int top2 = -1; // no top // top more than max item count FeedOptions options3 = new FeedOptions(); - options3.setMaxItemCount(100); + options3.maxItemCount(100); int top3 = 200; // top less than max item count FeedOptions options4 = new FeedOptions(); - options4.setMaxItemCount(100); + options4.maxItemCount(100); int top4 = 20; return new Object[][] { @@ -110,13 +110,13 @@ public void query(FeedOptions options, int top) { Func1>> executeFunc = request -> { FeedResponse rsp = feedResponseList.get(executeIndex.getAndIncrement()); - totalResultsReceived.addAndGet(rsp.getResults().size()); + totalResultsReceived.addAndGet(rsp.results().size()); return Observable.just(rsp); }; Fetcher fetcher = new Fetcher<>(createRequestFunc, executeFunc, options, false, top, - options.getMaxItemCount()); + options.maxItemCount()); validateFetcher(fetcher, options, top, feedResponseList); } @@ -131,7 +131,7 @@ private void validateFetcher(Fetcher fetcher, int index = 0; while(index < feedResponseList.size()) { assertThat(fetcher.shouldFetchMore()).describedAs("should fetch more pages").isTrue(); - totalNumberOfDocs += validate(fetcher.nextPage()).getResults().size(); + totalNumberOfDocs += validate(fetcher.nextPage()).results().size(); if ((top != -1) && (totalNumberOfDocs >= top)) { break; @@ -145,7 +145,7 @@ private void validateFetcher(Fetcher fetcher, public void changeFeed() { ChangeFeedOptions options = new ChangeFeedOptions(); - options.setMaxItemCount(100); + options.maxItemCount(100); boolean isChangeFeed = true; int top = -1; @@ -165,7 +165,7 @@ public void changeFeed() { AtomicInteger requestIndex = new AtomicInteger(0); Func2 createRequestFunc = (token, maxItemCount) -> { - assertThat(maxItemCount).describedAs("max item count").isEqualTo(options.getMaxItemCount()); + assertThat(maxItemCount).describedAs("max item count").isEqualTo(options.maxItemCount()); assertThat(token).describedAs("continuation token").isEqualTo( getExpectedContinuationTokenInRequest(options, feedResponseList, requestIndex.getAndIncrement())); @@ -180,7 +180,7 @@ public void changeFeed() { Fetcher fetcher = new Fetcher<>(createRequestFunc, executeFunc, options, isChangeFeed, top, - options.getMaxItemCount()); + options.maxItemCount()); validateFetcher(fetcher, options, feedResponseList); } @@ -212,10 +212,10 @@ private String getExpectedContinuationTokenInRequest(FeedOptionsBase options, List> feedResponseList, int requestIndex) { if (requestIndex == 0) { - return options.getRequestContinuation(); + return options.requestContinuation(); } - return feedResponseList.get(requestIndex - 1).getResponseContinuation(); + return feedResponseList.get(requestIndex - 1).continuationToken(); } private int getExpectedMaxItemCountInRequest(FeedOptionsBase options, @@ -223,12 +223,12 @@ private int getExpectedMaxItemCountInRequest(FeedOptionsBase options, List> feedResponseList, int requestIndex) { if (top == -1) { - return options.getMaxItemCount(); + return options.maxItemCount(); } int numberOfReceivedItemsSoFar = - feedResponseList.subList(0, requestIndex).stream().mapToInt(rsp -> rsp.getResults().size()).sum(); + feedResponseList.subList(0, requestIndex).stream().mapToInt(rsp -> rsp.results().size()).sum(); - return Math.min(top - numberOfReceivedItemsSoFar, options.getMaxItemCount()); + return Math.min(top - numberOfReceivedItemsSoFar, options.maxItemCount()); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AggregateQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java similarity index 85% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AggregateQueryTests.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java index 2a3c7696d3f69..e2894511bdae4 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/AggregateQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java @@ -20,13 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.ArrayList; import java.util.UUID; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.directconnectivity.Protocol; import reactor.core.publisher.Flux; @@ -36,12 +37,11 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; public class AggregateQueryTests extends TestSuiteBase { @@ -70,7 +70,7 @@ public AggregateConfig(String operator, Object expected, String condition) { } private CosmosContainer createdCollection; - private ArrayList docs = new ArrayList(); + private ArrayList docs = new ArrayList(); private ArrayList queryConfigs = new ArrayList(); private String partitionKey = "mypk"; @@ -89,26 +89,26 @@ public AggregateQueryTests(CosmosClientBuilder clientBuilder) { } - // TODO: DANOBLE: Investigate Direct TCP performance issue + // TODO: DANOBLE: Investigate DIRECT TCP performance issue // Links: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 // Notes: // I've seen this test time out in my development environment. I test against a debug instance of the public // emulator and so what I'm seeing could be the result of a public emulator performance issue. Of course, it - // might also be the result of a Tcp protocol performance problem. + // might also be the result of a TCP protocol performance problem. @Test(groups = { "simple" }, timeOut = 2 * TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocumentsWithAggregates(boolean qmEnabled) throws Exception { FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setPopulateQueryMetrics(qmEnabled); - options.setMaxDegreeOfParallelism(2); + options.enableCrossPartitionQuery(true); + options.populateQueryMetrics(qmEnabled); + options.maxDegreeOfParallelism(2); for (QueryConfig queryConfig : queryConfigs) { - Flux> queryObservable = createdCollection.queryItems(queryConfig.query, options); + Flux> queryObservable = createdCollection.queryItems(queryConfig.query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .withAggregateValue(queryConfig.expected) .numberOfPages(1) .hasValidQueryMetrics(qmEnabled) @@ -117,8 +117,8 @@ public void queryDocumentsWithAggregates(boolean qmEnabled) throws Exception { try { validateQuerySuccess(queryObservable, validator); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -136,26 +136,26 @@ public void generateTestData() { Object[] values = new Object[]{null, false, true, "abc", "cdfg", "opqrs", "ttttttt", "xyz", "oo", "ppp"}; for (int i = 0; i < values.length; i++) { - CosmosItemSettings d = new CosmosItemSettings(); - d.setId(UUID.randomUUID().toString()); + CosmosItemProperties d = new CosmosItemProperties(); + d.id(UUID.randomUUID().toString()); d.set(partitionKey, values[i]); docs.add(d); } for (int i = 0; i < numberOfDocsWithSamePartitionKey; i++) { - CosmosItemSettings d = new CosmosItemSettings(); + CosmosItemProperties d = new CosmosItemProperties(); d.set(partitionKey, uniquePartitionKey); d.set("resourceId", Integer.toString(i)); d.set(field, i + 1); - d.setId(UUID.randomUUID().toString()); + d.id(UUID.randomUUID().toString()); docs.add(d); } numberOfDocumentsWithNumericId = numberOfDocuments - values.length - numberOfDocsWithSamePartitionKey; for (int i = 0; i < numberOfDocumentsWithNumericId; i++) { - CosmosItemSettings d = new CosmosItemSettings(); + CosmosItemProperties d = new CosmosItemProperties(); d.set(partitionKey, i + 1); - d.setId(UUID.randomUUID().toString()); + d.id(UUID.randomUUID().toString()); docs.add(d); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureCrossPartitionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java similarity index 77% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureCrossPartitionTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java index a8fc9f00ab9c2..ec3dc6f9038dd 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureCrossPartitionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java @@ -20,26 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; - -import com.microsoft.azure.cosmos.ClientUnderTestBuilder; -import com.microsoft.azure.cosmos.CosmosBridgeInternal; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.Index; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientUnderTest; +package com.azure.data.cosmos.rx; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.DataType; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.IncludedPath; +import com.azure.data.cosmos.Index; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.RxDocumentClientUnderTest; import io.reactivex.subscribers.TestSubscriber; import reactor.core.publisher.Flux; @@ -73,41 +65,41 @@ public class BackPressureCrossPartitionTest extends TestSuiteBase { private int numberOfDocs = 4000; private CosmosDatabase createdDatabase; private CosmosContainer createdCollection; - private List createdDocuments; + private List createdDocuments; private CosmosClient client; private int numberOfPartitions; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); + return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } static protected CosmosContainerSettings getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); + includedPath.path("/*"); Collection indexes = new ArrayList<>(); - Index stringIndex = Index.Range(DataType.String); + Index stringIndex = Index.Range(DataType.STRING); stringIndex.set("precision", -1); indexes.add(stringIndex); - Index numberIndex = Index.Range(DataType.Number); + Index numberIndex = Index.Range(DataType.NUMBER); numberIndex.set("precision", -1); indexes.add(numberIndex); - includedPath.setIndexes(indexes); + includedPath.indexes(indexes); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); CosmosContainerSettings collectionDefinition = new CosmosContainerSettings( UUID.randomUUID().toString(), partitionKeyDef); - collectionDefinition.setIndexingPolicy(indexingPolicy); + collectionDefinition.indexingPolicy(indexingPolicy); return collectionDefinition; } @@ -119,7 +111,7 @@ public BackPressureCrossPartitionTest(CosmosClientBuilder clientBuilder) { private void warmUp() { FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); // ensure collection is cached createdCollection.queryItems("SELECT * FROM r", options).blockFirst(); } @@ -137,22 +129,22 @@ public Object[][] queryProvider() { }; } - // TODO: DANOBLE: Investigate Direct TCP performance issue + // TODO: DANOBLE: Investigate DIRECT TCP performance issue // Links: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 @Test(groups = { "long" }, dataProvider = "queryProvider", timeOut = 2 * TIMEOUT) public void query(String query, int maxItemCount, int maxExpectedBufferedCountForBackPressure, int expectedNumberOfResults) throws Exception { FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setMaxItemCount(maxItemCount); - options.setMaxDegreeOfParallelism(2); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.enableCrossPartitionQuery(true); + options.maxItemCount(maxItemCount); + options.maxDegreeOfParallelism(2); + Flux> queryObservable = createdCollection.queryItems(query, options); RxDocumentClientUnderTest rxClient = (RxDocumentClientUnderTest)CosmosBridgeInternal.getAsyncDocumentClient(client); rxClient.httpRequests.clear(); log.info("instantiating subscriber ..."); - TestSubscriber> subscriber = new TestSubscriber<>(1); + TestSubscriber> subscriber = new TestSubscriber<>(1); queryObservable.publishOn(Schedulers.elastic()).subscribe(subscriber); int sleepTimeInMillis = 40000; int i = 0; @@ -182,8 +174,8 @@ public void query(String query, int maxItemCount, int maxExpectedBufferedCountFo i++; } } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -193,10 +185,10 @@ public void query(String query, int maxItemCount, int maxExpectedBufferedCountFo try { subscriber.assertNoErrors(); subscriber.assertComplete(); - assertThat(subscriber.values().stream().mapToInt(p -> p.getResults().size()).sum()).isEqualTo(expectedNumberOfResults); + assertThat(subscriber.values().stream().mapToInt(p -> p.results().size()).sum()).isEqualTo(expectedNumberOfResults); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -212,7 +204,7 @@ public void beforeClass() { createdDatabase = getSharedCosmosDatabase(client); createdCollection = createCollection(createdDatabase, getCollectionDefinition(), options); - ArrayList docDefList = new ArrayList<>(); + ArrayList docDefList = new ArrayList<>(); for(int i = 0; i < numberOfDocs; i++) { docDefList.add(getDocumentDefinition(i)); } @@ -222,13 +214,13 @@ public void beforeClass() { docDefList); numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client).readPartitionKeyRanges(getCollectionLink(), null) - .flatMap(p -> Observable.from(p.getResults())).toList().toBlocking().single().size(); + .flatMap(p -> Observable.from(p.results())).toList().toBlocking().single().size(); waitIfNeededForReplicasToCatchUp(clientBuilder); warmUp(); } - // TODO: DANOBLE: Investigate Direct TCP performance issue + // TODO: DANOBLE: Investigate DIRECT TCP performance issue // Links: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 @AfterClass(groups = { "long" }, timeOut = 2 * SHUTDOWN_TIMEOUT, alwaysRun = true) @@ -237,9 +229,9 @@ public void afterClass() { safeClose(client); } - private static CosmosItemSettings getDocumentDefinition(int cnt) { + private static CosmosItemProperties getDocumentDefinition(int cnt) { String uuid = UUID.randomUUID().toString(); - CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"prop\" : %d, " + "\"mypk\": \"%s\", " diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java similarity index 78% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java index 2ac124487fc5d..d6b765d5e5e22 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/BackPressureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java @@ -20,22 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; - -import com.microsoft.azure.cosmos.ClientUnderTestBuilder; -import com.microsoft.azure.cosmos.CosmosBridgeInternal; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.rx.internal.RxDocumentClientUnderTest; +package com.azure.data.cosmos.rx; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.internal.RxDocumentClientUnderTest; import io.reactivex.subscribers.TestSubscriber; import reactor.core.publisher.Flux; @@ -61,19 +54,19 @@ public class BackPressureTest extends TestSuiteBase { private CosmosDatabase createdDatabase; private CosmosContainer createdCollection; - private List createdDocuments; + private List createdDocuments; private CosmosClient client; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); + return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } private static CosmosContainerSettings getSinglePartitionCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; @@ -87,14 +80,14 @@ public BackPressureTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "long" }, timeOut = TIMEOUT) public void readFeed() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(1); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.listItems(options); + options.maxItemCount(1); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.listItems(options); RxDocumentClientUnderTest rxClient = (RxDocumentClientUnderTest)CosmosBridgeInternal.getAsyncDocumentClient(client); rxClient.httpRequests.clear(); - TestSubscriber> subscriber = new TestSubscriber>(1); + TestSubscriber> subscriber = new TestSubscriber>(1); queryObservable.publishOn(Schedulers.elastic()).subscribe(subscriber); int sleepTimeInMillis = 10000; // 10 seconds @@ -126,14 +119,14 @@ public void readFeed() throws Exception { @Test(groups = { "long" }, timeOut = TIMEOUT) public void query() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(1); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryItems("SELECT * from r", options); + options.maxItemCount(1); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems("SELECT * from r", options); RxDocumentClientUnderTest rxClient = (RxDocumentClientUnderTest)CosmosBridgeInternal.getAsyncDocumentClient(client); rxClient.httpRequests.clear(); - TestSubscriber> subscriber = new TestSubscriber>(1); + TestSubscriber> subscriber = new TestSubscriber>(1); queryObservable.publishOn(Schedulers.elastic()).subscribe(subscriber); int sleepTimeInMillis = 10000; @@ -162,7 +155,7 @@ public void query() throws Exception { assertThat(subscriber.getEvents().get(0)).hasSize(createdDocuments.size()); } - // TODO: DANOBLE: Investigate Direct TCP performance issue + // TODO: DANOBLE: Investigate DIRECT TCP performance issue // NOTE: This method requires multiple SHUTDOWN_TIMEOUT intervals // SEE: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 @@ -182,13 +175,13 @@ public void beforeClass() throws Exception { // for bulk insert and later queries. Offer offer = rxClient.queryOffers( String.format("SELECT * FROM r WHERE r.offerResourceId = '%s'", - createdCollection.read().block().getCosmosContainerSettings().getResourceId()) - , null).first().map(FeedResponse::getResults).toBlocking().single().get(0); + createdCollection.read().block().settings().resourceId()) + , null).first().map(FeedResponse::results).toBlocking().single().get(0); offer.setThroughput(6000); offer = rxClient.replaceOffer(offer).toBlocking().single().getResource(); assertThat(offer.getThroughput()).isEqualTo(6000); - ArrayList docDefList = new ArrayList<>(); + ArrayList docDefList = new ArrayList<>(); for(int i = 0; i < 1000; i++) { docDefList.add(getDocumentDefinition(i)); } @@ -202,11 +195,11 @@ public void beforeClass() throws Exception { private void warmUp() { // ensure collection is cached FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); createdCollection.queryItems("SELECT * from r", options).blockFirst(); } - // TODO: DANOBLE: Investigate Direct TCP performance issue + // TODO: DANOBLE: Investigate DIRECT TCP performance issue // NOTE: This method requires multiple SHUTDOWN_TIMEOUT intervals // SEE: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 @@ -216,9 +209,9 @@ public void afterClass() { safeClose(client); } - private static CosmosItemSettings getDocumentDefinition(int cnt) { + private static CosmosItemProperties getDocumentDefinition(int cnt) { String uuid = UUID.randomUUID().toString(); - CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"prop\" : %d, " + "\"mypk\": \"%s\", " diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ChangeFeedTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java similarity index 74% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ChangeFeedTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java index 2dadeb8bf6df6..edf677e98b7f7 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ChangeFeedTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java @@ -20,28 +20,30 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; +import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Collection; import java.time.ZonedDateTime; import java.util.List; import java.util.UUID; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; @@ -67,17 +69,17 @@ public class ChangeFeedTest extends TestSuiteBase { private AsyncDocumentClient client; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); + return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } static protected DocumentCollection getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/" + PartitionKeyFieldName); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); collectionDefinition.setPartitionKey(partitionKeyDef); return collectionDefinition; @@ -94,9 +96,9 @@ public void changeFeed_fromBeginning() throws Exception { Collection expectedDocuments = partitionKeyToDocuments.get(partitionKey); ChangeFeedOptions changeFeedOption = new ChangeFeedOptions(); - changeFeedOption.setMaxItemCount(3); - changeFeedOption.setPartitionKey(new PartitionKey(partitionKey)); - changeFeedOption.setStartFromBeginning(true); + changeFeedOption.maxItemCount(3); + changeFeedOption.partitionKey(new PartitionKey(partitionKey)); + changeFeedOption.startFromBeginning(true); List> changeFeedResultList = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) .toList().toBlocking().single(); @@ -104,12 +106,12 @@ public void changeFeed_fromBeginning() throws Exception { int count = 0; for(int i = 0; i < changeFeedResultList.size(); i++) { FeedResponse changeFeedPage = changeFeedResultList.get(i); - assertThat(changeFeedPage.getResponseContinuation()).as("Response continuation should not be null").isNotNull(); + assertThat(changeFeedPage.continuationToken()).as("Response continuation should not be null").isNotNull(); - count += changeFeedPage.getResults().size(); - assertThat(changeFeedPage.getResults().size()) + count += changeFeedPage.results().size(); + assertThat(changeFeedPage.results().size()) .as("change feed should contain all the previously created documents") - .isLessThanOrEqualTo(changeFeedOption.getMaxItemCount()); + .isLessThanOrEqualTo(changeFeedOption.maxItemCount()); } assertThat(count).as("the number of changes").isEqualTo(expectedDocuments.size()); } @@ -117,8 +119,8 @@ public void changeFeed_fromBeginning() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void changesFromPartitionKeyRangeId_FromBeginning() throws Exception { List partitionKeyRangeIds = client.readPartitionKeyRanges(getCollectionLink(), null) - .flatMap(p -> Observable.from(p.getResults()), 1) - .map(pkr -> pkr.getId()) + .flatMap(p -> Observable.from(p.results()), 1) + .map(pkr -> pkr.id()) .toList() .toBlocking() .single(); @@ -128,24 +130,24 @@ public void changesFromPartitionKeyRangeId_FromBeginning() throws Exception { String pkRangeId = partitionKeyRangeIds.get(0); ChangeFeedOptions changeFeedOption = new ChangeFeedOptions(); - changeFeedOption.setMaxItemCount(3); - changeFeedOption.setPartitionKeyRangeId(pkRangeId); - changeFeedOption.setStartFromBeginning(true); + changeFeedOption.maxItemCount(3); + changeFeedOption.partitionKeyRangeId(pkRangeId); + changeFeedOption.startFromBeginning(true); List> changeFeedResultList = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) .toList().toBlocking().single(); int count = 0; for(int i = 0; i < changeFeedResultList.size(); i++) { FeedResponse changeFeedPage = changeFeedResultList.get(i); - assertThat(changeFeedPage.getResponseContinuation()).as("Response continuation should not be null").isNotNull(); + assertThat(changeFeedPage.continuationToken()).as("Response continuation should not be null").isNotNull(); - count += changeFeedPage.getResults().size(); - assertThat(changeFeedPage.getResults().size()) + count += changeFeedPage.results().size(); + assertThat(changeFeedPage.results().size()) .as("change feed should contain all the previously created documents") - .isLessThanOrEqualTo(changeFeedOption.getMaxItemCount()); + .isLessThanOrEqualTo(changeFeedOption.maxItemCount()); - assertThat(changeFeedPage.getResponseContinuation()).as("Response continuation should not be null").isNotNull(); - assertThat(changeFeedPage.getResponseContinuation()).as("Response continuation should not be empty").isNotEmpty(); + assertThat(changeFeedPage.continuationToken()).as("Response continuation should not be null").isNotNull(); + assertThat(changeFeedPage.continuationToken()).as("Response continuation should not be empty").isNotEmpty(); } assertThat(changeFeedResultList.size()).as("has at least one page").isGreaterThanOrEqualTo(1); assertThat(count).as("the number of changes").isGreaterThan(0); @@ -154,10 +156,10 @@ public void changesFromPartitionKeyRangeId_FromBeginning() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void changeFeed_fromNow() throws Exception { - // Read change feed from current. + // READ change feed from current. ChangeFeedOptions changeFeedOption = new ChangeFeedOptions(); String partitionKey = partitionKeyToDocuments.keySet().iterator().next(); - changeFeedOption.setPartitionKey(new PartitionKey(partitionKey)); + changeFeedOption.partitionKey(new PartitionKey(partitionKey)); List> changeFeedResultsList = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) .toList() @@ -166,7 +168,7 @@ public void changeFeed_fromNow() throws Exception { FeedResponseListValidator validator = new FeedResponseListValidator.Builder().totalSize(0).build(); validator.validate(changeFeedResultsList); assertThat(changeFeedResultsList.get(changeFeedResultsList.size() -1 ). - getResponseContinuation()).as("Response continuation should not be null").isNotNull(); + continuationToken()).as("Response continuation should not be null").isNotNull(); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -177,17 +179,17 @@ public void changeFeed_fromStartDate() throws Exception { throw new SkipException("StartTime/IfModifiedSince is not currently supported when EnableMultipleWriteLocations is set"); } - // Read change feed from current. + // READ change feed from current. ChangeFeedOptions changeFeedOption = new ChangeFeedOptions(); String partitionKey = partitionKeyToDocuments.keySet().iterator().next(); - changeFeedOption.setPartitionKey(new PartitionKey(partitionKey)); - ZonedDateTime befTime = ZonedDateTime.now(); + changeFeedOption.partitionKey(new PartitionKey(partitionKey)); + OffsetDateTime befTime = OffsetDateTime.now(); // Waiting for at-least a second to ensure that new document is created after we took the time stamp waitAtleastASecond(befTime); - ZonedDateTime dateTimeBeforeCreatingDoc = ZonedDateTime.now(); - changeFeedOption.setStartDateTime(dateTimeBeforeCreatingDoc); + OffsetDateTime dateTimeBeforeCreatingDoc = OffsetDateTime.now(); + changeFeedOption.startDateTime(dateTimeBeforeCreatingDoc); // Waiting for at-least a second to ensure that new document is created after we took the time stamp waitAtleastASecond(dateTimeBeforeCreatingDoc); @@ -200,8 +202,8 @@ public void changeFeed_fromStartDate() throws Exception { int count = 0; for(int i = 0; i < changeFeedResultList.size(); i++) { FeedResponse changeFeedPage = changeFeedResultList.get(i); - count += changeFeedPage.getResults().size(); - assertThat(changeFeedPage.getResponseContinuation()).as("Response continuation should not be null").isNotNull(); + count += changeFeedPage.results().size(); + assertThat(changeFeedPage.continuationToken()).as("Response continuation should not be null").isNotNull(); } assertThat(count).as("Change feed should have one newly created document").isEqualTo(1); } @@ -209,17 +211,17 @@ public void changeFeed_fromStartDate() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void changesFromPartitionKey_AfterInsertingNewDocuments() throws Exception { ChangeFeedOptions changeFeedOption = new ChangeFeedOptions(); - changeFeedOption.setMaxItemCount(3); + changeFeedOption.maxItemCount(3); String partitionKey = partitionKeyToDocuments.keySet().iterator().next(); - changeFeedOption.setPartitionKey(new PartitionKey(partitionKey)); + changeFeedOption.partitionKey(new PartitionKey(partitionKey)); List> changeFeedResultsList = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) .toList().toBlocking().single(); assertThat(changeFeedResultsList).as("only one page").hasSize(1); - assertThat(changeFeedResultsList.get(0).getResults()).as("no recent changes").isEmpty(); + assertThat(changeFeedResultsList.get(0).results()).as("no recent changes").isEmpty(); - String changeFeedContinuation = changeFeedResultsList.get(changeFeedResultsList.size()-1).getResponseContinuation(); + String changeFeedContinuation = changeFeedResultsList.get(changeFeedResultsList.size()-1).continuationToken(); assertThat(changeFeedContinuation).as("continuation token is not null").isNotNull(); assertThat(changeFeedContinuation).as("continuation token is not empty").isNotEmpty(); @@ -227,15 +229,15 @@ public void changesFromPartitionKey_AfterInsertingNewDocuments() throws Exceptio client.createDocument(getCollectionLink(), getDocumentDefinition(partitionKey), null, true).toBlocking().single(); client.createDocument(getCollectionLink(), getDocumentDefinition(partitionKey), null, true).toBlocking().single(); - // Read change feed from continuation - changeFeedOption.setRequestContinuation(changeFeedContinuation); + // READ change feed from continuation + changeFeedOption.requestContinuation(changeFeedContinuation); FeedResponse changeFeedResults2 = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) .toBlocking().first(); - assertThat(changeFeedResults2.getResults()).as("change feed should contain newly inserted docs.").hasSize(2); - assertThat(changeFeedResults2.getResponseContinuation()).as("Response continuation should not be null").isNotNull(); + assertThat(changeFeedResults2.results()).as("change feed should contain newly inserted docs.").hasSize(2); + assertThat(changeFeedResults2.continuationToken()).as("Response continuation should not be null").isNotNull(); } public void createDocument(AsyncDocumentClient client, String partitionKey) { @@ -249,7 +251,7 @@ public void createDocument(AsyncDocumentClient client, String partitionKey) { public List bulkInsert(AsyncDocumentClient client, List docs) { ArrayList>> result = new ArrayList>>(); for (int i = 0; i < docs.size(); i++) { - result.add(client.createDocument("dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(), docs.get(i), null, false)); + result.add(client.createDocument("dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(), docs.get(i), null, false)); } return Observable.merge(result, 100).map(r -> r.getResource()).toList().toBlocking().single(); @@ -269,7 +271,7 @@ public void populateDocuments(Method method) { RequestOptions options = new RequestOptions(); options.setOfferThroughput(10100); - createdCollection = createCollection(client, createdDatabase.getId(), getCollectionDefinition(), options); + createdCollection = createCollection(client, createdDatabase.id(), getCollectionDefinition(), options); List docs = new ArrayList<>(); @@ -301,14 +303,14 @@ public void afterClass() { private static Document getDocumentDefinition(String partitionKey) { String uuid = UUID.randomUUID().toString(); Document doc = new Document(); - doc.setId(uuid); + doc.id(uuid); doc.set("mypk", partitionKey); doc.set("prop", uuid); return doc; } - private static void waitAtleastASecond(ZonedDateTime befTime) throws InterruptedException { - while (befTime.plusSeconds(1).isAfter(ZonedDateTime.now())) { + private static void waitAtleastASecond(OffsetDateTime befTime) throws InterruptedException { + while (befTime.plusSeconds(1).isAfter(OffsetDateTime.now())) { Thread.sleep(100); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java similarity index 71% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java index 6ed1c702cf7dc..bb47411351686 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java @@ -1,333 +1,322 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.UUID; - -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.RetryAnalyzer; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerResponse; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemResponse; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import com.microsoft.azure.cosmosdb.CompositePath; -import com.microsoft.azure.cosmosdb.CompositePathSortOrder; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.IndexingMode; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.SpatialSpec; -import com.microsoft.azure.cosmosdb.SpatialType; - -import reactor.core.publisher.Mono; - -public class CollectionCrudTest extends TestSuiteBase { - private static final int TIMEOUT = 50000; - private static final int SETUP_TIMEOUT = 20000; - private static final int SHUTDOWN_TIMEOUT = 20000; - private final String databaseId = CosmosDatabaseForTest.generateId(); - - private CosmosClient client; - private CosmosDatabase database; - - @Factory(dataProvider = "clientBuildersWithDirect") - public CollectionCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; - this.subscriberValidationTimeout = TIMEOUT; - } - - @DataProvider(name = "collectionCrudArgProvider") - public Object[][] collectionCrudArgProvider() { - return new Object[][] { - // collection name, is name base - {UUID.randomUUID().toString()} , - - // with special characters in the name. - {"+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~"} , - }; - } - - private CosmosContainerSettings getCollectionDefinition(String collectionName) { - PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); - ArrayList paths = new ArrayList(); - paths.add("/mypk"); - partitionKeyDef.setPaths(paths); - - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings( - collectionName, - partitionKeyDef); - - return collectionDefinition; - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void createCollection(String collectionName) throws InterruptedException { - CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); - - Mono createObservable = database - .createContainer(collectionDefinition); - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(collectionDefinition.getId()).build(); - - validateSuccess(createObservable, validator); - safeDeleteAllCollections(database); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT) - public void createCollectionWithCompositeIndexAndSpatialSpec() throws InterruptedException { - PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); - ArrayList paths = new ArrayList(); - paths.add("/mypk"); - partitionKeyDef.setPaths(paths); - - CosmosContainerSettings collection = new CosmosContainerSettings( - UUID.randomUUID().toString(), - partitionKeyDef); - - IndexingPolicy indexingPolicy = new IndexingPolicy(); - CompositePath compositePath1 = new CompositePath(); - compositePath1.setPath("/path1"); - compositePath1.setOrder(CompositePathSortOrder.Ascending); - CompositePath compositePath2 = new CompositePath(); - compositePath2.setPath("/path2"); - compositePath2.setOrder(CompositePathSortOrder.Descending); - CompositePath compositePath3 = new CompositePath(); - compositePath3.setPath("/path3"); - CompositePath compositePath4 = new CompositePath(); - compositePath4.setPath("/path4"); - compositePath4.setOrder(CompositePathSortOrder.Ascending); - CompositePath compositePath5 = new CompositePath(); - compositePath5.setPath("/path5"); - compositePath5.setOrder(CompositePathSortOrder.Descending); - CompositePath compositePath6 = new CompositePath(); - compositePath6.setPath("/path6"); - - ArrayList compositeIndex1 = new ArrayList(); - compositeIndex1.add(compositePath1); - compositeIndex1.add(compositePath2); - compositeIndex1.add(compositePath3); - - ArrayList compositeIndex2 = new ArrayList(); - compositeIndex2.add(compositePath4); - compositeIndex2.add(compositePath5); - compositeIndex2.add(compositePath6); - - Collection> compositeIndexes = new ArrayList>(); - compositeIndexes.add(compositeIndex1); - compositeIndexes.add(compositeIndex2); - indexingPolicy.setCompositeIndexes(compositeIndexes); - - SpatialType[] spatialTypes = new SpatialType[] { - SpatialType.Point, - SpatialType.LineString, - SpatialType.Polygon, - SpatialType.MultiPolygon - }; - Collection spatialIndexes = new ArrayList(); - for (int index = 0; index < 2; index++) { - Collection collectionOfSpatialTypes = new ArrayList(); - - SpatialSpec spec = new SpatialSpec(); - spec.setPath("/path" + index + "/*"); - - for (int i = index; i < index + 3; i++) { - collectionOfSpatialTypes.add(spatialTypes[i]); - } - spec.setSpatialTypes(collectionOfSpatialTypes); - spatialIndexes.add(spec); - } - - indexingPolicy.setSpatialIndexes(spatialIndexes); - - collection.setIndexingPolicy(indexingPolicy); - - Mono createObservable = database - .createContainer(collection, new CosmosContainerRequestOptions()); - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(collection.getId()) - .withCompositeIndexes(compositeIndexes) - .withSpatialIndexes(spatialIndexes) - .build(); - - validateSuccess(createObservable, validator); - safeDeleteAllCollections(database); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void readCollection(String collectionName) throws InterruptedException { - CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); - - Mono createObservable = database.createContainer(collectionDefinition); - CosmosContainer collection = createObservable.block().getContainer(); - - Mono readObservable = collection.read(); - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(collection.getId()).build(); - validateSuccess(readObservable, validator); - safeDeleteAllCollections(database); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void readCollection_DoesntExist(String collectionName) throws Exception { - - Mono readObservable = database - .getContainer("I don't exist").read(); - - FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(readObservable, validator); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void deleteCollection(String collectionName) throws InterruptedException { - CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); - - Mono createObservable = database.createContainer(collectionDefinition); - CosmosContainer collection = createObservable.block().getContainer(); - - Mono deleteObservable = collection.delete(); - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .nullResource().build(); - validateSuccess(deleteObservable, validator); - } - - @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") - public void replaceCollection(String collectionName) throws InterruptedException { - // create a collection - CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); - Mono createObservable = database.createContainer(collectionDefinition); - CosmosContainer collection = createObservable.block().getContainer(); - CosmosContainerSettings collectionSettings = collection.read().block().getCosmosContainerSettings(); - // sanity check - assertThat(collectionSettings.getIndexingPolicy().getIndexingMode()).isEqualTo(IndexingMode.Consistent); - - // replace indexing mode - IndexingPolicy indexingMode = new IndexingPolicy(); - indexingMode.setIndexingMode(IndexingMode.Lazy); - collectionSettings.setIndexingPolicy(indexingMode); - Mono readObservable = collection.replace(collectionSettings, new CosmosContainerRequestOptions()); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .indexingMode(IndexingMode.Lazy).build(); - validateSuccess(readObservable, validator); - safeDeleteAllCollections(database); - } - - @Test(groups = { "emulator" }, timeOut = 10 * TIMEOUT, retryAnalyzer = RetryAnalyzer.class) - public void sessionTokenConsistencyCollectionDeleteCreateSameName() { - CosmosClient client1 = clientBuilder.build(); - CosmosClient client2 = clientBuilder.build(); - - String dbId = CosmosDatabaseForTest.generateId(); - String collectionId = "coll"; - CosmosDatabase db = null; - try { - Database databaseDefinition = new Database(); - databaseDefinition.setId(dbId); - db = createDatabase(client1, dbId); - - PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); - ArrayList paths = new ArrayList(); - paths.add("/mypk"); - partitionKeyDef.setPaths(paths); - - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(collectionId, partitionKeyDef); - CosmosContainer collection = createCollection(db, collectionDefinition, new CosmosContainerRequestOptions()); - - CosmosItemSettings document = new CosmosItemSettings(); - document.setId("doc"); - document.set("name", "New Document"); - document.set("mypk", "mypkValue"); - CosmosItem item = createDocument(collection, document); - CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(new PartitionKey("mypkValue")); - CosmosItemResponse readDocumentResponse = item.read(options).block(); - logger.info("Client 1 Read Document Client Side Request Statistics {}", readDocumentResponse.getRequestDiagnosticsString()); - logger.info("Client 1 Read Document Latency {}", readDocumentResponse.getRequestLatency()); - - document.set("name", "New Updated Document"); - CosmosItemResponse upsertDocumentResponse = collection.upsertItem(document).block(); - logger.info("Client 1 Upsert Document Client Side Request Statistics {}", upsertDocumentResponse.getRequestDiagnosticsString()); - logger.info("Client 1 Upsert Document Latency {}", upsertDocumentResponse.getRequestLatency()); - - // Delete the existing collection - deleteCollection(client2, dbId, collectionId); - // Recreate the collection with the same name but with different client - CosmosContainer collection2 = createCollection(client2, dbId, collectionDefinition); - - CosmosItemSettings newDocument = new CosmosItemSettings(); - newDocument.setId("doc"); - newDocument.set("name", "New Created Document"); - newDocument.set("mypk", "mypk"); - createDocument(collection2, newDocument); - - readDocumentResponse = client1.getDatabase(dbId).getContainer(collectionId).getItem(newDocument.getId(), newDocument.get("mypk")).read().block(); - logger.info("Client 2 Read Document Client Side Request Statistics {}", readDocumentResponse.getRequestDiagnosticsString()); - logger.info("Client 2 Read Document Latency {}", readDocumentResponse.getRequestLatency()); - - CosmosItemSettings readDocument = readDocumentResponse.getCosmosItemSettings(); - - assertThat(readDocument.getId().equals(newDocument.getId())).isTrue(); - assertThat(readDocument.get("name").equals(newDocument.get("name"))).isTrue(); - } finally { - safeDeleteDatabase(db); - safeClose(client1); - safeClose(client2); - } - } - - @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - client = clientBuilder.build(); - database = createDatabase(client, databaseId); - } - - @AfterClass(groups = { "emulator" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeDeleteDatabase(database); - safeClose(client); - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.rx; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RetryAnalyzer; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +import com.azure.data.cosmos.CompositePath; +import com.azure.data.cosmos.CompositePathSortOrder; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.IndexingMode; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.SpatialSpec; +import com.azure.data.cosmos.SpatialType; + +import reactor.core.publisher.Mono; + +public class CollectionCrudTest extends TestSuiteBase { + private static final int TIMEOUT = 50000; + private static final int SETUP_TIMEOUT = 20000; + private static final int SHUTDOWN_TIMEOUT = 20000; + private final String databaseId = CosmosDatabaseForTest.generateId(); + + private CosmosClient client; + private CosmosDatabase database; + + @Factory(dataProvider = "clientBuildersWithDirect") + public CollectionCrudTest(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; + this.subscriberValidationTimeout = TIMEOUT; + } + + @DataProvider(name = "collectionCrudArgProvider") + public Object[][] collectionCrudArgProvider() { + return new Object[][] { + // collection name, is name base + {UUID.randomUUID().toString()} , + + // with special characters in the name. + {"+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~"} , + }; + } + + private CosmosContainerSettings getCollectionDefinition(String collectionName) { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.paths(paths); + + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings( + collectionName, + partitionKeyDef); + + return collectionDefinition; + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") + public void createCollection(String collectionName) throws InterruptedException { + CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + + Mono createObservable = database + .createContainer(collectionDefinition); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(collectionDefinition.id()).build(); + + validateSuccess(createObservable, validator); + safeDeleteAllCollections(database); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT) + public void createCollectionWithCompositeIndexAndSpatialSpec() throws InterruptedException { + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.paths(paths); + + CosmosContainerSettings collection = new CosmosContainerSettings( + UUID.randomUUID().toString(), + partitionKeyDef); + + IndexingPolicy indexingPolicy = new IndexingPolicy(); + CompositePath compositePath1 = new CompositePath(); + compositePath1.path("/path1"); + compositePath1.order(CompositePathSortOrder.ASCENDING); + CompositePath compositePath2 = new CompositePath(); + compositePath2.path("/path2"); + compositePath2.order(CompositePathSortOrder.DESCENDING); + CompositePath compositePath3 = new CompositePath(); + compositePath3.path("/path3"); + CompositePath compositePath4 = new CompositePath(); + compositePath4.path("/path4"); + compositePath4.order(CompositePathSortOrder.ASCENDING); + CompositePath compositePath5 = new CompositePath(); + compositePath5.path("/path5"); + compositePath5.order(CompositePathSortOrder.DESCENDING); + CompositePath compositePath6 = new CompositePath(); + compositePath6.path("/path6"); + + ArrayList compositeIndex1 = new ArrayList(); + compositeIndex1.add(compositePath1); + compositeIndex1.add(compositePath2); + compositeIndex1.add(compositePath3); + + ArrayList compositeIndex2 = new ArrayList(); + compositeIndex2.add(compositePath4); + compositeIndex2.add(compositePath5); + compositeIndex2.add(compositePath6); + + Collection> compositeIndexes = new ArrayList>(); + compositeIndexes.add(compositeIndex1); + compositeIndexes.add(compositeIndex2); + indexingPolicy.compositeIndexes(compositeIndexes); + + SpatialType[] spatialTypes = new SpatialType[] { + SpatialType.POINT, + SpatialType.LINE_STRING, + SpatialType.POLYGON, + SpatialType.MULTI_POLYGON + }; + Collection spatialIndexes = new ArrayList(); + for (int index = 0; index < 2; index++) { + Collection collectionOfSpatialTypes = new ArrayList(); + + SpatialSpec spec = new SpatialSpec(); + spec.path("/path" + index + "/*"); + + for (int i = index; i < index + 3; i++) { + collectionOfSpatialTypes.add(spatialTypes[i]); + } + spec.spatialTypes(collectionOfSpatialTypes); + spatialIndexes.add(spec); + } + + indexingPolicy.spatialIndexes(spatialIndexes); + + collection.indexingPolicy(indexingPolicy); + + Mono createObservable = database + .createContainer(collection, new CosmosContainerRequestOptions()); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(collection.id()) + .withCompositeIndexes(compositeIndexes) + .withSpatialIndexes(spatialIndexes) + .build(); + + validateSuccess(createObservable, validator); + safeDeleteAllCollections(database); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") + public void readCollection(String collectionName) throws InterruptedException { + CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + + Mono createObservable = database.createContainer(collectionDefinition); + CosmosContainer collection = createObservable.block().container(); + + Mono readObservable = collection.read(); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(collection.id()).build(); + validateSuccess(readObservable, validator); + safeDeleteAllCollections(database); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") + public void readCollection_DoesntExist(String collectionName) throws Exception { + + Mono readObservable = database + .getContainer("I don't exist").read(); + + FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(readObservable, validator); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") + public void deleteCollection(String collectionName) throws InterruptedException { + CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + + Mono createObservable = database.createContainer(collectionDefinition); + CosmosContainer collection = createObservable.block().container(); + + Mono deleteObservable = collection.delete(); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteObservable, validator); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") + public void replaceCollection(String collectionName) throws InterruptedException { + // create a collection + CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + Mono createObservable = database.createContainer(collectionDefinition); + CosmosContainer collection = createObservable.block().container(); + CosmosContainerSettings collectionSettings = collection.read().block().settings(); + // sanity check + assertThat(collectionSettings.indexingPolicy().indexingMode()).isEqualTo(IndexingMode.CONSISTENT); + + // replace indexing mode + IndexingPolicy indexingMode = new IndexingPolicy(); + indexingMode.indexingMode(IndexingMode.LAZY); + collectionSettings.indexingPolicy(indexingMode); + Mono readObservable = collection.replace(collectionSettings, new CosmosContainerRequestOptions()); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .indexingMode(IndexingMode.LAZY).build(); + validateSuccess(readObservable, validator); + safeDeleteAllCollections(database); + } + + @Test(groups = { "emulator" }, timeOut = 10 * TIMEOUT, retryAnalyzer = RetryAnalyzer.class) + public void sessionTokenConsistencyCollectionDeleteCreateSameName() { + CosmosClient client1 = clientBuilder.build(); + CosmosClient client2 = clientBuilder.build(); + + String dbId = CosmosDatabaseForTest.generateId(); + String collectionId = "coll"; + CosmosDatabase db = null; + try { + Database databaseDefinition = new Database(); + databaseDefinition.id(dbId); + db = createDatabase(client1, dbId); + + PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.paths(paths); + + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(collectionId, partitionKeyDef); + CosmosContainer collection = createCollection(db, collectionDefinition, new CosmosContainerRequestOptions()); + + CosmosItemProperties document = new CosmosItemProperties(); + document.id("doc"); + document.set("name", "New Document"); + document.set("mypk", "mypkValue"); + CosmosItem item = createDocument(collection, document); + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.partitionKey(new PartitionKey("mypkValue")); + CosmosItemResponse readDocumentResponse = item.read(options).block(); + logger.info("Client 1 READ Document Client Side Request Statistics {}", readDocumentResponse.requestDiagnosticsString()); + logger.info("Client 1 READ Document Latency {}", readDocumentResponse.requestLatency()); + + document.set("name", "New Updated Document"); + CosmosItemResponse upsertDocumentResponse = collection.upsertItem(document).block(); + logger.info("Client 1 Upsert Document Client Side Request Statistics {}", upsertDocumentResponse.requestDiagnosticsString()); + logger.info("Client 1 Upsert Document Latency {}", upsertDocumentResponse.requestLatency()); + + // DELETE the existing collection + deleteCollection(client2, dbId, collectionId); + // Recreate the collection with the same name but with different client + CosmosContainer collection2 = createCollection(client2, dbId, collectionDefinition); + + CosmosItemProperties newDocument = new CosmosItemProperties(); + newDocument.id("doc"); + newDocument.set("name", "New Created Document"); + newDocument.set("mypk", "mypk"); + createDocument(collection2, newDocument); + + readDocumentResponse = client1.getDatabase(dbId).getContainer(collectionId).getItem(newDocument.id(), newDocument.get("mypk")).read().block(); + logger.info("Client 2 READ Document Client Side Request Statistics {}", readDocumentResponse.requestDiagnosticsString()); + logger.info("Client 2 READ Document Latency {}", readDocumentResponse.requestLatency()); + + CosmosItemProperties readDocument = readDocumentResponse.properties(); + + assertThat(readDocument.id().equals(newDocument.id())).isTrue(); + assertThat(readDocument.get("name").equals(newDocument.get("name"))).isTrue(); + } finally { + safeDeleteDatabase(db); + safeClose(client1); + safeClose(client2); + } + } + + @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) + public void beforeClass() { + client = clientBuilder.build(); + database = createDatabase(client, databaseId); + } + + @AfterClass(groups = { "emulator" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeDeleteDatabase(database); + safeClose(client); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java similarity index 84% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java index dff6d520b0dcf..cac8f90459c41 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/CollectionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -29,21 +29,21 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyDefinition; import reactor.core.publisher.Flux; @@ -63,23 +63,23 @@ public CollectionQueryTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryCollectionsWithFilter() throws Exception { - String filterCollectionId = createdCollections.get(0).getId(); + String filterCollectionId = createdCollections.get(0).id(); String query = String.format("SELECT * from c where c.id = '%s'", filterCollectionId); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Flux> queryObservable = createdDatabase.queryContainers(query, options); List expectedCollections = createdCollections.stream() - .filter(c -> StringUtils.equals(filterCollectionId, c.getId()) ).collect(Collectors.toList()); + .filter(c -> StringUtils.equals(filterCollectionId, c.id()) ).collect(Collectors.toList()); assertThat(expectedCollections).isNotEmpty(); - int expectedPageSize = (expectedCollections.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedCollections.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedCollections.size()) - .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.read().block().getCosmosContainerSettings().getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.read().block().settings().resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -94,18 +94,18 @@ public void queryAllCollections() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Flux> queryObservable = createdDatabase.queryContainers(query, options); List expectedCollections = createdCollections; assertThat(expectedCollections).isNotEmpty(); - int expectedPageSize = (expectedCollections.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedCollections.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedCollections.size()) - .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.read().block().getCosmosContainerSettings().getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.read().block().settings().resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -119,7 +119,7 @@ public void queryCollections_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); Flux> queryObservable = createdDatabase.queryContainers(query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() @@ -139,7 +139,7 @@ public void beforeClass() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); createdCollections.add(createCollection(client, databaseId, collection)); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java similarity index 88% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java index 01f4b02193868..8c1d6dbbff134 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java @@ -20,21 +20,21 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseRequestOptions; -import com.microsoft.azure.cosmos.CosmosDatabaseResponse; -import com.microsoft.azure.cosmos.CosmosDatabaseSettings; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseRequestOptions; +import com.azure.data.cosmos.CosmosDatabaseResponse; +import com.azure.data.cosmos.CosmosDatabaseSettings; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosDatabaseForTest; import reactor.core.publisher.Mono; @@ -55,21 +55,21 @@ public DatabaseCrudTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void createDatabase() throws Exception { CosmosDatabaseSettings databaseDefinition = new CosmosDatabaseSettings(CosmosDatabaseForTest.generateId()); - databases.add(databaseDefinition.getId()); + databases.add(databaseDefinition.id()); // create the database Mono createObservable = client.createDatabase(databaseDefinition, new CosmosDatabaseRequestOptions()); // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(databaseDefinition.getId()).build(); + .withId(databaseDefinition.id()).build(); validateSuccess(createObservable, validator); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void createDatabase_AlreadyExists() throws Exception { CosmosDatabaseSettings databaseDefinition = new CosmosDatabaseSettings(CosmosDatabaseForTest.generateId()); - databases.add(databaseDefinition.getId()); + databases.add(databaseDefinition.id()); client.createDatabase(databaseDefinition, new CosmosDatabaseRequestOptions()).block(); @@ -107,8 +107,8 @@ public void readDatabase_DoesntExist() throws Exception { public void deleteDatabase() throws Exception { // create the database CosmosDatabaseSettings databaseDefinition = new CosmosDatabaseSettings(CosmosDatabaseForTest.generateId()); - databases.add(databaseDefinition.getId()); - CosmosDatabase database = client.createDatabase(databaseDefinition, new CosmosDatabaseRequestOptions()).block().getDatabase(); + databases.add(databaseDefinition.id()); + CosmosDatabase database = client.createDatabase(databaseDefinition, new CosmosDatabaseRequestOptions()).block().database(); // delete the database Mono deleteObservable = database.delete(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java similarity index 84% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java index 6a399ba68206d..52142bf840670 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DatabaseQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -28,19 +28,19 @@ import java.util.List; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseSettings; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseSettings; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Flux; @@ -63,19 +63,19 @@ public void queryDatabaseWithFilter() throws Exception { String query = String.format("SELECT * from c where c.id = '%s'", databaseId1); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Flux> queryObservable = client.queryDatabases(query, options); List expectedDatabases = createdDatabases.stream() - .filter(d -> StringUtils.equals(databaseId1, d.getId()) ).map(d -> d.read().block().getCosmosDatabaseSettings()).collect(Collectors.toList()); + .filter(d -> StringUtils.equals(databaseId1, d.id()) ).map(d -> d.read().block().settings()).collect(Collectors.toList()); assertThat(expectedDatabases).isNotEmpty(); - int expectedPageSize = (expectedDatabases.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDatabases.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDatabases.size()) - .exactlyContainsInAnyOrder(expectedDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedDatabases.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -92,18 +92,18 @@ public void queryAllDatabase() throws Exception { databaseId2); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Flux> queryObservable = client.queryDatabases(query, options); - List expectedDatabases = createdDatabases.stream().map(d -> d.read().block().getCosmosDatabaseSettings()).collect(Collectors.toList()); + List expectedDatabases = createdDatabases.stream().map(d -> d.read().block().settings()).collect(Collectors.toList()); assertThat(expectedDatabases).isNotEmpty(); - int expectedPageSize = (expectedDatabases.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDatabases.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDatabases.size()) - .exactlyContainsInAnyOrder(expectedDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedDatabases.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -117,7 +117,7 @@ public void queryDatabases_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); Flux> queryObservable = client.queryDatabases(query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentClientResourceLeakTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java similarity index 85% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentClientResourceLeakTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java index 333f0c148500f..ef0c4bb840605 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentClientResourceLeakTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java @@ -20,14 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.directconnectivity.Protocol; import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -45,7 +41,7 @@ public class DocumentClientResourceLeakTest extends TestSuiteBase { private CosmosClientBuilder clientBuilder; private CosmosClient client; - private CosmosDatabase createdDatabase; + private CosmosDatabase createdDatabase; private CosmosContainer createdCollection; @Factory(dataProvider = "simpleClientBuildersWithDirect") @@ -57,7 +53,7 @@ public DocumentClientResourceLeakTest(CosmosClientBuilder clientBuilder) { @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void resourceLeak() throws Exception { //TODO FIXME DANOBLE this test doesn't pass on RNTBD - if (clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { + if (clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { throw new SkipException("RNTBD"); } System.gc(); @@ -70,7 +66,7 @@ public void resourceLeak() throws Exception { logger.info("client {}", i); try { logger.info("creating doc..."); - createDocument(client.getDatabase(createdDatabase.getId()).getContainer(createdCollection.getId()), getDocumentDefinition()); + createDocument(client.getDatabase(createdDatabase.id()).getContainer(createdCollection.id()), getDocumentDefinition()); } finally { logger.info("closing client..."); client.close(); @@ -90,9 +86,9 @@ public void beforeClass() { createdCollection = getSharedMultiPartitionCosmosContainer(client); } - private CosmosItemSettings getDocumentDefinition() { + private CosmosItemProperties getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java similarity index 77% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java index 7ac50af7f425b..b926867c74bfc 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/DocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java @@ -1,395 +1,388 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx; - -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemResponse; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; - -import reactor.core.publisher.Mono; - -import org.apache.commons.lang3.StringUtils; -import org.testng.SkipException; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import java.time.Duration; -import java.time.OffsetDateTime; -import java.util.UUID; -import java.util.concurrent.TimeoutException; - -import static org.apache.commons.io.FileUtils.ONE_MB; -import static org.assertj.core.api.Assertions.assertThat; - -public class DocumentCrudTest extends TestSuiteBase { - - private CosmosContainer createdCollection; - - private CosmosClient client; - - @Factory(dataProvider = "clientBuildersWithDirect") - public DocumentCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; - } - - @DataProvider(name = "documentCrudArgProvider") - public Object[][] documentCrudArgProvider() { - return new Object[][] { - // collection name, is name base - {UUID.randomUUID().toString()} , - - // with special characters in the name. - {"+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~"} , - }; - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void createDocument(String documentId) throws InterruptedException { - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); - - validateSuccess(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void createLargeDocument(String documentId) throws InterruptedException { - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - //Keep size as ~ 1.5MB to account for size of other props - int size = (int) (ONE_MB * 1.5); - docDefinition.set("largeString", StringUtils.repeat("x", size)); - - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); - - validateSuccess(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void createDocumentWithVeryLargePartitionKey(String documentId) throws InterruptedException { - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - StringBuilder sb = new StringBuilder(); - for(int i = 0; i < 100; i++) { - sb.append(i).append("x"); - } - docDefinition.set("mypk", sb.toString()); - - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .withProperty("mypk", sb.toString()) - .build(); - validateSuccess(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void readDocumentWithVeryLargePartitionKey(String documentId) throws InterruptedException { - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - StringBuilder sb = new StringBuilder(); - for(int i = 0; i < 100; i++) { - sb.append(i).append("x"); - } - docDefinition.set("mypk", sb.toString()); - - CosmosItem createdDocument = TestSuiteBase.createDocument(createdCollection, docDefinition); - - waitIfNeededForReplicasToCatchUp(clientBuilder); - - CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(new PartitionKey(sb.toString())); - Mono readObservable = createdDocument.read(options); - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .withProperty("mypk", sb.toString()) - .build(); - validateSuccess(readObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void createDocument_AlreadyExists(String documentId) throws InterruptedException { - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block(); - - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); - - FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); - validateFailure(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void createDocumentTimeout(String documentId) throws InterruptedException { - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()) - .timeout(Duration.ofMillis(1)); - - FailureValidator validator = new FailureValidator.Builder().instanceOf(TimeoutException.class).build(); - - validateFailure(createObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void readDocument(String documentId) throws InterruptedException { - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); - waitIfNeededForReplicasToCatchUp(clientBuilder); - - CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); - Mono readObservable = document.read(options); - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(document.getId()) - .build(); - validateSuccess(readObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void timestamp(String documentId, boolean isNameBased) throws Exception { - OffsetDateTime before = OffsetDateTime.now(); - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - Thread.sleep(1000); - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); - - waitIfNeededForReplicasToCatchUp(clientBuilder); - - CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); - CosmosItemSettings readDocument = document.read(options).block().getCosmosItemSettings(); - Thread.sleep(1000); - OffsetDateTime after = OffsetDateTime.now(); - - assertThat(readDocument.getTimestamp()).isAfterOrEqualTo(before); - assertThat(readDocument.getTimestamp()).isBeforeOrEqualTo(after); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void readDocument_DoesntExist(String documentId) throws InterruptedException { - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); - - CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); - document.delete(options).block(); - - waitIfNeededForReplicasToCatchUp(clientBuilder); - - options.setPartitionKey(new PartitionKey("looloo")); - Mono readObservable = document.read(options); - - FailureValidator validator = new FailureValidator.Builder().instanceOf(DocumentClientException.class) - .statusCode(404).build(); - validateFailure(readObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void deleteDocument(String documentId) throws InterruptedException { - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); - - CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); - Mono deleteObservable = document.delete(options); - - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .nullResource().build(); - validateSuccess(deleteObservable, validator); - - // attempt to read document which was deleted - waitIfNeededForReplicasToCatchUp(clientBuilder); - - Mono readObservable = document.read(options); - FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(readObservable, notFoundValidator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void deleteDocument_undefinedPK(String documentId) throws InterruptedException { - Document docDefinition = new Document(); - docDefinition.setId(documentId); - - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); - - CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(PartitionKey.None); - Mono deleteObservable = document.delete(options); - - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .nullResource().build(); - validateSuccess(deleteObservable, validator); - - // attempt to read document which was deleted - waitIfNeededForReplicasToCatchUp(clientBuilder); - - Mono readObservable = document.read(options); - FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(readObservable, notFoundValidator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void deleteDocument_DoesntExist(String documentId) throws InterruptedException { - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); - - CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); - document.delete(options).block(); - - // delete again - Mono deleteObservable = document.delete(options); - - FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(deleteObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void replaceDocument(String documentId) throws InterruptedException { - // create a document - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItem(); - - String newPropValue = UUID.randomUUID().toString(); - docDefinition.set("newProp", newPropValue); - - CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(new PartitionKey(docDefinition.get("mypk"))); - // replace document - Mono replaceObservable = document.replace(docDefinition, options); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withProperty("newProp", newPropValue).build(); - validateSuccess(replaceObservable, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void upsertDocument_CreateDocument(String documentId) throws Throwable { - // create a document - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - - // replace document - Mono upsertObservable = createdCollection.upsertItem(docDefinition, new CosmosItemRequestOptions()); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()).build(); - try { - validateSuccess(upsertObservable, validator); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT * 100, dataProvider = "documentCrudArgProvider") - public void upsertDocument_ReplaceDocument(String documentId) throws Throwable { - // create a document - CosmosItemSettings docDefinition = getDocumentDefinition(documentId); - - docDefinition = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItemSettings(); - - String newPropValue = UUID.randomUUID().toString(); - docDefinition.set("newProp", newPropValue); - - // replace document - Mono readObservable = createdCollection.upsertItem(docDefinition, new CosmosItemRequestOptions()); - System.out.println(docDefinition); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withProperty("newProp", newPropValue).build(); - try { - validateSuccess(readObservable, validator); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } - } - - @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - client = clientBuilder.build(); - createdCollection = getSharedMultiPartitionCosmosContainer(client); - } - - @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeClose(client); - } - - @BeforeMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) - public void beforeMethod() { - safeClose(client); - client = clientBuilder.build(); - } - - private CosmosItemSettings getDocumentDefinition(String documentId) { - String uuid = UUID.randomUUID().toString(); - CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " - + "\"id\": \"%s\", " - + "\"mypk\": \"%s\", " - + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" - + "}" - , documentId, uuid)); - return doc; - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.rx; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.directconnectivity.Protocol; + +import reactor.core.publisher.Mono; + +import org.apache.commons.lang3.StringUtils; +import org.testng.SkipException; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.util.concurrent.TimeoutException; + +import static org.apache.commons.io.FileUtils.ONE_MB; +import static org.assertj.core.api.Assertions.assertThat; + +public class DocumentCrudTest extends TestSuiteBase { + + private CosmosContainer createdCollection; + + private CosmosClient client; + + @Factory(dataProvider = "clientBuildersWithDirect") + public DocumentCrudTest(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; + } + + @DataProvider(name = "documentCrudArgProvider") + public Object[][] documentCrudArgProvider() { + return new Object[][] { + // collection name, is name base + {UUID.randomUUID().toString()} , + + // with special characters in the name. + {"+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~"} , + }; + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void createDocument(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(docDefinition.id()) + .build(); + + validateSuccess(createObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void createLargeDocument(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + //Keep size as ~ 1.5MB to account for size of other props + int size = (int) (ONE_MB * 1.5); + docDefinition.set("largeString", StringUtils.repeat("x", size)); + + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(docDefinition.id()) + .build(); + + validateSuccess(createObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void createDocumentWithVeryLargePartitionKey(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + StringBuilder sb = new StringBuilder(); + for(int i = 0; i < 100; i++) { + sb.append(i).append("x"); + } + docDefinition.set("mypk", sb.toString()); + + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(docDefinition.id()) + .withProperty("mypk", sb.toString()) + .build(); + validateSuccess(createObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void readDocumentWithVeryLargePartitionKey(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + StringBuilder sb = new StringBuilder(); + for(int i = 0; i < 100; i++) { + sb.append(i).append("x"); + } + docDefinition.set("mypk", sb.toString()); + + CosmosItem createdDocument = TestSuiteBase.createDocument(createdCollection, docDefinition); + + waitIfNeededForReplicasToCatchUp(clientBuilder); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.partitionKey(new PartitionKey(sb.toString())); + Mono readObservable = createdDocument.read(options); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(docDefinition.id()) + .withProperty("mypk", sb.toString()) + .build(); + validateSuccess(readObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void createDocument_AlreadyExists(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block(); + + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + + FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); + validateFailure(createObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void createDocumentTimeout(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()) + .timeout(Duration.ofMillis(1)); + + FailureValidator validator = new FailureValidator.Builder().instanceOf(TimeoutException.class).build(); + + validateFailure(createObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void readDocument(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + waitIfNeededForReplicasToCatchUp(clientBuilder); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); + Mono readObservable = document.read(options); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(document.id()) + .build(); + validateSuccess(readObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void timestamp(String documentId, boolean isNameBased) throws Exception { + OffsetDateTime before = OffsetDateTime.now(); + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + Thread.sleep(1000); + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + + waitIfNeededForReplicasToCatchUp(clientBuilder); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); + CosmosItemProperties readDocument = document.read(options).block().properties(); + Thread.sleep(1000); + OffsetDateTime after = OffsetDateTime.now(); + + assertThat(readDocument.timestamp()).isAfterOrEqualTo(before); + assertThat(readDocument.timestamp()).isBeforeOrEqualTo(after); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void readDocument_DoesntExist(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); + document.delete(options).block(); + + waitIfNeededForReplicasToCatchUp(clientBuilder); + + options.partitionKey(new PartitionKey("looloo")); + Mono readObservable = document.read(options); + + FailureValidator validator = new FailureValidator.Builder().instanceOf(CosmosClientException.class) + .statusCode(404).build(); + validateFailure(readObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void deleteDocument(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); + Mono deleteObservable = document.delete(options); + + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteObservable, validator); + + // attempt to read document which was deleted + waitIfNeededForReplicasToCatchUp(clientBuilder); + + Mono readObservable = document.read(options); + FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(readObservable, notFoundValidator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void deleteDocument_undefinedPK(String documentId) throws InterruptedException { + Document docDefinition = new Document(); + docDefinition.id(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.partitionKey(PartitionKey.None); + Mono deleteObservable = document.delete(options); + + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .nullResource().build(); + validateSuccess(deleteObservable, validator); + + // attempt to read document which was deleted + waitIfNeededForReplicasToCatchUp(clientBuilder); + + Mono readObservable = document.read(options); + FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(readObservable, notFoundValidator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void deleteDocument_DoesntExist(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); + document.delete(options).block(); + + // delete again + Mono deleteObservable = document.delete(options); + + FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); + validateFailure(deleteObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void replaceDocument(String documentId) throws InterruptedException { + // create a document + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + + String newPropValue = UUID.randomUUID().toString(); + docDefinition.set("newProp", newPropValue); + + CosmosItemRequestOptions options = new CosmosItemRequestOptions(); + options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); + // replace document + Mono replaceObservable = document.replace(docDefinition, options); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withProperty("newProp", newPropValue).build(); + validateSuccess(replaceObservable, validator); + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") + public void upsertDocument_CreateDocument(String documentId) throws Throwable { + // create a document + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + + // replace document + Mono upsertObservable = createdCollection.upsertItem(docDefinition, new CosmosItemRequestOptions()); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(docDefinition.id()).build(); + try { + validateSuccess(upsertObservable, validator); + } catch (Throwable error) { + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + logger.info(message, error); + throw new SkipException(message, error); + } + throw error; + } + } + + @Test(groups = { "simple" }, timeOut = TIMEOUT * 100, dataProvider = "documentCrudArgProvider") + public void upsertDocument_ReplaceDocument(String documentId) throws Throwable { + // create a document + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + + docDefinition = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().properties(); + + String newPropValue = UUID.randomUUID().toString(); + docDefinition.set("newProp", newPropValue); + + // replace document + Mono readObservable = createdCollection.upsertItem(docDefinition, new CosmosItemRequestOptions()); + System.out.println(docDefinition); + + // validate + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withProperty("newProp", newPropValue).build(); + try { + validateSuccess(readObservable, validator); + } catch (Throwable error) { + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + logger.info(message, error); + throw new SkipException(message, error); + } + throw error; + } + } + + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) + public void beforeClass() { + client = clientBuilder.build(); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + } + + @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeClose(client); + } + + @BeforeMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) + public void beforeMethod() { + safeClose(client); + client = clientBuilder.build(); + } + + private CosmosItemProperties getDocumentDefinition(String documentId) { + String uuid = UUID.randomUUID().toString(); + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + + "\"id\": \"%s\", " + + "\"mypk\": \"%s\", " + + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + + "}" + , documentId, uuid)); + return doc; + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/LogLevelTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java similarity index 80% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/LogLevelTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java index 8decf192dce3b..5050b5fb36b6c 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/LogLevelTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java @@ -21,12 +21,14 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.io.StringWriter; import java.lang.reflect.Method; import java.util.UUID; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.*; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; @@ -39,20 +41,13 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemResponse; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.CosmosResponseValidator; - import reactor.core.publisher.Mono; import static org.assertj.core.api.Assertions.assertThat; public class LogLevelTest extends TestSuiteBase { - public final static String COSMOS_DB_LOGGING_CATEGORY = "com.microsoft.azure.cosmosdb"; - public final static String NETWORK_LOGGING_CATEGORY = "com.microsoft.azure.cosmosdb.netty-network"; + public final static String COSMOS_DB_LOGGING_CATEGORY = "com.azure.data.cosmos"; + public final static String NETWORK_LOGGING_CATEGORY = "com.azure.data.cosmos.netty-network"; public final static String LOG_PATTERN_1 = "HTTP/1.1 200 Ok."; public final static String LOG_PATTERN_2 = "| 0 1 2 3 4 5 6 7 8 9 a b c d e f |"; public final static String LOG_PATTERN_3 = "USER_EVENT: SslHandshakeCompletionEvent(SUCCESS)"; @@ -65,14 +60,15 @@ public LogLevelTest() { this.clientBuilder = createGatewayRxDocumentClient(); } - @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder.build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); } /** - * This test will try to create document with netty wire DEBUG logging and validate it. + * This test will try to create document with netty wire DEBUG logging and + * validate it. * * @throws Exception */ @@ -85,11 +81,11 @@ public void createDocumentWithDebugLevel() throws Exception { CosmosClient client = clientBuilder.build(); try { - CosmosItemSettings docDefinition = getDocumentDefinition(); - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosItemProperties docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, + new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); + .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator); assertThat(consoleWriter.toString()).isEmpty(); @@ -100,7 +96,8 @@ public void createDocumentWithDebugLevel() throws Exception { } /** - * This test will try to create document with netty wire WARN logging and validate it. + * This test will try to create document with netty wire WARN logging and + * validate it. * * @throws Exception */ @@ -114,11 +111,11 @@ public void createDocumentWithWarningLevel() throws Exception { CosmosClient client = clientBuilder.build(); try { - CosmosItemSettings docDefinition = getDocumentDefinition(); - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosItemProperties docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, + new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); + .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator); assertThat(consoleWriter.toString()).isEmpty(); @@ -128,7 +125,8 @@ public void createDocumentWithWarningLevel() throws Exception { } /** - * This test will try to create document with netty wire TRACE logging and validate it. + * This test will try to create document with netty wire TRACE logging and + * validate it. * * @throws Exception */ @@ -142,11 +140,11 @@ public void createDocumentWithTraceLevel() throws Exception { CosmosClient client = clientBuilder.build(); try { - CosmosItemSettings docDefinition = getDocumentDefinition(); - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosItemProperties docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, + new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); + .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator); assertThat(consoleWriter.toString()).contains(LOG_PATTERN_1); @@ -169,11 +167,11 @@ public void createDocumentWithTraceLevelAtRoot() throws Exception { CosmosClient client = clientBuilder.build(); try { - CosmosItemSettings docDefinition = getDocumentDefinition(); - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosItemProperties docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, + new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); + .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator); assertThat(consoleWriter.toString()).contains(LOG_PATTERN_1); @@ -195,11 +193,11 @@ public void createDocumentWithDebugLevelAtRoot() throws Exception { CosmosClient client = clientBuilder.build(); try { - CosmosItemSettings docDefinition = getDocumentDefinition(); - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosItemProperties docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, + new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); + .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator); assertThat(consoleWriter.toString()).isEmpty(); @@ -209,7 +207,8 @@ public void createDocumentWithDebugLevelAtRoot() throws Exception { } /** - * This test will try to create document with netty wire ERROR logging and validate it. + * This test will try to create document with netty wire ERROR logging and + * validate it. * * @throws Exception */ @@ -223,11 +222,11 @@ public void createDocumentWithErrorClient() throws Exception { CosmosClient client = clientBuilder.build(); try { - CosmosItemSettings docDefinition = getDocumentDefinition(); - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosItemProperties docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, + new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); + .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator); assertThat(consoleWriter.toString()).isEmpty(); @@ -237,7 +236,8 @@ public void createDocumentWithErrorClient() throws Exception { } /** - * This test will try to create document with netty wire INFO logging and validate it. + * This test will try to create document with netty wire INFO logging and + * validate it. * * @throws Exception */ @@ -251,11 +251,11 @@ public void createDocumentWithInfoLevel() throws Exception { CosmosClient client = clientBuilder.build(); try { - CosmosItemSettings docDefinition = getDocumentDefinition(); - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosItemProperties docDefinition = getDocumentDefinition(); + Mono createObservable = createdCollection.createItem(docDefinition, + new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) - .build(); + .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator); assertThat(consoleWriter.toString()).isEmpty(); @@ -264,18 +264,15 @@ public void createDocumentWithInfoLevel() throws Exception { } } - private CosmosItemSettings getDocumentDefinition() { + private CosmosItemProperties getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " - + "\"id\": \"%s\", " - + "\"mypk\": \"%s\", " - + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" - + "}" - , uuid, uuid)); + CosmosItemProperties doc = new CosmosItemProperties( + String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}", uuid, uuid)); return doc; } - @BeforeMethod(groups = { "simple"}) + @BeforeMethod(groups = { "simple" }) public void beforeMethod(Method method) { super.beforeMethod(method); LogManager.resetConfiguration(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiMasterConflictResolutionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java similarity index 61% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiMasterConflictResolutionTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java index a9f73ec834136..10f61efa8da3e 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiMasterConflictResolutionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java @@ -1,215 +1,205 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.microsoft.azure.cosmosdb.rx; - -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerResponse; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import com.microsoft.azure.cosmosdb.BridgeUtils; -import com.microsoft.azure.cosmosdb.ConflictResolutionMode; -import com.microsoft.azure.cosmosdb.ConflictResolutionPolicy; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; - -import reactor.core.publisher.Mono; - -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.UUID; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - -// assumes multi master is enabled in endpoint -public class MultiMasterConflictResolutionTest extends TestSuiteBase { - private static final int TIMEOUT = 40000; - - private final String databaseId = CosmosDatabaseForTest.generateId(); - - private PartitionKeyDefinition partitionKeyDef; - private CosmosClient client; - private CosmosDatabase database; - - @Factory(dataProvider = "clientBuilders") - public MultiMasterConflictResolutionTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; - } - - @Test(groups = "multi-master", timeOut = 10 * TIMEOUT) - public void conflictResolutionPolicyCRUD() { - - // default last writer wins, path _ts - CosmosContainerSettings collectionSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); - CosmosContainer collection = database.createContainer(collectionSettings, new CosmosContainerRequestOptions()).block().getContainer(); - collectionSettings = collection.read().block().getCosmosContainerSettings(); - - assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionMode()).isEqualTo(ConflictResolutionMode.LastWriterWins); - - // LWW without path specified, should default to _ts - collectionSettings.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy()); - collectionSettings = collection.replace(collectionSettings, null).block().getCosmosContainerSettings(); - - assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionMode()).isEqualTo(ConflictResolutionMode.LastWriterWins); - assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionPath()).isEqualTo("/_ts"); - - // Tests the following scenarios - // 1. LWW with valid path - // 2. LWW with null path, should default to _ts - // 3. LWW with empty path, should default to _ts - testConflictResolutionPolicyRequiringPath(ConflictResolutionMode.LastWriterWins, - new String[] { "/a", null, "" }, new String[] { "/a", "/_ts", "/_ts" }); - - // LWW invalid path - collectionSettings.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy("/a/b")); - - try { - collectionSettings = collection.replace(collectionSettings, null).block().getCosmosContainerSettings(); - fail("Expected exception on invalid path."); - } catch (Exception e) { - - // when (e.StatusCode == HttpStatusCode.BadRequest) - DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e.getCause(), DocumentClientException.class); - if (dce != null && dce.getStatusCode() == 400) { - assertThat(dce.getMessage()).contains("Invalid path '\\/a\\/b' for last writer wins conflict resolution"); - } else { - throw e; - } - } - - // LWW invalid path - - collectionSettings.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy("someText")); - - try { - collectionSettings = collection.replace(collectionSettings, null).block().getCosmosContainerSettings(); - fail("Expected exception on invalid path."); - } catch (Exception e) { - // when (e.StatusCode == HttpStatusCode.BadRequest) - DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e.getCause(), DocumentClientException.class); - if (dce != null && dce.getStatusCode() == 400) { - assertThat(dce.getMessage()).contains("Invalid path 'someText' for last writer wins conflict resolution"); - } else { - throw e; - } - } - - // Tests the following scenarios - // 1. Custom with valid sprocLink - // 2. Custom with null sprocLink, should default to empty string - // 3. Custom with empty sprocLink, should default to empty string - testConflictResolutionPolicyRequiringPath(ConflictResolutionMode.Custom, - new String[] { "randomSprocName", null, "" }, new String[] { "randomSprocName", "", "" }); - } - - private void testConflictResolutionPolicyRequiringPath(ConflictResolutionMode conflictResolutionMode, - String[] paths, String[] expectedPaths) { - for (int i = 0; i < paths.length; i++) { - CosmosContainerSettings collectionSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); - - if (conflictResolutionMode == ConflictResolutionMode.LastWriterWins) { - collectionSettings.setConflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy(paths[i])); - } else { - collectionSettings.setConflictResolutionPolicy(ConflictResolutionPolicy.createCustomPolicy(paths[i])); - } - collectionSettings = database.createContainer(collectionSettings, new CosmosContainerRequestOptions()).block().getCosmosContainerSettings(); - assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionMode()).isEqualTo(conflictResolutionMode); - - if (conflictResolutionMode == ConflictResolutionMode.LastWriterWins) { - assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionPath()).isEqualTo(expectedPaths[i]); - } else { - assertThat(collectionSettings.getConflictResolutionPolicy().getConflictResolutionProcedure()).isEqualTo(expectedPaths[i]); - } - } - } - - @Test(groups = "multi-master", timeOut = TIMEOUT) - public void invalidConflictResolutionPolicy_LastWriterWinsWithStoredProc() throws Exception { - CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); - - // LWW without path specified, should default to _ts - ConflictResolutionPolicy policy = BridgeUtils.createConflictResolutionPolicy(); - BridgeUtils.setMode(policy, ConflictResolutionMode.LastWriterWins); - BridgeUtils.setStoredProc(policy,"randomSprocName"); - collection.setConflictResolutionPolicy(policy); - - Mono createObservable = database.createContainer( - collection, - new CosmosContainerRequestOptions()); - - FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) - .statusCode(400) - .errorMessageContains("LastWriterWins conflict resolution mode should not have conflict resolution procedure set.") - .build(); - validateFailure(createObservable, validator); - } - - @Test(groups = "multi-master", timeOut = TIMEOUT) - public void invalidConflictResolutionPolicy_CustomWithPath() throws Exception { - CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); - - // LWW without path specified, should default to _ts - ConflictResolutionPolicy policy = BridgeUtils.createConflictResolutionPolicy(); - BridgeUtils.setMode(policy, ConflictResolutionMode.Custom); - BridgeUtils.setPath(policy,"/mypath"); - collection.setConflictResolutionPolicy(policy); - - Mono createObservable = database.createContainer( - collection, - new CosmosContainerRequestOptions()); - - FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) - .statusCode(400) - .errorMessageContains("Custom conflict resolution mode should not have conflict resolution path set.") - .build(); - validateFailure(createObservable, validator); - } - - @BeforeClass(groups = {"multi-master"}, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - // set up the client - - client = clientBuilder.build(); - database = createDatabase(client, databaseId); - partitionKeyDef = new PartitionKeyDefinition(); - ArrayList paths = new ArrayList(); - paths.add("/mypk"); - partitionKeyDef.setPaths(paths); - } - - @AfterClass(groups = {"multi-master"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeDeleteDatabase(database); - safeClose(client); - } -} +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.rx; + +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.CosmosClientException; + +import reactor.core.publisher.Mono; + +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +// assumes multi master is enabled in endpoint +public class MultiMasterConflictResolutionTest extends TestSuiteBase { + private static final int TIMEOUT = 40000; + + private final String databaseId = CosmosDatabaseForTest.generateId(); + + private PartitionKeyDefinition partitionKeyDef; + private CosmosClient client; + private CosmosDatabase database; + + @Factory(dataProvider = "clientBuilders") + public MultiMasterConflictResolutionTest(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; + } + + @Test(groups = "multi-master", timeOut = 10 * TIMEOUT) + public void conflictResolutionPolicyCRUD() { + + // default last writer wins, path _ts + CosmosContainerSettings collectionSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainer collection = database.createContainer(collectionSettings, new CosmosContainerRequestOptions()).block().container(); + collectionSettings = collection.read().block().settings(); + + assertThat(collectionSettings.conflictResolutionPolicy().mode()).isEqualTo(ConflictResolutionMode.LAST_WRITER_WINS); + + // LWW without path specified, should default to _ts + collectionSettings.conflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy()); + collectionSettings = collection.replace(collectionSettings, null).block().settings(); + + assertThat(collectionSettings.conflictResolutionPolicy().mode()).isEqualTo(ConflictResolutionMode.LAST_WRITER_WINS); + assertThat(collectionSettings.conflictResolutionPolicy().conflictResolutionPath()).isEqualTo("/_ts"); + + // Tests the following scenarios + // 1. LWW with valid path + // 2. LWW with null path, should default to _ts + // 3. LWW with empty path, should default to _ts + testConflictResolutionPolicyRequiringPath(ConflictResolutionMode.LAST_WRITER_WINS, + new String[] { "/a", null, "" }, new String[] { "/a", "/_ts", "/_ts" }); + + // LWW invalid path + collectionSettings.conflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy("/a/b")); + + try { + collectionSettings = collection.replace(collectionSettings, null).block().settings(); + fail("Expected exception on invalid path."); + } catch (Exception e) { + + // when (e.StatusCode == HttpStatusCode.BadRequest) + CosmosClientException dce = Utils.as(e.getCause(), CosmosClientException.class); + if (dce != null && dce.statusCode() == 400) { + assertThat(dce.getMessage()).contains("INVALID path '\\/a\\/b' for last writer wins conflict resolution"); + } else { + throw e; + } + } + + // LWW invalid path + + collectionSettings.conflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy("someText")); + + try { + collectionSettings = collection.replace(collectionSettings, null).block().settings(); + fail("Expected exception on invalid path."); + } catch (Exception e) { + // when (e.StatusCode == HttpStatusCode.BadRequest) + CosmosClientException dce = Utils.as(e.getCause(), CosmosClientException.class); + if (dce != null && dce.statusCode() == 400) { + assertThat(dce.getMessage()).contains("INVALID path 'someText' for last writer wins conflict resolution"); + } else { + throw e; + } + } + + // Tests the following scenarios + // 1. CUSTOM with valid sprocLink + // 2. CUSTOM with null sprocLink, should default to empty string + // 3. CUSTOM with empty sprocLink, should default to empty string + testConflictResolutionPolicyRequiringPath(ConflictResolutionMode.CUSTOM, + new String[] { "randomSprocName", null, "" }, new String[] { "randomSprocName", "", "" }); + } + + private void testConflictResolutionPolicyRequiringPath(ConflictResolutionMode conflictResolutionMode, + String[] paths, String[] expectedPaths) { + for (int i = 0; i < paths.length; i++) { + CosmosContainerSettings collectionSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + + if (conflictResolutionMode == ConflictResolutionMode.LAST_WRITER_WINS) { + collectionSettings.conflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy(paths[i])); + } else { + collectionSettings.conflictResolutionPolicy(ConflictResolutionPolicy.createCustomPolicy(paths[i])); + } + collectionSettings = database.createContainer(collectionSettings, new CosmosContainerRequestOptions()).block().settings(); + assertThat(collectionSettings.conflictResolutionPolicy().mode()).isEqualTo(conflictResolutionMode); + + if (conflictResolutionMode == ConflictResolutionMode.LAST_WRITER_WINS) { + assertThat(collectionSettings.conflictResolutionPolicy().conflictResolutionPath()).isEqualTo(expectedPaths[i]); + } else { + assertThat(collectionSettings.conflictResolutionPolicy().conflictResolutionProcedure()).isEqualTo(expectedPaths[i]); + } + } + } + + @Test(groups = "multi-master", timeOut = TIMEOUT) + public void invalidConflictResolutionPolicy_LastWriterWinsWithStoredProc() throws Exception { + CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + + // LWW without path specified, should default to _ts + ConflictResolutionPolicy policy = BridgeUtils.createConflictResolutionPolicy(); + BridgeUtils.setMode(policy, ConflictResolutionMode.LAST_WRITER_WINS); + BridgeUtils.setStoredProc(policy,"randomSprocName"); + collection.conflictResolutionPolicy(policy); + + Mono createObservable = database.createContainer( + collection, + new CosmosContainerRequestOptions()); + + FailureValidator validator = new FailureValidator.Builder() + .instanceOf(CosmosClientException.class) + .statusCode(400) + .errorMessageContains("LAST_WRITER_WINS conflict resolution mode should not have conflict resolution procedure set.") + .build(); + validateFailure(createObservable, validator); + } + + @Test(groups = "multi-master", timeOut = TIMEOUT) + public void invalidConflictResolutionPolicy_CustomWithPath() throws Exception { + CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + + // LWW without path specified, should default to _ts + ConflictResolutionPolicy policy = BridgeUtils.createConflictResolutionPolicy(); + BridgeUtils.setMode(policy, ConflictResolutionMode.CUSTOM); + BridgeUtils.setPath(policy,"/mypath"); + collection.conflictResolutionPolicy(policy); + + Mono createObservable = database.createContainer( + collection, + new CosmosContainerRequestOptions()); + + FailureValidator validator = new FailureValidator.Builder() + .instanceOf(CosmosClientException.class) + .statusCode(400) + .errorMessageContains("CUSTOM conflict resolution mode should not have conflict resolution path set.") + .build(); + validateFailure(createObservable, validator); + } + + @BeforeClass(groups = {"multi-master"}, timeOut = SETUP_TIMEOUT) + public void beforeClass() { + // set up the client + + client = clientBuilder.build(); + database = createDatabase(client, databaseId); + partitionKeyDef = new PartitionKeyDefinition(); + ArrayList paths = new ArrayList(); + paths.add("/mypk"); + partitionKeyDef.paths(paths); + } + + @AfterClass(groups = {"multi-master"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeDeleteDatabase(database); + safeClose(client); + } +} diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiOrderByQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java similarity index 75% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiOrderByQueryTests.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java index 38d551d1cac8e..254f2020bade3 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/MultiOrderByQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.ArrayList; import java.util.Collection; @@ -32,7 +32,8 @@ import java.util.Random; import java.util.UUID; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.*; import org.apache.commons.collections4.ComparatorUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -40,21 +41,10 @@ import org.testng.annotations.Test; import com.fasterxml.jackson.databind.ObjectMapper; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.CompositePath; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClientException; import reactor.core.publisher.Flux; -import com.microsoft.azure.cosmosdb.CompositePathSortOrder; -import com.microsoft.azure.cosmosdb.Document; - public class MultiOrderByQueryTests extends TestSuiteBase { private static final int TIMEOUT = 35000; @@ -70,12 +60,12 @@ public class MultiOrderByQueryTests extends TestSuiteBase { private static final String MEDIUM_STRING_FIELD = "mediumStringField"; private static final String LONG_STRING_FIELD = "longStringField"; private static final String PARTITION_KEY = "pk"; - private ArrayList documents = new ArrayList(); + private ArrayList documents = new ArrayList(); private CosmosContainer documentCollection; private CosmosClientBuilder clientBuilder; private CosmosClient client; - class CustomComparator implements Comparator { + class CustomComparator implements Comparator { String path; CompositePathSortOrder order; boolean isNumericPath = false; @@ -98,8 +88,8 @@ public CustomComparator(String path, CompositePathSortOrder order) { } @Override - public int compare(CosmosItemSettings doc1, CosmosItemSettings doc2) { - boolean isAsc = order == CompositePathSortOrder.Ascending; + public int compare(CosmosItemProperties doc1, CosmosItemProperties doc2) { + boolean isAsc = order == CompositePathSortOrder.ASCENDING; if (isNumericPath) { if (doc1.getInt(path) < doc2.getInt(path)) return isAsc ? -1 : 1; @@ -109,7 +99,7 @@ else if (doc1.getInt(path) > doc2.getInt(path)) return 0; } else if (isStringPath) { if (!isAsc) { - CosmosItemSettings temp = doc1; + CosmosItemProperties temp = doc1; doc1 = doc2; doc2 = temp; } @@ -156,30 +146,30 @@ public void beforeClass() throws Exception { for (int j = 0; j < numberOfDuplicates; j++) { // Add the document itself for exact duplicates - CosmosItemSettings initialDocument = new CosmosItemSettings(multiOrderByDocumentString); - initialDocument.setId(UUID.randomUUID().toString()); + CosmosItemProperties initialDocument = new CosmosItemProperties(multiOrderByDocumentString); + initialDocument.id(UUID.randomUUID().toString()); this.documents.add(initialDocument); // Permute all the fields so that there are duplicates with tie breaks - CosmosItemSettings numberClone = new CosmosItemSettings(multiOrderByDocumentString); + CosmosItemProperties numberClone = new CosmosItemProperties(multiOrderByDocumentString); numberClone.set(NUMBER_FIELD, random.nextInt(5)); - numberClone.setId(UUID.randomUUID().toString()); + numberClone.id(UUID.randomUUID().toString()); this.documents.add(numberClone); - CosmosItemSettings stringClone = new CosmosItemSettings(multiOrderByDocumentString); + CosmosItemProperties stringClone = new CosmosItemProperties(multiOrderByDocumentString); stringClone.set(STRING_FIELD, Integer.toString(random.nextInt(5))); - stringClone.setId(UUID.randomUUID().toString()); + stringClone.id(UUID.randomUUID().toString()); this.documents.add(stringClone); - CosmosItemSettings boolClone = new CosmosItemSettings(multiOrderByDocumentString); + CosmosItemProperties boolClone = new CosmosItemProperties(multiOrderByDocumentString); boolClone.set(BOOL_FIELD, random.nextInt(2) % 2 == 0); - boolClone.setId(UUID.randomUUID().toString()); + boolClone.id(UUID.randomUUID().toString()); this.documents.add(boolClone); // Also fuzz what partition it goes to - CosmosItemSettings partitionClone = new CosmosItemSettings(multiOrderByDocumentString); + CosmosItemProperties partitionClone = new CosmosItemProperties(multiOrderByDocumentString); partitionClone.set(PARTITION_KEY, random.nextInt(5)); - partitionClone.setId(UUID.randomUUID().toString()); + partitionClone.id(UUID.randomUUID().toString()); this.documents.add(partitionClone); } } @@ -192,7 +182,7 @@ public void beforeClass() throws Exception { private Document generateMultiOrderByDocument() { Random random = new Random(); Document document = new Document(); - document.setId(UUID.randomUUID().toString()); + document.id(UUID.randomUUID().toString()); document.set(NUMBER_FIELD, random.nextInt(5)); document.set(NUMBER_FIELD_2, random.nextInt(5)); document.set(BOOL_FIELD, (random.nextInt() % 2) == 0); @@ -209,13 +199,13 @@ private Document generateMultiOrderByDocument() { } @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void queryDocumentsWithMultiOrder() throws DocumentClientException, InterruptedException { + public void queryDocumentsWithMultiOrder() throws CosmosClientException, InterruptedException { FeedOptions feedOptions = new FeedOptions(); - feedOptions.setEnableCrossPartitionQuery(true); + feedOptions.enableCrossPartitionQuery(true); boolean[] booleanValues = new boolean[] {true, false}; - CosmosContainerSettings containerSettings = documentCollection.read().block().getCosmosContainerSettings(); - Iterator> compositeIndexesIterator = containerSettings.getIndexingPolicy().getCompositeIndexes().iterator(); + CosmosContainerSettings containerSettings = documentCollection.read().block().settings(); + Iterator> compositeIndexesIterator = containerSettings.indexingPolicy().compositeIndexes().iterator(); while (compositeIndexesIterator.hasNext()) { ArrayList compositeIndex = compositeIndexesIterator.next(); // for every order @@ -232,13 +222,13 @@ public void queryDocumentsWithMultiOrder() throws DocumentClientException, Inter Iterator compositeIndexiterator = compositeIndex.iterator(); while (compositeIndexiterator.hasNext()) { CompositePath compositePath = compositeIndexiterator.next(); - isDesc = compositePath.getOrder() == CompositePathSortOrder.Descending ? true : false; + isDesc = compositePath.order() == CompositePathSortOrder.DESCENDING ? true : false; if (invert) { isDesc = !isDesc; } String isDescString = isDesc ? "DESC" : "ASC"; - String compositePathName = compositePath.getPath().replaceAll("/", ""); + String compositePathName = compositePath.path().replaceAll("/", ""); String orderByItemsString = "root." + compositePathName + " " + isDescString; String selectItemsString = "root." + compositePathName; orderByItems.add(orderByItemsString); @@ -265,12 +255,12 @@ public void queryDocumentsWithMultiOrder() throws DocumentClientException, Inter "FROM root " + whereString + " " + "ORDER BY " + orderByItemStringBuilder.toString(); - ArrayList expectedOrderedList = top(sort(filter(this.documents, hasFilter), compositeIndex, invert), hasTop, topCount) ; + ArrayList expectedOrderedList = top(sort(filter(this.documents, hasFilter), compositeIndex, invert), hasTop, topCount) ; - Flux> queryObservable = documentCollection.queryItems(query, feedOptions); + Flux> queryObservable = documentCollection.queryItems(query, feedOptions); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .withOrderedResults(expectedOrderedList, compositeIndex) .build(); @@ -280,13 +270,13 @@ public void queryDocumentsWithMultiOrder() throws DocumentClientException, Inter } } - // Create document with numberField not set. + // CREATE document with numberField not set. // This query would then be invalid. Document documentWithEmptyField = generateMultiOrderByDocument(); documentWithEmptyField.remove(NUMBER_FIELD); documentCollection.createItem(documentWithEmptyField, new CosmosItemRequestOptions()).block(); String query = "SELECT [root." + NUMBER_FIELD + ",root." + STRING_FIELD + "] FROM root ORDER BY root." + NUMBER_FIELD + " ASC ,root." + STRING_FIELD + " DESC"; - Flux> queryObservable = documentCollection.queryItems(query, feedOptions); + Flux> queryObservable = documentCollection.queryItems(query, feedOptions); FailureValidator validator = new FailureValidator.Builder() .instanceOf(UnsupportedOperationException.class) @@ -295,8 +285,8 @@ public void queryDocumentsWithMultiOrder() throws DocumentClientException, Inter validateQueryFailure(queryObservable, validator); } - private ArrayList top(ArrayList arrayList, boolean hasTop, int topCount) { - ArrayList result = new ArrayList(); + private ArrayList top(ArrayList arrayList, boolean hasTop, int topCount) { + ArrayList result = new ArrayList(); int counter = 0; if (hasTop) { while (counter < topCount && counter < arrayList.size()) { @@ -309,31 +299,31 @@ private ArrayList top(ArrayList arrayLis return result; } - private ArrayList sort(ArrayList arrayList, ArrayList compositeIndex, - boolean invert) { - Collection> comparators = new ArrayList>(); + private ArrayList sort(ArrayList arrayList, ArrayList compositeIndex, + boolean invert) { + Collection> comparators = new ArrayList>(); Iterator compositeIndexIterator = compositeIndex.iterator(); while (compositeIndexIterator.hasNext()) { CompositePath compositePath = compositeIndexIterator.next(); - CompositePathSortOrder order = compositePath.getOrder(); + CompositePathSortOrder order = compositePath.order(); if (invert) { - if (order == CompositePathSortOrder.Descending) { - order = CompositePathSortOrder.Ascending; + if (order == CompositePathSortOrder.DESCENDING) { + order = CompositePathSortOrder.ASCENDING; } else { - order = CompositePathSortOrder.Descending; + order = CompositePathSortOrder.DESCENDING; } } - String path = compositePath.getPath().replace("/", ""); + String path = compositePath.path().replace("/", ""); comparators.add(new CustomComparator(path, order)); } Collections.sort(arrayList, ComparatorUtils.chainedComparator(comparators)); return arrayList; } - private ArrayList filter(ArrayList cosmosItemSettings, boolean hasFilter) { - ArrayList result = new ArrayList(); + private ArrayList filter(ArrayList cosmosItemSettings, boolean hasFilter) { + ArrayList result = new ArrayList(); if (hasFilter) { - for (CosmosItemSettings document : cosmosItemSettings) { + for (CosmosItemProperties document : cosmosItemSettings) { if (document.getInt(NUMBER_FIELD) % 2 == 0) { result.add(document); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java similarity index 84% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java index aa9a329faaa37..f0048141f4740 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -29,21 +29,22 @@ import java.util.UUID; import java.util.stream.Collectors; +import com.azure.data.cosmos.AsyncDocumentClient; import org.assertj.core.util.Strings; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient.Builder; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.internal.TestSuiteBase; import rx.Observable; @@ -68,23 +69,23 @@ public OfferQueryTest(Builder clientBuilder) { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void queryOffersWithFilter() throws Exception { - String collectionResourceId = createdCollections.get(0).getResourceId(); + String collectionResourceId = createdCollections.get(0).resourceId(); String query = String.format("SELECT * from c where c.offerResourceId = '%s'", collectionResourceId); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Observable> queryObservable = client.queryOffers(query, null); - List allOffers = client.readOffers(null).flatMap(f -> Observable.from(f.getResults())).toList().toBlocking().single(); + List allOffers = client.readOffers(null).flatMap(f -> Observable.from(f.results())).toList().toBlocking().single(); List expectedOffers = allOffers.stream().filter(o -> collectionResourceId.equals(o.getString("offerResourceId"))).collect(Collectors.toList()); assertThat(expectedOffers).isNotEmpty(); - int expectedPageSize = (expectedOffers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedOffers.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedOffers.size()) - .exactlyContainsInAnyOrder(expectedOffers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedOffers.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -96,25 +97,25 @@ public void queryOffersWithFilter() throws Exception { @Test(groups = { "emulator" }, timeOut = TIMEOUT * 100) public void queryOffersFilterMorePages() throws Exception { - List collectionResourceIds = createdCollections.stream().map(c -> c.getResourceId()).collect(Collectors.toList()); + List collectionResourceIds = createdCollections.stream().map(c -> c.resourceId()).collect(Collectors.toList()); String query = String.format("SELECT * from c where c.offerResourceId in (%s)", Strings.join(collectionResourceIds.stream().map(s -> "'" + s + "'").collect(Collectors.toList())).with(",")); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(1); + options.maxItemCount(1); Observable> queryObservable = client.queryOffers(query, options); - List expectedOffers = client.readOffers(null).flatMap(f -> Observable.from(f.getResults())).toList().toBlocking().single() + List expectedOffers = client.readOffers(null).flatMap(f -> Observable.from(f.results())).toList().toBlocking().single() .stream().filter(o -> collectionResourceIds.contains(o.getOfferResourceId())) .collect(Collectors.toList()); assertThat(expectedOffers).hasSize(createdCollections.size()); - int expectedPageSize = (expectedOffers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedOffers.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedOffers.size()) - .exactlyContainsInAnyOrder(expectedOffers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedOffers.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -144,17 +145,17 @@ public void beforeClass() throws Exception { client = clientBuilder.build(); Database d1 = new Database(); - d1.setId(databaseId); + d1.id(databaseId); createDatabase(client, d1); for(int i = 0; i < 3; i++) { DocumentCollection collection = new DocumentCollection(); - collection.setId(UUID.randomUUID().toString()); + collection.id(UUID.randomUUID().toString()); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); collection.setPartitionKey(partitionKeyDef); createdCollections.add(createCollection(client, databaseId, collection)); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferReadReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java similarity index 86% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferReadReplaceTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java index de3715f02152a..eb6daed6b3a13 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OfferReadReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java @@ -20,21 +20,22 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.List; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.TestSuiteBase; import rx.Observable; @@ -59,17 +60,17 @@ public void readAndReplaceOffer() { client.readOffers(null).toBlocking().subscribe((offersFeed) -> { try { int i; - List offers = offersFeed.getResults(); + List offers = offersFeed.results(); for (i = 0; i < offers.size(); i++) { - if (offers.get(i).getOfferResourceId().equals(createdCollection.getResourceId())) { + if (offers.get(i).getOfferResourceId().equals(createdCollection.resourceId())) { break; } } - Offer rOffer = client.readOffer(offers.get(i).getSelfLink()).toBlocking().single().getResource(); + Offer rOffer = client.readOffer(offers.get(i).selfLink()).toBlocking().single().getResource(); int oldThroughput = rOffer.getThroughput(); - Observable> readObservable = client.readOffer(offers.get(i).getSelfLink()); + Observable> readObservable = client.readOffer(offers.get(i).selfLink()); // validate offer read ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() @@ -103,7 +104,7 @@ public void readAndReplaceOffer() { public void beforeClass() { client = clientBuilder.build(); createdDatabase = createDatabase(client, databaseId); - createdCollection = createCollection(client, createdDatabase.getId(), + createdCollection = createCollection(client, createdDatabase.id(), getCollectionDefinition()); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java similarity index 72% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java index 37c521e4478f6..f096e671e2d5e 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -35,8 +35,8 @@ import java.util.function.Function; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmosdb.RetryAnalyzer; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.*; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.core.JsonProcessingException; @@ -47,21 +47,12 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosBridgeInternal; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.internal.query.QueryItem; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; -import com.microsoft.azure.cosmosdb.rx.internal.query.CompositeContinuationToken; -import com.microsoft.azure.cosmosdb.rx.internal.query.OrderByContinuationToken; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.query.QueryItem; +import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.internal.Utils.ValueHolder; +import com.azure.data.cosmos.internal.query.CompositeContinuationToken; +import com.azure.data.cosmos.internal.query.OrderByContinuationToken; import io.reactivex.subscribers.TestSubscriber; import reactor.core.publisher.Flux; @@ -73,7 +64,7 @@ public class OrderbyDocumentQueryTest extends TestSuiteBase { private CosmosClient client; private CosmosContainer createdCollection; private CosmosDatabase createdDatabase; - private List createdDocuments = new ArrayList<>(); + private List createdDocuments = new ArrayList<>(); private int numberOfPartitions; @@ -84,32 +75,32 @@ public OrderbyDocumentQueryTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocumentsValidateContent(boolean qmEnabled) throws Exception { - CosmosItemSettings expectedDocument = createdDocuments.get(0); + CosmosItemProperties expectedDocument = createdDocuments.get(0); String query = String.format("SELECT * from root r where r.propStr = '%s'" + " ORDER BY r.propInt" , expectedDocument.getString("propStr")); FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setPopulateQueryMetrics(qmEnabled); + options.enableCrossPartitionQuery(true); + options.populateQueryMetrics(qmEnabled); - Flux> queryObservable = createdCollection.queryItems(query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); List expectedResourceIds = new ArrayList<>(); - expectedResourceIds.add(expectedDocument.getResourceId()); + expectedResourceIds.add(expectedDocument.resourceId()); - Map> resourceIDToValidator = new HashMap<>(); + Map> resourceIDToValidator = new HashMap<>(); - resourceIDToValidator.put(expectedDocument.getResourceId(), - new ResourceValidator.Builder().areEqual(expectedDocument).build()); + resourceIDToValidator.put(expectedDocument.resourceId(), + new ResourceValidator.Builder().areEqual(expectedDocument).build()); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .numberOfPages(1) .containsExactly(expectedResourceIds) .validateAllResources(resourceIDToValidator) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) - .allPagesSatisfy(new FeedResponseValidator.Builder().hasRequestChargeHeader().build()) + .allPagesSatisfy(new FeedResponseValidator.Builder().hasRequestChargeHeader().build()) .hasValidQueryMetrics(qmEnabled) .build(); @@ -119,7 +110,7 @@ public void queryDocumentsValidateContent(boolean qmEnabled) throws Exception { // TODO: DANOBLE: report this detailed information in all failures produced by TestSuiteBase classes // work item: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/370015 String message = String.format("%s %s mode with %s consistency test failure", - this.clientBuilder.getConnectionPolicy().getConnectionMode(), + this.clientBuilder.getConnectionPolicy().connectionMode(), this.clientBuilder.getConfigs().getProtocol(), this.clientBuilder.getDesiredConsistencyLevel()); throw new AssertionError(message, error); @@ -130,14 +121,14 @@ public void queryDocumentsValidateContent(boolean qmEnabled) throws Exception { public void queryDocuments_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2' ORDER BY r.propInt"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .hasRequestChargeHeader().build()) .build(); @@ -153,10 +144,10 @@ public Object[][] sortOrder() { public void queryOrderBy(String sortOrder) throws Exception { String query = String.format("SELECT * FROM r ORDER BY r.propInt %s", sortOrder); FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); int pageSize = 3; - options.setMaxItemCount(pageSize); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.maxItemCount(pageSize); + Flux> queryObservable = createdCollection.queryItems(query, options); Comparator validatorComparator = Comparator.nullsFirst(Comparator.naturalOrder()); List expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); @@ -166,10 +157,10 @@ public void queryOrderBy(String sortOrder) throws Exception { int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); @@ -181,19 +172,19 @@ public void queryOrderBy(String sortOrder) throws Exception { public void queryOrderByInt() throws Exception { String query = "SELECT * FROM r ORDER BY r.propInt"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); int pageSize = 3; - options.setMaxItemCount(pageSize); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.maxItemCount(pageSize); + Flux> queryObservable = createdCollection.queryItems(query, options); Comparator validatorComparator = Comparator.nullsFirst(Comparator.naturalOrder()); List expectedResourceIds = sortDocumentsAndCollectResourceIds("propInt", d -> d.getInt("propInt"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); @@ -205,19 +196,19 @@ public void queryOrderByInt() throws Exception { public void queryOrderByString() throws Exception { String query = "SELECT * FROM r ORDER BY r.propStr"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); int pageSize = 3; - options.setMaxItemCount(pageSize); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.maxItemCount(pageSize); + Flux> queryObservable = createdCollection.queryItems(query, options); Comparator validatorComparator = Comparator.nullsFirst(Comparator.naturalOrder()); List expectedResourceIds = sortDocumentsAndCollectResourceIds("propStr", d -> d.getString("propStr"), validatorComparator); int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * minQueryRequestChargePerPartition) .build(); @@ -235,10 +226,10 @@ public Object[][] topValueParameter() { public void queryOrderWithTop(int topValue) throws Exception { String query = String.format("SELECT TOP %d * FROM r ORDER BY r.propInt", topValue); FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); int pageSize = 3; - options.setMaxItemCount(pageSize); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.maxItemCount(pageSize); + Flux> queryObservable = createdCollection.queryItems(query, options); Comparator validatorComparator = Comparator.nullsFirst(Comparator.naturalOrder()); @@ -248,10 +239,10 @@ public void queryOrderWithTop(int topValue) throws Exception { int expectedPageSize = expectedNumberOfPages(expectedResourceIds.size(), pageSize); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(expectedResourceIds) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .hasRequestChargeHeader().build()) .totalRequestChargeIsAtLeast(numberOfPartitions * (topValue > 0 ? minQueryRequestChargePerPartition : 1)) .build(); @@ -259,21 +250,21 @@ public void queryOrderWithTop(int topValue) throws Exception { validateQuerySuccess(queryObservable, validator); } - private List sortDocumentsAndCollectResourceIds(String propName, Function extractProp, Comparator comparer) { + private List sortDocumentsAndCollectResourceIds(String propName, Function extractProp, Comparator comparer) { return createdDocuments.stream() .filter(d -> d.getMap().containsKey(propName)) // removes undefined .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) - .map(d -> d.getResourceId()).collect(Collectors.toList()); + .map(d -> d.resourceId()).collect(Collectors.toList()); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void crossPartitionQueryNotEnabled() throws Exception { String query = "SELECT * FROM r ORDER BY r.propInt"; FeedOptions options = new FeedOptions(); - Flux> queryObservable = createdCollection.queryItems(query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) + .instanceOf(CosmosClientException.class) .statusCode(400) .build(); validateQueryFailure(queryObservable, validator); @@ -283,41 +274,41 @@ public void crossPartitionQueryNotEnabled() throws Exception { public void queryScopedToSinglePartition_StartWithContinuationToken() throws Exception { String query = "SELECT * FROM r ORDER BY r.propScopedPartitionInt ASC"; FeedOptions options = new FeedOptions(); - options.setPartitionKey(new PartitionKey("duplicateParitionKeyValue")); - options.setMaxItemCount(3); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.partitionKey(new PartitionKey("duplicateParitionKeyValue")); + options.maxItemCount(3); + Flux> queryObservable = createdCollection.queryItems(query, options); - TestSubscriber> subscriber = new TestSubscriber<>(); + TestSubscriber> subscriber = new TestSubscriber<>(); queryObservable.take(1).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertComplete(); subscriber.assertNoErrors(); assertThat(subscriber.valueCount()).isEqualTo(1); - FeedResponse page = (FeedResponse) subscriber.getEvents().get(0).get(0); - assertThat(page.getResults()).hasSize(3); + FeedResponse page = (FeedResponse) subscriber.getEvents().get(0).get(0); + assertThat(page.results()).hasSize(3); - assertThat(page.getResponseContinuation()).isNotEmpty(); + assertThat(page.continuationToken()).isNotEmpty(); - options.setRequestContinuation(page.getResponseContinuation()); + options.requestContinuation(page.continuationToken()); queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments.stream() + List expectedDocs = createdDocuments.stream() .filter(d -> (StringUtils.equals("duplicateParitionKeyValue", d.getString("mypk")))) .filter(d -> (d.getInt("propScopedPartitionInt") > 2)).collect(Collectors.toList()); - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); assertThat(expectedDocs).hasSize(10 - 3); - FeedResponseListValidator validator = null; + FeedResponseListValidator validator = null; - validator = new FeedResponseListValidator.Builder() + validator = new FeedResponseListValidator.Builder() .containsExactly(expectedDocs.stream() .sorted((e1, e2) -> Integer.compare(e1.getInt("propScopedPartitionInt"), e2.getInt("propScopedPartitionInt"))) - .map(d -> d.getResourceId()).collect(Collectors.toList())) + .map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -410,18 +401,18 @@ public void queryDocumentsWithInvalidOrderByContinuationTokensString(String sort this.assertInvalidContinuationToken(query, new int[] { 1, 5, 10, 100 }, expectedResourceIds); } - public CosmosItemSettings createDocument(CosmosContainer cosmosContainer, Map keyValueProps) - throws DocumentClientException { - CosmosItemSettings docDefinition = getDocumentDefinition(keyValueProps); - return cosmosContainer.createItem(docDefinition, new CosmosItemSettings()).block().getCosmosItemSettings(); + public CosmosItemProperties createDocument(CosmosContainer cosmosContainer, Map keyValueProps) + throws CosmosClientException { + CosmosItemProperties docDefinition = getDocumentDefinition(keyValueProps); + return cosmosContainer.createItem(docDefinition, new CosmosItemProperties()).block().properties(); } - public List bulkInsert(CosmosContainer cosmosContainer, List> keyValuePropsList) { + public List bulkInsert(CosmosContainer cosmosContainer, List> keyValuePropsList) { - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList(); for(Map keyValueProps: keyValuePropsList) { - CosmosItemSettings docDefinition = getDocumentDefinition(keyValueProps); + CosmosItemProperties docDefinition = getDocumentDefinition(keyValueProps); result.add(docDefinition); } @@ -460,16 +451,16 @@ public void beforeClass() throws Exception { for(int i = 0; i < 10; i++) { Map p = new HashMap<>(); p.put("propScopedPartitionInt", i); - CosmosItemSettings doc = getDocumentDefinition("duplicateParitionKeyValue", UUID.randomUUID().toString(), p); + CosmosItemProperties doc = getDocumentDefinition("duplicateParitionKeyValue", UUID.randomUUID().toString(), p); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(new PartitionKey(doc.get("mypk"))); - createdDocuments.add(createDocument(createdCollection, doc).read(options).block().getCosmosItemSettings()); + options.partitionKey(new PartitionKey(doc.get("mypk"))); + createdDocuments.add(createDocument(createdCollection, doc).read(options).block().properties()); } numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client) - .readPartitionKeyRanges("dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(), null) - .flatMap(p -> Observable.from(p.getResults())).toList().toBlocking().single().size(); + .readPartitionKeyRanges("dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(), null) + .flatMap(p -> Observable.from(p.results())).toList().toBlocking().single().size(); waitIfNeededForReplicasToCatchUp(clientBuilder); } @@ -483,9 +474,9 @@ private void assertInvalidContinuationToken(String query, int[] pageSize, List> queryObservable = createdCollection.queryItems(query, + options.requestContinuation(orderByContinuationToken.toString()); + Flux> queryObservable = createdCollection.queryItems(query, options); //Observable> firstPageObservable = queryObservable.first(); - TestSubscriber> testSubscriber = new TestSubscriber<>(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); queryObservable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); - testSubscriber.assertError(DocumentClientException.class); + testSubscriber.assertError(CosmosClientException.class); } while (requestContinuation != null); } private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, List expectedIds) { for (int pageSize : pageSizes) { - List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); + List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); List actualIds = new ArrayList(); - for (CosmosItemSettings document : receivedDocuments) { - actualIds.add(document.getResourceId()); + for (CosmosItemProperties document : receivedDocuments) { + actualIds.add(document.resourceId()); } assertThat(actualIds).containsExactlyElementsOf(expectedIds); } } - private List queryWithContinuationTokens(String query, int pageSize) { + private List queryWithContinuationTokens(String query, int pageSize) { String requestContinuation = null; List continuationTokens = new ArrayList(); - List receivedDocuments = new ArrayList(); + List receivedDocuments = new ArrayList(); do { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(pageSize); - options.setEnableCrossPartitionQuery(true); - options.setMaxDegreeOfParallelism(2); - options.setRequestContinuation(requestContinuation); - Flux> queryObservable = createdCollection.queryItems(query, + options.maxItemCount(pageSize); + options.enableCrossPartitionQuery(true); + options.maxDegreeOfParallelism(2); + options.requestContinuation(requestContinuation); + Flux> queryObservable = createdCollection.queryItems(query, options); //Observable> firstPageObservable = queryObservable.first(); - TestSubscriber> testSubscriber = new TestSubscriber<>(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); queryObservable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); - FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); - requestContinuation = firstPage.getResponseContinuation(); - receivedDocuments.addAll(firstPage.getResults()); + FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); + requestContinuation = firstPage.continuationToken(); + receivedDocuments.addAll(firstPage.results()); continuationTokens.add(requestContinuation); } while (requestContinuation != null); return receivedDocuments; } - private static CosmosItemSettings getDocumentDefinition(String partitionKey, String id, Map keyValuePair) { + private static CosmosItemProperties getDocumentDefinition(String partitionKey, String id, Map keyValuePair) { StringBuilder sb = new StringBuilder(); sb.append("{\n"); @@ -566,17 +557,17 @@ private static CosmosItemSettings getDocumentDefinition(String partitionKey, Str sb.append(String.format(" \"mypk\": \"%s\"\n", partitionKey)); sb.append("}"); - return new CosmosItemSettings(sb.toString()); + return new CosmosItemProperties(sb.toString()); } - private static CosmosItemSettings getDocumentDefinition(Map keyValuePair) { + private static CosmosItemProperties getDocumentDefinition(Map keyValuePair) { String uuid = UUID.randomUUID().toString(); return getDocumentDefinition(uuid, uuid, keyValuePair); } private static String toJson(Object object){ try { - return com.microsoft.azure.cosmosdb.internal.Utils.getSimpleObjectMapper().writeValueAsString(object); + return com.azure.data.cosmos.internal.Utils.getSimpleObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParallelDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java similarity index 68% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParallelDocumentQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java index 8f2a8b749c6b7..4cfc00a75d5e2 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParallelDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java @@ -20,15 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; - -import com.microsoft.azure.cosmos.CosmosBridgeInternal; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.BridgeInternal; +package com.azure.data.cosmos.rx; + +import com.azure.data.cosmos.*; + import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; @@ -42,17 +37,14 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.QueryMetrics; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.directconnectivity.Protocol; import org.testng.SkipException; import org.testng.annotations.DataProvider; -import com.microsoft.azure.cosmosdb.internal.routing.Range; -import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; -import com.microsoft.azure.cosmosdb.rx.internal.query.CompositeContinuationToken; +import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.internal.Utils.ValueHolder; +import com.azure.data.cosmos.internal.query.CompositeContinuationToken; import io.reactivex.subscribers.TestSubscriber; import reactor.core.publisher.Flux; @@ -63,12 +55,12 @@ public class ParallelDocumentQueryTest extends TestSuiteBase { private CosmosDatabase createdDatabase; private CosmosContainer createdCollection; - private List createdDocuments; + private List createdDocuments; private CosmosClient client; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); + return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } @Factory(dataProvider = "clientBuildersWithDirect") @@ -88,19 +80,19 @@ public Object[][] queryMetricsArgProvider() { public void queryDocuments(boolean qmEnabled) { String query = "SELECT * from c where c.prop = 99"; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(5); - options.setEnableCrossPartitionQuery(true); - options.setPopulateQueryMetrics(qmEnabled); - options.setMaxDegreeOfParallelism(2); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.maxItemCount(5); + options.enableCrossPartitionQuery(true); + options.populateQueryMetrics(qmEnabled); + options.maxDegreeOfParallelism(2); + Flux> queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments.stream().filter(d -> 99 == d.getInt("prop") ).collect(Collectors.toList()); + List expectedDocs = createdDocuments.stream().filter(d -> 99 == d.getInt("prop") ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) - .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .hasValidQueryMetrics(qmEnabled) .build(); @@ -108,8 +100,8 @@ public void queryDocuments(boolean qmEnabled) { try { validateQuerySuccess(queryObservable, validator, TIMEOUT); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format(String.format("Direct TCP test failure: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel())); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format(String.format("DIRECT TCP test failure: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel())); logger.info(message, error); throw new SkipException(message, error); } @@ -121,21 +113,21 @@ public void queryDocuments(boolean qmEnabled) { public void queryMetricEquality() throws Exception { String query = "SELECT * from c where c.prop = 99"; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(5); - options.setEnableCrossPartitionQuery(true); - options.setPopulateQueryMetrics(true); - options.setMaxDegreeOfParallelism(0); + options.maxItemCount(5); + options.enableCrossPartitionQuery(true); + options.populateQueryMetrics(true); + options.maxDegreeOfParallelism(0); - Flux> queryObservable = createdCollection.queryItems(query, options); - List> resultList1 = queryObservable.collectList().block(); + Flux> queryObservable = createdCollection.queryItems(query, options); + List> resultList1 = queryObservable.collectList().block(); - options.setMaxDegreeOfParallelism(4); - Flux> threadedQueryObs = createdCollection.queryItems(query, options); - List> resultList2 = threadedQueryObs.collectList().block(); + options.maxDegreeOfParallelism(4); + Flux> threadedQueryObs = createdCollection.queryItems(query, options); + List> resultList2 = threadedQueryObs.collectList().block(); assertThat(resultList1.size()).isEqualTo(resultList2.size()); for(int i = 0; i < resultList1.size(); i++){ - compareQueryMetrics(resultList1.get(i).getQueryMetrics(), resultList2.get(i).getQueryMetrics()); + compareQueryMetrics(resultList1.get(i).queryMetrics(), resultList2.get(i).queryMetrics()); } } @@ -156,20 +148,20 @@ private void compareQueryMetrics(Map qm1, Map> queryObservable = createdCollection.queryItems(query, options); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPagesIsGreaterThanOrEqualTo(1) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .pageSizeIsLessThanOrEqualTo(0) .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); } - // TODO: DANOBLE: Investigate Direct TCP performance issue + // TODO: DANOBLE: Investigate DIRECT TCP performance issue // See: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 @Test(groups = { "simple" }, timeOut = 2 * TIMEOUT) @@ -177,22 +169,22 @@ public void queryDocumentsWithPageSize() { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); int pageSize = 3; - options.setMaxItemCount(pageSize); - options.setMaxDegreeOfParallelism(-1); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.maxItemCount(pageSize); + options.maxDegreeOfParallelism(-1); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments; + List expectedDocs = createdDocuments; assertThat(expectedDocs).isNotEmpty(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() - .map(d -> d.getResourceId()) + .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPagesIsGreaterThanOrEqualTo((expectedDocs.size() + 1) / 3) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0) .pageSizeIsLessThanOrEqualTo(pageSize) .build()) @@ -200,8 +192,8 @@ public void queryDocumentsWithPageSize() { try { validateQuerySuccess(queryObservable, validator, 2 * subscriberValidationTimeout); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -213,11 +205,11 @@ public void queryDocumentsWithPageSize() { public void invalidQuerySyntax() { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(query, options); FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) + .instanceOf(CosmosClientException.class) .statusCode(400) .notNullActivityId() .build(); @@ -228,16 +220,16 @@ public void invalidQuerySyntax() { public void crossPartitionQueryNotEnabled() { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); - Flux> queryObservable = createdCollection.queryItems(query, options); + Flux> queryObservable = createdCollection.queryItems(query, options); FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) + .instanceOf(CosmosClientException.class) .statusCode(400) .build(); validateQueryFailure(queryObservable, validator); } - // TODO: DANOBLE: Investigate Direct TCP performance issue + // TODO: DANOBLE: Investigate DIRECT TCP performance issue // Links: // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 @@ -246,20 +238,20 @@ public void partitionKeyRangeId() { int sum = 0; try { for (String partitionKeyRangeId : CosmosBridgeInternal.getAsyncDocumentClient(client).readPartitionKeyRanges(getCollectionLink(), null) - .flatMap(p -> Observable.from(p.getResults())) - .map(pkr -> pkr.getId()).toList().toBlocking().single()) { + .flatMap(p -> Observable.from(p.results())) + .map(pkr -> pkr.id()).toList().toBlocking().single()) { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); - options.setPartitionKeyRangeIdInternal(partitionKeyRangeId); + options.partitionKeyRangeIdInternal(partitionKeyRangeId); int queryResultCount = createdCollection.queryItems(query, options) - .flatMap(p -> Flux.fromIterable(p.getResults())) + .flatMap(p -> Flux.fromIterable(p.results())) .collectList().block().size(); sum += queryResultCount; } } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -297,7 +289,7 @@ public void compositeContinuationTokenRoundTrip() throws Exception { } { - // Negative - Gateway composite continuation token + // Negative - GATEWAY composite continuation token ValueHolder outCompositeContinuationToken = new ValueHolder(); boolean succeeed = CompositeContinuationToken.tryParse("{\"token\":\"-RID:tZFQAImzNLQLAAAAAAAAAA==#RT:1#TRC:10\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}", outCompositeContinuationToken); assertThat(succeeed).isFalse(); @@ -310,7 +302,7 @@ public void queryDocumentsWithCompositeContinuationTokens() throws Exception { String query = "SELECT * FROM c"; // Get Expected - List expectedDocs = createdDocuments + List expectedDocs = createdDocuments .stream() .collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); @@ -318,14 +310,14 @@ public void queryDocumentsWithCompositeContinuationTokens() throws Exception { this.queryWithContinuationTokensAndPageSizes(query, new int[] {1, 10, 100}, expectedDocs); } - // TODO: DANOBLE: Investigate Direct TCP performance issue + // TODO: DANOBLE: Investigate DIRECT TCP performance issue // Links: // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 // Notes: // When I've watch this method execute in the debugger and seen that the code sometimes pauses for quite a while in // the middle of the second group of 21 documents. I test against a debug instance of the public emulator and so // what I'm seeing could be the result of a public emulator performance issue. Of course, it might also be the - // result of a Tcp protocol performance problem. + // result of a TCP protocol performance problem. @BeforeClass(groups = { "simple", "non-emulator" }, timeOut = 2 * SETUP_TIMEOUT) public void beforeClass() { @@ -333,7 +325,7 @@ public void beforeClass() { createdDatabase = getSharedCosmosDatabase(client); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); - List docDefList = new ArrayList<>(); + List docDefList = new ArrayList<>(); for(int i = 0; i < 13; i++) { docDefList.add(getDocumentDefinition(i)); } @@ -352,9 +344,9 @@ public void afterClass() { safeClose(client); } - private static CosmosItemSettings getDocumentDefinition(int cnt) { + private static CosmosItemProperties getDocumentDefinition(int cnt) { String uuid = UUID.randomUUID().toString(); - CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"prop\" : %d, " + "\"mypk\": \"%s\", " @@ -369,59 +361,59 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(query, options); - FailureValidator validator = new FailureValidator.Builder().instanceOf(DocumentClientException.class) + FailureValidator validator = new FailureValidator.Builder().instanceOf(CosmosClientException.class) .statusCode(400).notNullActivityId().build(); validateQueryFailure(queryObservable, validator); } - public CosmosItemSettings createDocument(CosmosContainer cosmosContainer, int cnt) throws DocumentClientException { + public CosmosItemProperties createDocument(CosmosContainer cosmosContainer, int cnt) throws CosmosClientException { - CosmosItemSettings docDefinition = getDocumentDefinition(cnt); + CosmosItemProperties docDefinition = getDocumentDefinition(cnt); - return cosmosContainer.createItem(docDefinition, new CosmosItemSettings()).block().getCosmosItemSettings(); + return cosmosContainer.createItem(docDefinition, new CosmosItemProperties()).block().properties(); } - private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, List expectedDocs) { + private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, List expectedDocs) { for (int pageSize : pageSizes) { - List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); + List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); List actualIds = new ArrayList(); - for (CosmosItemSettings document : receivedDocuments) { - actualIds.add(document.getResourceId()); + for (CosmosItemProperties document : receivedDocuments) { + actualIds.add(document.resourceId()); } List expectedIds = new ArrayList(); - for (CosmosItemSettings document : expectedDocs) { - expectedIds.add(document.getResourceId()); + for (CosmosItemProperties document : expectedDocs) { + expectedIds.add(document.resourceId()); } assertThat(actualIds).containsOnlyElementsOf(expectedIds); } } - private List queryWithContinuationTokens(String query, int pageSize) { + private List queryWithContinuationTokens(String query, int pageSize) { String requestContinuation = null; List continuationTokens = new ArrayList(); - List receivedDocuments = new ArrayList(); + List receivedDocuments = new ArrayList(); do { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(pageSize); - options.setEnableCrossPartitionQuery(true); - options.setMaxDegreeOfParallelism(2); - options.setRequestContinuation(requestContinuation); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.maxItemCount(pageSize); + options.enableCrossPartitionQuery(true); + options.maxDegreeOfParallelism(2); + options.requestContinuation(requestContinuation); + Flux> queryObservable = createdCollection.queryItems(query, options); - TestSubscriber> testSubscriber = new TestSubscriber<>(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); queryObservable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); - FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); - requestContinuation = firstPage.getResponseContinuation(); - receivedDocuments.addAll(firstPage.getResults()); + FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); + requestContinuation = firstPage.continuationToken(); + receivedDocuments.addAll(firstPage.results()); continuationTokens.add(requestContinuation); } while (requestContinuation != null); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParsingEnvTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java similarity index 79% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParsingEnvTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java index e0e0eb8d1c020..0c6b64c4a20cc 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ParsingEnvTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.directconnectivity.Protocol; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; @@ -33,8 +33,8 @@ public class ParsingEnvTest { @Test(groups = "unit") public void parseDesiredConsistencies() { - assertThat(TestSuiteBase.parseDesiredConsistencies("[ \"Session\" , \"Strong\" ]")).containsExactly( - ConsistencyLevel.Session, ConsistencyLevel.Strong); + assertThat(TestSuiteBase.parseDesiredConsistencies("[ \"SESSION\" , \"STRONG\" ]")).containsExactly( + ConsistencyLevel.SESSION, ConsistencyLevel.STRONG); } @Test(groups = "unit") @@ -44,8 +44,8 @@ public void parseDesiredConsistencies_null() { @Test(groups = "unit") public void lowerConsistencies() { - assertThat(TestSuiteBase.allEqualOrLowerConsistencies(ConsistencyLevel.Session)) - .containsExactly(ConsistencyLevel.Session, ConsistencyLevel.ConsistentPrefix, ConsistencyLevel.Eventual); + assertThat(TestSuiteBase.allEqualOrLowerConsistencies(ConsistencyLevel.SESSION)) + .containsExactly(ConsistencyLevel.SESSION, ConsistencyLevel.CONSISTENT_PREFIX, ConsistencyLevel.EVENTUAL); } @Test(groups = "unit") @@ -61,6 +61,6 @@ public void parsePreferredLocation_null() { @Test(groups = "unit") public void protocols() { - assertThat(TestSuiteBase.parseProtocols("[ \"Tcp\" , \"Https\" ]")).containsExactly(Protocol.Tcp, Protocol.Https); + assertThat(TestSuiteBase.parseProtocols("[ \"TCP\" , \"HTTPS\" ]")).containsExactly(Protocol.TCP, Protocol.HTTPS); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java similarity index 73% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java index bbc3ad2c18494..4c72653b8f015 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java @@ -20,28 +20,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.UUID; -import com.microsoft.azure.cosmosdb.Document; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.PermissionMode; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.PermissionMode; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.internal.TestSuiteBase; import rx.Observable; -import javax.net.ssl.SSLException; - //TODO: change to use external TestSuiteBase public class PermissionCrudTest extends TestSuiteBase { @@ -58,11 +55,11 @@ public PermissionCrudTest(AsyncDocumentClient.Builder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createPermission() throws Exception { - createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); + createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); //create permission Permission permission = new Permission(); - permission.setId(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.Read); + permission.id(UUID.randomUUID().toString()); + permission.setPermissionMode(PermissionMode.READ); permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); @@ -70,8 +67,8 @@ public void createPermission() throws Exception { // validate permission creation ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(permission.getId()) - .withPermissionMode(PermissionMode.Read) + .withId(permission.id()) + .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); @@ -80,22 +77,22 @@ public void createPermission() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readPermission() throws Exception { - createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); + createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); // create permission Permission permission = new Permission(); - permission.setId(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.Read); + permission.id(UUID.randomUUID().toString()); + permission.setPermissionMode(PermissionMode.READ); permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); Permission readBackPermission = client.createPermission(getUserLink(), permission, null).toBlocking().single().getResource(); // read Permission - Observable> readObservable = client.readPermission(readBackPermission.getSelfLink(), null); + Observable> readObservable = client.readPermission(readBackPermission.selfLink(), null); // validate permission read ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(permission.getId()) - .withPermissionMode(PermissionMode.Read) + .withId(permission.id()) + .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); @@ -105,17 +102,17 @@ public void readPermission() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deletePermission() throws Exception { - createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); + createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); // create permission Permission permission = new Permission(); - permission.setId(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.Read); + permission.id(UUID.randomUUID().toString()); + permission.setPermissionMode(PermissionMode.READ); permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); Permission readBackPermission = client.createPermission(getUserLink(), permission, null).toBlocking().single().getResource(); // delete - Observable> deleteObservable = client.deletePermission(readBackPermission.getSelfLink(), null); + Observable> deleteObservable = client.deletePermission(readBackPermission.selfLink(), null); // validate delete permission ResourceResponseValidator validator = new ResourceResponseValidator.Builder() @@ -126,7 +123,7 @@ public void deletePermission() throws Exception { waitIfNeededForReplicasToCatchUp(clientBuilder); // attempt to read the permission which was deleted - Observable> readObservable = client.readPermission(readBackPermission.getSelfLink(), null); + Observable> readObservable = client.readPermission(readBackPermission.selfLink(), null); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); validateFailure(readObservable, notFoundValidator); } @@ -134,36 +131,36 @@ public void deletePermission() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void upsertPermission() throws Exception { - createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); + createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); // create permission Permission permission = new Permission(); - permission.setId(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.Read); + permission.id(UUID.randomUUID().toString()); + permission.setPermissionMode(PermissionMode.READ); permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); Permission readBackPermission = client.upsertPermission(getUserLink(), permission, null).toBlocking().single().getResource(); // read Permission - Observable> readObservable = client.readPermission(readBackPermission.getSelfLink(), null); + Observable> readObservable = client.readPermission(readBackPermission.selfLink(), null); // validate permission creation ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() - .withId(readBackPermission.getId()) - .withPermissionMode(PermissionMode.Read) + .withId(readBackPermission.id()) + .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); validateSuccess(readObservable, validatorForRead); //update permission - readBackPermission.setPermissionMode(PermissionMode.All); + readBackPermission.setPermissionMode(PermissionMode.ALL); Observable> updateObservable = client.upsertPermission(getUserLink(), readBackPermission, null); // validate permission update ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() - .withId(readBackPermission.getId()) - .withPermissionMode(PermissionMode.All) + .withId(readBackPermission.id()) + .withPermissionMode(PermissionMode.ALL) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); @@ -173,36 +170,36 @@ public void upsertPermission() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void replacePermission() throws Exception { - createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); + createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); // create permission Permission permission = new Permission(); - permission.setId(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.Read); + permission.id(UUID.randomUUID().toString()); + permission.setPermissionMode(PermissionMode.READ); permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); Permission readBackPermission = client.createPermission(getUserLink(), permission, null).toBlocking().single().getResource(); // read Permission - Observable> readObservable = client.readPermission(readBackPermission.getSelfLink(), null); + Observable> readObservable = client.readPermission(readBackPermission.selfLink(), null); // validate permission creation ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() - .withId(readBackPermission.getId()) - .withPermissionMode(PermissionMode.Read) + .withId(readBackPermission.id()) + .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); validateSuccess(readObservable, validatorForRead); //update permission - readBackPermission.setPermissionMode(PermissionMode.All); + readBackPermission.setPermissionMode(PermissionMode.ALL); Observable> updateObservable = client.replacePermission(readBackPermission, null); // validate permission replace ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() - .withId(readBackPermission.getId()) - .withPermissionMode(PermissionMode.All) + .withId(readBackPermission.id()) + .withPermissionMode(PermissionMode.ALL) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); @@ -222,11 +219,11 @@ public void afterClass() { private static User getUserDefinition() { User user = new User(); - user.setId(UUID.randomUUID().toString()); + user.id(UUID.randomUUID().toString()); return user; } private String getUserLink() { - return createdUser.getSelfLink(); + return createdUser.selfLink(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java similarity index 79% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java index ea87e18cdce0a..c80f91265f294 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/PermissionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -29,26 +29,25 @@ import java.util.UUID; import java.util.stream.Collectors; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.PermissionMode; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.PermissionMode; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.internal.TestSuiteBase; import rx.Observable; -import javax.net.ssl.SSLException; - //TODO: change to use external TestSuiteBase public class PermissionQueryTest extends TestSuiteBase { @@ -68,22 +67,22 @@ public PermissionQueryTest(AsyncDocumentClient.Builder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryWithFilter() throws Exception { - String filterId = createdPermissions.get(0).getId(); + String filterId = createdPermissions.get(0).id(); String query = String.format("SELECT * from c where c.id = '%s'", filterId); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(5); + options.maxItemCount(5); Observable> queryObservable = client .queryPermissions(getUserLink(), query, options); - List expectedDocs = createdPermissions.stream().filter(sp -> filterId.equals(sp.getId()) ).collect(Collectors.toList()); + List expectedDocs = createdPermissions.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) - .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -96,7 +95,7 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); Observable> queryObservable = client .queryPermissions(getUserLink(), query, options); @@ -114,18 +113,18 @@ public void queryAll() throws Exception { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(3); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(3); + options.enableCrossPartitionQuery(true); Observable> queryObservable = client .queryPermissions(getUserLink(), query, options); - int expectedPageSize = (createdPermissions.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (createdPermissions.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator .Builder() .exactlyContainsInAnyOrder(createdPermissions .stream() - .map(d -> d.getResourceId()) + .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() @@ -138,12 +137,12 @@ public void queryAll() throws Exception { public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); Observable> queryObservable = client .queryPermissions(getUserLink(), query, options); FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) + .instanceOf(CosmosClientException.class) .statusCode(400) .notNullActivityId() .build(); @@ -154,9 +153,9 @@ public void invalidQuerySytax() throws Exception { public void beforeClass() { client = clientBuilder.build(); Database d = new Database(); - d.setId(databaseId); + d.id(databaseId); createdDatabase = createDatabase(client, d); - createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); + createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); for(int i = 0; i < 5; i++) { createdPermissions.add(createPermissions(client, i)); @@ -173,17 +172,17 @@ public void afterClass() { private static User getUserDefinition() { User user = new User(); - user.setId(UUID.randomUUID().toString()); + user.id(UUID.randomUUID().toString()); return user; } public Permission createPermissions(AsyncDocumentClient client, int index) { DocumentCollection collection = new DocumentCollection(); - collection.setId(UUID.randomUUID().toString()); + collection.id(UUID.randomUUID().toString()); Permission permission = new Permission(); - permission.setId(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.Read); + permission.id(UUID.randomUUID().toString()); + permission.setPermissionMode(PermissionMode.READ); permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgT" + Integer.toString(index) + "="); return client.createPermission(getUserLink(), permission, null).toBlocking().single().getResource(); @@ -194,10 +193,10 @@ private String getUserLink() { } private String getDatabaseId() { - return createdDatabase.getId(); + return createdDatabase.id(); } private String getUserId() { - return createdUser.getId(); + return createdUser.id(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ProxyHostTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java similarity index 83% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ProxyHostTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java index 79e9a38e23252..3f482593ce335 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ProxyHostTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.io.StringWriter; import java.lang.reflect.Method; @@ -39,19 +39,19 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.rx.proxy.HttpProxyServer; +import com.azure.data.cosmos.rx.proxy.HttpProxyServer; import reactor.core.publisher.Mono; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemResponse; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.CosmosItemResponse; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; import static org.assertj.core.api.Assertions.assertThat; @@ -96,16 +96,16 @@ public void createDocumentWithValidHttpProxy() throws Exception { CosmosClient clientWithRightProxy = null; try { ConnectionPolicy connectionPolicy =new ConnectionPolicy(); - connectionPolicy.setProxy(PROXY_HOST, PROXY_PORT); + connectionPolicy.proxy(PROXY_HOST, PROXY_PORT); clientWithRightProxy = CosmosClient.builder().endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .connectionPolicy(connectionPolicy) - .consistencyLevel(ConsistencyLevel.Session).build(); - CosmosItemSettings docDefinition = getDocumentDefinition(); - Mono createObservable = clientWithRightProxy.getDatabase(createdDatabase.getId()).getContainer(createdCollection.getId()) + .consistencyLevel(ConsistencyLevel.SESSION).build(); + CosmosItemProperties docDefinition = getDocumentDefinition(); + Mono createObservable = clientWithRightProxy.getDatabase(createdDatabase.id()).getContainer(createdCollection.id()) .createItem(docDefinition, new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) + .withId(docDefinition.id()) .build(); validateSuccess(createObservable, validator); } finally { @@ -129,16 +129,16 @@ public void createDocumentWithValidHttpProxyWithNettyWireLogging() throws Except Logger.getLogger(LogLevelTest.NETWORK_LOGGING_CATEGORY).addAppender(appender); ConnectionPolicy connectionPolicy =new ConnectionPolicy(); - connectionPolicy.setProxy(PROXY_HOST, PROXY_PORT); + connectionPolicy.proxy(PROXY_HOST, PROXY_PORT); clientWithRightProxy = CosmosClient.builder().endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .connectionPolicy(connectionPolicy) - .consistencyLevel(ConsistencyLevel.Session).build(); - CosmosItemSettings docDefinition = getDocumentDefinition(); - Mono createObservable = clientWithRightProxy.getDatabase(createdDatabase.getId()).getContainer(createdCollection.getId()) + .consistencyLevel(ConsistencyLevel.SESSION).build(); + CosmosItemProperties docDefinition = getDocumentDefinition(); + Mono createObservable = clientWithRightProxy.getDatabase(createdDatabase.id()).getContainer(createdCollection.id()) .createItem(docDefinition, new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) + .withId(docDefinition.id()) .build(); validateSuccess(createObservable, validator); @@ -174,9 +174,9 @@ public void afterMethod(Method method) { PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties")); } - private CosmosItemSettings getDocumentDefinition() { + private CosmosItemProperties getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedCollectionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java similarity index 81% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedCollectionsTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java index 54982a098e6fe..a4ef1c38ce56d 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedCollectionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java @@ -20,28 +20,28 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyDefinition; import reactor.core.publisher.Flux; @@ -67,15 +67,15 @@ public ReadFeedCollectionsTest(CosmosClientBuilder clientBuilder) { public void readCollections() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Flux> feedObservable = createdDatabase.listContainers(options); - int expectedPageSize = (createdCollections.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (createdCollections.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdCollections.size()) - .exactlyContainsInAnyOrder(createdCollections.stream().map(d -> d.read().block().getCosmosContainerSettings().getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(createdCollections.stream().map(d -> d.read().block().settings().resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -105,8 +105,8 @@ public CosmosContainer createCollections(CosmosDatabase database) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); - return database.createContainer(collection, new CosmosContainerRequestOptions()).block().getContainer(); + return database.createContainer(collection, new CosmosContainerRequestOptions()).block().container(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDatabasesTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java similarity index 84% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDatabasesTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java index 74e01f247ef94..07f4cd2eabbfe 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDatabasesTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.net.URISyntaxException; import java.util.ArrayList; @@ -28,17 +28,17 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosDatabaseRequestOptions; -import com.microsoft.azure.cosmos.CosmosDatabaseSettings; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosDatabaseRequestOptions; +import com.azure.data.cosmos.CosmosDatabaseSettings; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Flux; @@ -58,14 +58,14 @@ public ReadFeedDatabasesTest(CosmosClientBuilder clientBuilder) { public void readDatabases() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Flux> feedObservable = client.listDatabases(options); - int expectedPageSize = (allDatabases.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (allDatabases.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(allDatabases.size()) - .exactlyContainsInAnyOrder(allDatabases.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(allDatabases.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -78,7 +78,7 @@ public void readDatabases() throws Exception { public void beforeClass() throws URISyntaxException { client = clientBuilder.build(); allDatabases = client.listDatabases(null) - .map(frp -> frp.getResults()) + .map(frp -> frp.results()) .collectList() .map(list -> list.stream().flatMap(x -> x.stream()).collect(Collectors.toList())) .block(); @@ -90,13 +90,13 @@ public void beforeClass() throws URISyntaxException { public CosmosDatabaseSettings createDatabase(CosmosClient client) { CosmosDatabaseSettings db = new CosmosDatabaseSettings(UUID.randomUUID().toString()); - return client.createDatabase(db, new CosmosDatabaseRequestOptions()).block().getCosmosDatabaseSettings(); + return client.createDatabase(db, new CosmosDatabaseRequestOptions()).block().settings(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { for (int i = 0; i < 5; i ++) { - safeDeleteDatabase(client.getDatabase(createdDatabases.get(i).getId())); + safeDeleteDatabase(client.getDatabase(createdDatabases.get(i).id())); } safeClose(client); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDocumentsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java similarity index 76% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDocumentsTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java index 83620644114ac..61a6e47a90813 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedDocumentsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java @@ -20,16 +20,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Flux; @@ -47,7 +47,7 @@ public class ReadFeedDocumentsTest extends TestSuiteBase { private CosmosDatabase createdDatabase; private CosmosContainer createdCollection; - private List createdDocuments; + private List createdDocuments; private CosmosClient client; @@ -59,17 +59,17 @@ public ReadFeedDocumentsTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) public void readDocuments() { FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setMaxItemCount(2); + options.enableCrossPartitionQuery(true); + options.maxItemCount(2); - Flux> feedObservable = createdCollection.listItems(options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + Flux> feedObservable = createdCollection.listItems(options); + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdDocuments.size()) .numberOfPagesIsGreaterThanOrEqualTo(1) - .exactlyContainsInAnyOrder(createdDocuments.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .exactlyContainsInAnyOrder(createdDocuments.stream().map(d -> d.resourceId()).collect(Collectors.toList())) + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0) - .pageSizeIsLessThanOrEqualTo(options.getMaxItemCount()) + .pageSizeIsLessThanOrEqualTo(options.maxItemCount()) .build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -78,10 +78,10 @@ public void readDocuments() { @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) public void readDocuments_withoutEnableCrossPartitionQuery() { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); - Flux> feedObservable = createdCollection.listItems(options); - FailureValidator validator = FailureValidator.builder().instanceOf(DocumentClientException.class) + Flux> feedObservable = createdCollection.listItems(options); + FailureValidator validator = FailureValidator.builder().instanceOf(CosmosClientException.class) .statusCode(400) .errorMessageContains("Cross partition query is required but disabled." + " Please set x-ms-documentdb-query-enablecrosspartition to true," + @@ -97,7 +97,7 @@ public void beforeClass() { createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); - List docDefList = new ArrayList<>(); + List docDefList = new ArrayList<>(); for(int i = 0; i < 100; i++) { docDefList.add(getDocumentDefinition()); @@ -112,9 +112,9 @@ public void afterClass() { safeClose(client); } - private CosmosItemSettings getDocumentDefinition() { + private CosmosItemProperties getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" @@ -128,10 +128,10 @@ public String getCollectionLink() { } private String getCollectionId() { - return createdCollection.getId(); + return createdCollection.id(); } private String getDatabaseId() { - return createdDatabase.getId(); + return createdDatabase.id(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedExceptionHandlingTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java similarity index 89% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedExceptionHandlingTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java index e6e8327b81146..8eb0026e59835 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedExceptionHandlingTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java @@ -20,24 +20,24 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.mockito.Mockito; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosDatabaseSettings; -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosDatabaseSettings; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.FeedResponse; import io.reactivex.subscribers.TestSubscriber; import reactor.core.publisher.Flux; @@ -63,7 +63,7 @@ public void readFeedException() throws Exception { frps.add(BridgeInternal.createFeedResponse(dbs, null)); Flux> response = Flux.merge(Flux.fromIterable(frps)) - .mergeWith(Flux.error(new DocumentClientException(0))) + .mergeWith(Flux.error(new CosmosClientException(0))) .mergeWith(Flux.fromIterable(frps)); final CosmosClient mockClient = Mockito.spy(client); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedOffersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java similarity index 81% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedOffersTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java index f4f54e27647a6..d22d38a16d53d 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedOffersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java @@ -20,32 +20,30 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Offer; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.internal.TestSuiteBase; import rx.Observable; -import javax.net.ssl.SSLException; - //TODO: change to use external TestSuiteBase public class ReadFeedOffersTest extends TestSuiteBase { @@ -69,15 +67,15 @@ public ReadFeedOffersTest(AsyncDocumentClient.Builder clientBuilder) { public void readOffers() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Observable> feedObservable = client.readOffers(options); - int expectedPageSize = (allOffers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (allOffers.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(allOffers.size()) - .exactlyContainsInAnyOrder(allOffers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(allOffers.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -95,7 +93,7 @@ public void beforeClass() { } allOffers = client.readOffers(null) - .map(frp -> frp.getResults()) + .map(frp -> frp.results()) .toList() .map(list -> list.stream().flatMap(x -> x.stream()).collect(Collectors.toList())) .toBlocking() @@ -110,18 +108,18 @@ public void afterClass() { public DocumentCollection createCollections(AsyncDocumentClient client) { DocumentCollection collection = new DocumentCollection(); - collection.setId(UUID.randomUUID().toString()); + collection.id(UUID.randomUUID().toString()); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); collection.setPartitionKey(partitionKeyDef); return client.createCollection(getDatabaseLink(), collection, null).toBlocking().single().getResource(); } private String getDatabaseLink() { - return "dbs/" + createdDatabase.getId(); + return "dbs/" + createdDatabase.id(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPermissionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java similarity index 81% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPermissionsTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java index 3fcab18c1e425..7500611e3d8f8 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPermissionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java @@ -20,26 +20,27 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; +import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DatabaseForTest; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.PermissionMode; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.PermissionMode; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.internal.TestSuiteBase; import rx.Observable; @@ -63,16 +64,16 @@ public ReadFeedPermissionsTest(AsyncDocumentClient.Builder clientBuilder) { public void readPermissions() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Observable> feedObservable = client.readPermissions(getUserLink(), options); - int expectedPageSize = (createdPermissions.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (createdPermissions.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdPermissions.size()) .numberOfPages(expectedPageSize) - .exactlyContainsInAnyOrder(createdPermissions.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(createdPermissions.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -83,9 +84,9 @@ public void readPermissions() throws Exception { public void beforeClass() { client = clientBuilder.build(); Database d = new Database(); - d.setId(databaseId); + d.id(databaseId); createdDatabase = createDatabase(client, d); - createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); + createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); for(int i = 0; i < 5; i++) { createdPermissions.add(createPermissions(client, i)); @@ -102,14 +103,14 @@ public void afterClass() { private static User getUserDefinition() { User user = new User(); - user.setId(UUID.randomUUID().toString()); + user.id(UUID.randomUUID().toString()); return user; } public Permission createPermissions(AsyncDocumentClient client, int index) { Permission permission = new Permission(); - permission.setId(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.Read); + permission.id(UUID.randomUUID().toString()); + permission.setPermissionMode(PermissionMode.READ); permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgT" + Integer.toString(index) + "="); return client.createPermission(getUserLink(), permission, null).toBlocking().single().getResource(); } @@ -119,10 +120,10 @@ private String getUserLink() { } private String getDatabaseId() { - return createdDatabase.getId(); + return createdDatabase.id(); } private String getUserId() { - return createdUser.getId(); + return createdUser.id(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPkrTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java similarity index 83% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPkrTests.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java index e9207e83b3d87..65227ef707a37 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedPkrTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java @@ -20,21 +20,17 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.*; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosBridgeInternal; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKeyRange; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; import rx.Observable; @@ -54,7 +50,7 @@ public ReadFeedPkrTests(CosmosClientBuilder clientBuilder) { public void readPartitionKeyRanges() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Observable> feedObservable = client.readPartitionKeyRanges(getCollectionLink(), options); @@ -81,6 +77,6 @@ public void afterClass() { } private String getCollectionLink() { - return "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId(); + return "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedStoredProceduresTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java similarity index 83% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedStoredProceduresTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java index e0b46a7d8476b..f15380f41bc60 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedStoredProceduresTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java @@ -20,25 +20,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosStoredProcedureRequestOptions; -import com.microsoft.azure.cosmos.CosmosStoredProcedureSettings; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; +import com.azure.data.cosmos.CosmosStoredProcedureSettings; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Flux; @@ -58,18 +58,18 @@ public ReadFeedStoredProceduresTest(CosmosClientBuilder clientBuilder) { public void readStoredProcedures() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Flux> feedObservable = createdCollection.listStoredProcedures(options); - int expectedPageSize = (createdStoredProcedures.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (createdStoredProcedures.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator .Builder() .totalSize(createdStoredProcedures.size()) .exactlyContainsInAnyOrder(createdStoredProcedures .stream() - .map(d -> d.getResourceId()) + .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() @@ -98,8 +98,8 @@ public void afterClass() { public CosmosStoredProcedureSettings createStoredProcedures(CosmosContainer cosmosContainer) { CosmosStoredProcedureSettings sproc = new CosmosStoredProcedureSettings(); - sproc.setId(UUID.randomUUID().toString()); - sproc.setBody("function() {var x = 10;}"); - return cosmosContainer.createStoredProcedure(sproc, new CosmosStoredProcedureRequestOptions()).block().getStoredProcedureSettings(); + sproc.id(UUID.randomUUID().toString()); + sproc.body("function() {var x = 10;}"); + return cosmosContainer.createStoredProcedure(sproc, new CosmosStoredProcedureRequestOptions()).block().settings(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedTriggersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java similarity index 79% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedTriggersTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java index 406f3033b186f..6b596689bc247 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedTriggersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java @@ -20,27 +20,27 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosRequestOptions; -import com.microsoft.azure.cosmos.CosmosTriggerSettings; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.TriggerOperation; -import com.microsoft.azure.cosmosdb.TriggerType; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosRequestOptions; +import com.azure.data.cosmos.CosmosTriggerSettings; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.TriggerOperation; +import com.azure.data.cosmos.TriggerType; import reactor.core.publisher.Flux; @@ -60,18 +60,18 @@ public ReadFeedTriggersTest(CosmosClientBuilder clientBuilder) { public void readTriggers() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Flux> feedObservable = createdCollection.listTriggers(options); - int expectedPageSize = (createdTriggers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (createdTriggers.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator .Builder() .totalSize(createdTriggers.size()) .exactlyContainsInAnyOrder(createdTriggers .stream() - .map(d -> d.getResourceId()) + .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() @@ -100,10 +100,10 @@ public void afterClass() { public CosmosTriggerSettings createTriggers(CosmosContainer cosmosContainer) { CosmosTriggerSettings trigger = new CosmosTriggerSettings(); - trigger.setId(UUID.randomUUID().toString()); - trigger.setBody("function() {var x = 10;}"); - trigger.setTriggerOperation(TriggerOperation.Create); - trigger.setTriggerType(TriggerType.Pre); - return cosmosContainer.createTrigger(trigger, new CosmosRequestOptions()).block().getCosmosTriggerSettings(); + trigger.id(UUID.randomUUID().toString()); + trigger.body("function() {var x = 10;}"); + trigger.triggerOperation(TriggerOperation.CREATE); + trigger.triggerType(TriggerType.PRE); + return cosmosContainer.createTrigger(trigger, new CosmosRequestOptions()).block().settings(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUdfsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java similarity index 82% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUdfsTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java index 9e5fe1c2a5de1..2930a6360001f 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUdfsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java @@ -20,26 +20,26 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosRequestOptions; -import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionSettings; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosRequestOptions; +import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Flux; @@ -60,18 +60,18 @@ public ReadFeedUdfsTest(CosmosClientBuilder clientBuilder) { public void readUserDefinedFunctions() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Flux> feedObservable = createdCollection.listUserDefinedFunctions(options); - int expectedPageSize = (createdUserDefinedFunctions.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (createdUserDefinedFunctions.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator .Builder() .totalSize(createdUserDefinedFunctions.size()) .exactlyContainsInAnyOrder(createdUserDefinedFunctions .stream() - .map(d -> d.getResourceId()) + .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() @@ -100,9 +100,9 @@ public void afterClass() { public CosmosUserDefinedFunctionSettings createUserDefinedFunctions(CosmosContainer cosmosContainer) { CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); - udf.setId(UUID.randomUUID().toString()); - udf.setBody("function() {var x = 10;}"); - return cosmosContainer.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().getCosmosUserDefinedFunctionSettings(); + udf.id(UUID.randomUUID().toString()); + udf.body("function() {var x = 10;}"); + return cosmosContainer.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().settings(); } private String getCollectionLink() { @@ -110,10 +110,10 @@ private String getCollectionLink() { } private String getCollectionId() { - return createdCollection.getId(); + return createdCollection.id(); } private String getDatabaseId() { - return createdDatabase.getId(); + return createdDatabase.id(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUsersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java similarity index 82% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUsersTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java index f7e62b47932d7..bacf6f95fd08d 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ReadFeedUsersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java @@ -20,26 +20,26 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosUserSettings; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.RequestOptions; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosUserSettings; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.RequestOptions; import reactor.core.publisher.Flux; @@ -60,15 +60,15 @@ public ReadFeedUsersTest(CosmosClientBuilder clientBuilder) { public void readUsers() throws Exception { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); Flux> feedObservable = createdDatabase.listUsers(options); - int expectedPageSize = (createdUsers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (createdUsers.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdUsers.size()) - .exactlyContainsInAnyOrder(createdUsers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(createdUsers.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -96,7 +96,7 @@ public void afterClass() { public CosmosUserSettings createUsers(CosmosDatabase cosmosDatabase) { CosmosUserSettings user = new CosmosUserSettings(); - user.setId(UUID.randomUUID().toString()); - return cosmosDatabase.createUser(user, new RequestOptions()).block().getCosmosUserSettings(); + user.id(UUID.randomUUID().toString()); + return cosmosDatabase.createUser(user, new RequestOptions()).block().settings(); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ResourceTokenTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java similarity index 72% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ResourceTokenTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java index 83c94f829934e..aa66f6d61c12e 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/ResourceTokenTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java @@ -20,13 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.ArrayList; import java.util.List; import java.util.UUID; -import com.microsoft.azure.cosmosdb.DatabaseForTest; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.DatabaseForTest; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; @@ -35,19 +36,19 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.PermissionMode; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.PermissionMode; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.internal.TestSuiteBase; import rx.Observable; @@ -83,7 +84,7 @@ public class ResourceTokenTest extends TestSuiteBase { private AsyncDocumentClient client; - // All static string used in below test cases + // ALL static string used in below test cases private final static String DOCUMENT_DEFINITION = "{ 'id': 'doc%d', 'counter': '%d'}"; private final static String DOCUMENT_DEFINITION_WITH_PERMISSION_KEY = "{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}"; @@ -111,54 +112,54 @@ public ResourceTokenTest(AsyncDocumentClient.Builder clientBuilder) { public void beforeClass() throws Exception { client = clientBuilder.build(); Database d = new Database(); - d.setId(databaseId); + d.id(databaseId); createdDatabase = createDatabase(client, d); - // Create collection - createdCollection = createCollection(client, createdDatabase.getId(), getCollectionDefinitionWithPartitionKey(PARTITION_KEY_PATH_2)); - // Create document - createdDocument = createDocument(client, createdDatabase.getId(),createdCollection.getId(), getDocument()); - // Create collection with partition key - createdCollectionWithPartitionKey = createCollection(client, createdDatabase.getId(), getCollectionDefinitionWithPartitionKey(PARTITION_KEY_PATH_1)); - // Create document with partition key - createdDocumentWithPartitionKey = createDocument(client, createdDatabase.getId(), createdCollectionWithPartitionKey.getId(), + // CREATE collection + createdCollection = createCollection(client, createdDatabase.id(), getCollectionDefinitionWithPartitionKey(PARTITION_KEY_PATH_2)); + // CREATE document + createdDocument = createDocument(client, createdDatabase.id(),createdCollection.id(), getDocument()); + // CREATE collection with partition key + createdCollectionWithPartitionKey = createCollection(client, createdDatabase.id(), getCollectionDefinitionWithPartitionKey(PARTITION_KEY_PATH_1)); + // CREATE document with partition key + createdDocumentWithPartitionKey = createDocument(client, createdDatabase.id(), createdCollectionWithPartitionKey.id(), getDocumentDefinitionWithPartitionKey()); - // Create second document with partition key - createdDocumentWithPartitionKey2 = createDocument(client, createdDatabase.getId(),createdCollectionWithPartitionKey.getId(), + // CREATE second document with partition key + createdDocumentWithPartitionKey2 = createDocument(client, createdDatabase.id(),createdCollectionWithPartitionKey.id(), getDocumentDefinitionWithPartitionKey2()); - // Create user - createdUser = createUser(client, createdDatabase.getId(), getUserDefinition()); - // Create permission for collection + // CREATE user + createdUser = createUser(client, createdDatabase.id(), getUserDefinition()); + // CREATE permission for collection createdCollPermission = client.createPermission(getUserLink(), getCollPermission(), null).toBlocking().single() .getResource(); createdCollPermissionWithName = client.createPermission(getUserLink(), getCollPermissionWithName(), null).toBlocking().single() .getResource(); - // Create permission for document + // CREATE permission for document createdDocPermission = client.createPermission(getUserLink(), getDocPermission(), null).toBlocking().single() .getResource(); createdDocPermissionWithName = client.createPermission(getUserLink(), getDocPermissionWithName(), null).toBlocking().single() .getResource(); - // Create permission for document with partition key + // CREATE permission for document with partition key createdDocPermissionWithPartitionKey = client .createPermission(getUserLink(), getDocPermissionWithPartitionKey(), null).toBlocking().single() .getResource(); createdDocPermissionWithPartitionKeyWithName = client .createPermission(getUserLink(), getDocPermissionWithPartitionKeyWithName(), null).toBlocking().single() .getResource(); - // Create permission for document with partition key 2 + // CREATE permission for document with partition key 2 createdDocPermissionWithPartitionKey2 = client .createPermission(getUserLink(), getDocPermissionWithPartitionKey2(), null).toBlocking().single() .getResource(); createdDocPermissionWithPartitionKey2WithName = client .createPermission(getUserLink(), getDocPermissionWithPartitionKey2WithName(), null).toBlocking().single() .getResource(); - // Create permission for collection with partition key + // CREATE permission for collection with partition key createdColPermissionWithPartitionKey = client .createPermission(getUserLink(), getColPermissionWithPartitionKey(), null).toBlocking().single() .getResource(); createdColPermissionWithPartitionKeyWithName = client .createPermission(getUserLink(), getColPermissionWithPartitionKeyWithName(), null).toBlocking().single() .getResource(); - // Create permission for collection with partition key + // CREATE permission for collection with partition key createdColPermissionWithPartitionKey2 = client .createPermission(getUserLink(), getColPermissionWithPartitionKey2(), null).toBlocking().single() .getResource(); @@ -171,8 +172,8 @@ public void beforeClass() throws Exception { public Object[][] collectionAndPermissionData() { return new Object[][]{ //This test will try to read collection from its own permission and validate it, both with request Id and name. - {createdCollection.getSelfLink(), createdCollPermission}, - {Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()), createdDocPermissionWithName}, + {createdCollection.selfLink(), createdCollPermission}, + {Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()), createdDocPermissionWithName}, }; } @@ -180,30 +181,30 @@ public Object[][] collectionAndPermissionData() { public Object[][] documentAndPermissionData() { return new Object[][]{ //These tests will try to read document from its own permission and validate it, both with request Id and name. - {createdDocument.getSelfLink(), createdDocPermission, createdDocument.getId(), null}, - {Utils.getDocumentNameLink(createdDatabase.getId(), createdCollection.getId(), createdDocument.getId()), createdDocPermissionWithName, createdDocument.getId(), null}, + {createdDocument.selfLink(), createdDocPermission, createdDocument.id(), null}, + {Utils.getDocumentNameLink(createdDatabase.id(), createdCollection.id(), createdDocument.id()), createdDocPermissionWithName, createdDocument.id(), null}, //These tests will try to read document from its permission having partition key 1 and validate it, both with request Id and name. - {createdDocumentWithPartitionKey.getSelfLink(), createdDocPermissionWithPartitionKey, createdDocumentWithPartitionKey.getId(), PARTITION_KEY_VALUE}, - {Utils.getDocumentNameLink(createdDatabase.getId(), createdCollectionWithPartitionKey.getId(), createdDocumentWithPartitionKey.getId()), createdDocPermissionWithPartitionKeyWithName - , createdDocumentWithPartitionKey.getId(), PARTITION_KEY_VALUE}, + {createdDocumentWithPartitionKey.selfLink(), createdDocPermissionWithPartitionKey, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, + {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), createdDocPermissionWithPartitionKeyWithName + , createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, //These tests will try to read document from its permission having partition key 2 and validate it, both with request Id and name. - {createdDocumentWithPartitionKey2.getSelfLink(), createdDocPermissionWithPartitionKey2, createdDocumentWithPartitionKey2.getId(), PARTITION_KEY_VALUE_2}, - {Utils.getDocumentNameLink(createdDatabase.getId(), createdCollectionWithPartitionKey.getId(), createdDocumentWithPartitionKey2.getId()), - createdDocPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey2.getId(), PARTITION_KEY_VALUE_2}, + {createdDocumentWithPartitionKey2.selfLink(), createdDocPermissionWithPartitionKey2, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2}, + {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), + createdDocPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2}, // These tests will try to read document from its parent collection permission and validate it, both with request Id and name. - {createdDocument.getSelfLink(), createdCollPermission, createdDocument.getId(), null}, - {Utils.getDocumentNameLink(createdDatabase.getId(), createdCollection.getId(), createdDocument.getId()), createdCollPermissionWithName, createdDocument.getId(), null}, + {createdDocument.selfLink(), createdCollPermission, createdDocument.id(), null}, + {Utils.getDocumentNameLink(createdDatabase.id(), createdCollection.id(), createdDocument.id()), createdCollPermissionWithName, createdDocument.id(), null}, //This test will try to read document from collection permission having partition key 1 and validate it, both with request Id and name. - {createdDocumentWithPartitionKey.getSelfLink(), createdColPermissionWithPartitionKey, createdDocumentWithPartitionKey.getId(), PARTITION_KEY_VALUE}, - {Utils.getDocumentNameLink(createdDatabase.getId(), createdCollectionWithPartitionKey.getId(), createdDocumentWithPartitionKey.getId()), createdColPermissionWithPartitionKeyWithName, createdDocumentWithPartitionKey.getId(), PARTITION_KEY_VALUE}, + {createdDocumentWithPartitionKey.selfLink(), createdColPermissionWithPartitionKey, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, + {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), createdColPermissionWithPartitionKeyWithName, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, //This test will try to read document from collection permission having partition key 2 and validate it, both with request Id and name. - {createdDocumentWithPartitionKey2.getSelfLink(), createdColPermissionWithPartitionKey2, createdDocumentWithPartitionKey2.getId(), PARTITION_KEY_VALUE_2}, - {Utils.getDocumentNameLink(createdDatabase.getId(), createdCollectionWithPartitionKey.getId(), createdDocumentWithPartitionKey2.getId()), createdColPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey2.getId(), PARTITION_KEY_VALUE_2} + {createdDocumentWithPartitionKey2.selfLink(), createdColPermissionWithPartitionKey2, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2}, + {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), createdColPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2} }; } @@ -212,9 +213,9 @@ public Object[][] documentAndPermissionData() { public Object[][] documentAndPermissionDataForResourceNotFound() { return new Object[][]{ //This test will try to read document from its resource token directly and validate it. - {createdDocumentWithPartitionKey2.getSelfLink(), createdColPermissionWithPartitionKey, PARTITION_KEY_VALUE}, + {createdDocumentWithPartitionKey2.selfLink(), createdColPermissionWithPartitionKey, PARTITION_KEY_VALUE}, //This test will try to read document from its parent collection resource token directly and validate it. - {Utils.getDocumentNameLink(createdDatabase.getId(), createdCollectionWithPartitionKey.getId(), createdDocumentWithPartitionKey2.getId()), + {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), createdColPermissionWithPartitionKeyWithName, PARTITION_KEY_VALUE} }; } @@ -223,16 +224,16 @@ public Object[][] documentAndPermissionDataForResourceNotFound() { public Object[][] documentAndMultipleCollPermissionData() { return new Object[][]{ //These tests will try to read document from partition 1 with two collection permissions having different partition keys and validate it, both with request Id and name. - {createdDocumentWithPartitionKey.getSelfLink(), createdColPermissionWithPartitionKey, createdColPermissionWithPartitionKey2, createdDocumentWithPartitionKey.getId(), + {createdDocumentWithPartitionKey.selfLink(), createdColPermissionWithPartitionKey, createdColPermissionWithPartitionKey2, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, - {Utils.getDocumentNameLink(createdDatabase.getId(), createdCollectionWithPartitionKey.getId(), createdDocumentWithPartitionKey.getId()), createdColPermissionWithPartitionKeyWithName - , createdColPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey.getId(), PARTITION_KEY_VALUE}, + {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), createdColPermissionWithPartitionKeyWithName + , createdColPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, //These tests will try to read document from partition 1 with two collection permissions having different partition keys and validate it, both with request Id and name. - {createdDocumentWithPartitionKey2.getSelfLink(), createdColPermissionWithPartitionKey, createdColPermissionWithPartitionKey2, createdDocumentWithPartitionKey2.getId(), + {createdDocumentWithPartitionKey2.selfLink(), createdColPermissionWithPartitionKey, createdColPermissionWithPartitionKey2, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2}, - {Utils.getDocumentNameLink(createdDatabase.getId(), createdCollectionWithPartitionKey.getId(), createdDocumentWithPartitionKey2.getId()), createdColPermissionWithPartitionKeyWithName - , createdColPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey2.getId(), PARTITION_KEY_VALUE_2} + {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), createdColPermissionWithPartitionKeyWithName + , createdColPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2} }; } @@ -258,13 +259,13 @@ public void readCollectionFromPermissionFeed(String collectionUrl, Permission pe List permissionFeed = new ArrayList<>(); permissionFeed.add(permission); asyncClientResourceToken = new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) - .withPermissionFeed(permissionFeed).withConnectionPolicy(ConnectionPolicy.GetDefault()) - .withConsistencyLevel(ConsistencyLevel.Session).build(); + .withPermissionFeed(permissionFeed).withConnectionPolicy(ConnectionPolicy.defaultPolicy()) + .withConsistencyLevel(ConsistencyLevel.SESSION).build(); Observable> readObservable = asyncClientResourceToken .readCollection(collectionUrl, null); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(createdCollection.getId()).build(); + .withId(createdCollection.id()).build(); validateSuccess(readObservable, validator); } finally { safeClose(asyncClientResourceToken); @@ -283,8 +284,8 @@ public void readDocumentFromPermissionFeed(String documentUrl, Permission permis List permissionFeed = new ArrayList<>(); permissionFeed.add(permission); asyncClientResourceToken = new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) - .withPermissionFeed(permissionFeed).withConnectionPolicy(ConnectionPolicy.GetDefault()) - .withConsistencyLevel(ConsistencyLevel.Session).build(); + .withPermissionFeed(permissionFeed).withConnectionPolicy(ConnectionPolicy.defaultPolicy()) + .withConsistencyLevel(ConsistencyLevel.SESSION).build(); RequestOptions options = new RequestOptions(); if (StringUtils.isNotEmpty(partitionKey)) { options.setPartitionKey(new PartitionKey((String)partitionKey)); @@ -312,14 +313,14 @@ public void readDocumentFromResouceToken(String resourceToken) throws Exception try { asyncClientResourceToken = new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(resourceToken) - .withConnectionPolicy(ConnectionPolicy.GetDefault()).withConsistencyLevel(ConsistencyLevel.Session) + .withConnectionPolicy(ConnectionPolicy.defaultPolicy()).withConsistencyLevel(ConsistencyLevel.SESSION) .build(); RequestOptions options = new RequestOptions(); options.setPartitionKey(PartitionKey.None); Observable> readObservable = asyncClientResourceToken - .readDocument(createdDocument.getSelfLink(), options); + .readDocument(createdDocument.selfLink(), options); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(createdDocument.getId()).build(); + .withId(createdDocument.id()).build(); validateSuccess(readObservable, validator); } finally { safeClose(asyncClientResourceToken); @@ -339,8 +340,8 @@ public void readDocumentOfParKeyFromTwoCollPermissionWithDiffPartitionKeys(Strin permissionFeed.add(collPermission1); permissionFeed.add(collPermission2); asyncClientResourceToken = new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) - .withPermissionFeed(permissionFeed).withConnectionPolicy(ConnectionPolicy.GetDefault()) - .withConsistencyLevel(ConsistencyLevel.Session).build(); + .withPermissionFeed(permissionFeed).withConnectionPolicy(ConnectionPolicy.defaultPolicy()) + .withConsistencyLevel(ConsistencyLevel.SESSION).build(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(partitionKey)); Observable> readObservable = asyncClientResourceToken @@ -366,8 +367,8 @@ public void readDocumentFromCollPermissionWithDiffPartitionKey_ResourceNotFound( List permissionFeed = new ArrayList<>(); permissionFeed.add(permission); asyncClientResourceToken = new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) - .withPermissionFeed(permissionFeed).withConnectionPolicy(ConnectionPolicy.GetDefault()) - .withConsistencyLevel(ConsistencyLevel.Session).build(); + .withPermissionFeed(permissionFeed).withConnectionPolicy(ConnectionPolicy.defaultPolicy()) + .withConsistencyLevel(ConsistencyLevel.SESSION).build(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(partitionKey)); Observable> readObservable = asyncClientResourceToken @@ -393,14 +394,14 @@ public void readDocumentFromCollPermissionWithDiffPartitionKey_WithException() t permissionFeed.add(createdColPermissionWithPartitionKey); asyncClientResourceToken = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) - .withConnectionPolicy(ConnectionPolicy.GetDefault()) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConnectionPolicy(ConnectionPolicy.defaultPolicy()) + .withConsistencyLevel(ConsistencyLevel.SESSION) .withPermissionFeed(permissionFeed) .build(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(PARTITION_KEY_VALUE_2)); Observable> readObservable = asyncClientResourceToken - .readDocument(createdDocumentWithPartitionKey.getSelfLink(), options); + .readDocument(createdDocumentWithPartitionKey.selfLink(), options); FailureValidator validator = new FailureValidator.Builder().resourceTokenNotFound().build(); validateFailure(readObservable, validator); } finally { @@ -416,7 +417,7 @@ public void afterClass() { private static User getUserDefinition() { User user = new User(); - user.setId(USER_NAME); + user.id(USER_NAME); return user; } @@ -427,99 +428,99 @@ private static Document getDocument() { private Permission getCollPermission() { Permission permission = new Permission(); - permission.setId(PERMISSION_FOR_COLL); - permission.setPermissionMode(PermissionMode.Read); - permission.setResourceLink(createdCollection.getSelfLink()); + permission.id(PERMISSION_FOR_COLL); + permission.setPermissionMode(PermissionMode.READ); + permission.setResourceLink(createdCollection.selfLink()); return permission; } private Permission getCollPermissionWithName() { Permission permission = new Permission(); - permission.setId(PERMISSION_FOR_COLL_WITH_NAME); - permission.setPermissionMode(PermissionMode.Read); - permission.setResourceLink(Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId())); + permission.id(PERMISSION_FOR_COLL_WITH_NAME); + permission.setPermissionMode(PermissionMode.READ); + permission.setResourceLink(Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id())); return permission; } private Permission getDocPermission() { Permission permission = new Permission(); - permission.setId(PERMISSION_FOR_DOC); - permission.setPermissionMode(PermissionMode.Read); - permission.setResourceLink(createdDocument.getSelfLink()); + permission.id(PERMISSION_FOR_DOC); + permission.setPermissionMode(PermissionMode.READ); + permission.setResourceLink(createdDocument.selfLink()); return permission; } private Permission getDocPermissionWithName() { Permission permission = new Permission(); - permission.setId(PERMISSION_FOR_DOC_WITH_NAME); - permission.setPermissionMode(PermissionMode.Read); - permission.setResourceLink(Utils.getDocumentNameLink(createdDatabase.getId(),createdCollection.getId(),createdDocument.getId())); + permission.id(PERMISSION_FOR_DOC_WITH_NAME); + permission.setPermissionMode(PermissionMode.READ); + permission.setResourceLink(Utils.getDocumentNameLink(createdDatabase.id(),createdCollection.id(),createdDocument.id())); return permission; } private Permission getDocPermissionWithPartitionKey() { - String permissionStr = String.format(PERMISSION_DEFINITION, createdDocumentWithPartitionKey.getSelfLink(), + String permissionStr = String.format(PERMISSION_DEFINITION, createdDocumentWithPartitionKey.selfLink(), PARTITION_KEY_VALUE); Permission permission = new Permission(permissionStr); return permission; } private Permission getDocPermissionWithPartitionKeyWithName() { - String permissionStr = String.format(PERMISSION_DEFINITION, Utils.getDocumentNameLink(createdDatabase.getId(), createdCollectionWithPartitionKey.getId(), createdDocumentWithPartitionKey.getId()), + String permissionStr = String.format(PERMISSION_DEFINITION, Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), PARTITION_KEY_VALUE); Permission permission = new Permission(permissionStr); - permission.setId("PermissionForDocWithPartitionKeyWithName"); + permission.id("PermissionForDocWithPartitionKeyWithName"); return permission; } private Permission getDocPermissionWithPartitionKey2() { - String permissionStr = String.format(PERMISSION_DEFINITION, createdDocumentWithPartitionKey2.getSelfLink(), + String permissionStr = String.format(PERMISSION_DEFINITION, createdDocumentWithPartitionKey2.selfLink(), PARTITION_KEY_VALUE_2); Permission permission = new Permission(permissionStr); - permission.setId("PermissionForDocWithPartitionKey2"); + permission.id("PermissionForDocWithPartitionKey2"); return permission; } private Permission getDocPermissionWithPartitionKey2WithName() { - String permissionStr = String.format(PERMISSION_DEFINITION, Utils.getDocumentNameLink(createdDatabase.getId(),createdCollectionWithPartitionKey.getId(),createdDocumentWithPartitionKey2.getId()), + String permissionStr = String.format(PERMISSION_DEFINITION, Utils.getDocumentNameLink(createdDatabase.id(),createdCollectionWithPartitionKey.id(),createdDocumentWithPartitionKey2.id()), PARTITION_KEY_VALUE_2); Permission permission = new Permission(permissionStr); - permission.setId("PermissionForDocWithPartitionKey2WithName"); + permission.id("PermissionForDocWithPartitionKey2WithName"); return permission; } private Permission getColPermissionWithPartitionKey() { - String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, createdCollectionWithPartitionKey.getSelfLink(), + String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, createdCollectionWithPartitionKey.selfLink(), PARTITION_KEY_VALUE); Permission permission = new Permission(permissionStr); return permission; } private Permission getColPermissionWithPartitionKeyWithName() { - String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, Utils.getCollectionNameLink(createdDatabase.getId(), createdCollectionWithPartitionKey.getId()), + String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, Utils.getCollectionNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id()), PARTITION_KEY_VALUE); Permission permission = new Permission(permissionStr); - permission.setId("PermissionForColWithPartitionKeyWithName"); + permission.id("PermissionForColWithPartitionKeyWithName"); return permission; } private Permission getColPermissionWithPartitionKey2() { - String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, createdCollectionWithPartitionKey.getSelfLink(), + String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, createdCollectionWithPartitionKey.selfLink(), PARTITION_KEY_VALUE_2); Permission permission = new Permission(permissionStr); - permission.setId("PermissionForColWithPartitionKey2"); + permission.id("PermissionForColWithPartitionKey2"); return permission; } private Permission getColPermissionWithPartitionKey2WithName() { - String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, Utils.getCollectionNameLink(createdDatabase.getId(), createdCollectionWithPartitionKey.getId()), + String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, Utils.getCollectionNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id()), PARTITION_KEY_VALUE_2); Permission permission = new Permission(permissionStr); - permission.setId("PermissionForColWithPartitionKey2WithName"); + permission.id("PermissionForColWithPartitionKey2WithName"); return permission; } private String getUserLink() { - return createdUser.getSelfLink(); + return createdUser.selfLink(); } private Document getDocumentDefinitionWithPartitionKey() { @@ -537,10 +538,10 @@ private DocumentCollection getCollectionDefinitionWithPartitionKey(String pkDefP PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add(pkDefPath); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); DocumentCollection collectionDefinition = new DocumentCollection(); - collectionDefinition.setId(UUID.randomUUID().toString()); + collectionDefinition.id(UUID.randomUUID().toString()); collectionDefinition.setPartitionKey(partitionKeyDef); return collectionDefinition; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SimpleSerializationTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java similarity index 95% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SimpleSerializationTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java index 18ae2b0e59784..c3f2dba117a3e 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SimpleSerializationTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonGenerator; @@ -28,9 +28,9 @@ import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; import org.apache.commons.lang3.NotImplementedException; import org.testng.Assert; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java similarity index 62% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionDocumentQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java index e2b5e4fa43d46..fd0f10abb6de8 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -29,11 +29,8 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmosdb.SqlParameter; -import com.microsoft.azure.cosmosdb.SqlParameterCollection; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.directconnectivity.Protocol; import io.reactivex.subscribers.TestSubscriber; import reactor.core.publisher.Flux; @@ -44,25 +41,18 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClientException; public class SinglePartitionDocumentQueryTest extends TestSuiteBase { private Database createdDatabase; private CosmosContainer createdCollection; - private List createdDocuments = new ArrayList<>(); + private List createdDocuments = new ArrayList<>(); private CosmosClient client; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); + return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } @Factory(dataProvider = "clientBuildersWithDirect") @@ -76,21 +66,21 @@ public void queryDocuments(boolean queryMetricsEnabled) throws Exception { String query = "SELECT * from c where c.prop = 99"; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(5); - options.setEnableCrossPartitionQuery(true); - options.setPopulateQueryMetrics(queryMetricsEnabled); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.maxItemCount(5); + options.enableCrossPartitionQuery(true); + options.populateQueryMetrics(queryMetricsEnabled); + Flux> queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments.stream().filter(d -> 99 == d.getInt("prop") ).collect(Collectors.toList()); + List expectedDocs = createdDocuments.stream().filter(d -> 99 == d.getInt("prop") ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) - .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .hasValidQueryMetrics(queryMetricsEnabled) .build(); @@ -98,8 +88,8 @@ public void queryDocuments(boolean queryMetricsEnabled) throws Exception { try { validateQuerySuccess(queryObservable, validator, 10000); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -114,28 +104,28 @@ public void queryDocuments_ParameterizedQueryWithInClause() throws Exception { SqlQuerySpec sqs = new SqlQuerySpec(query, params); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(5); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryItems(sqs, options); + options.maxItemCount(5); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(sqs, options); - List expectedDocs = createdDocuments.stream().filter(d -> (3 == d.getInt("prop") || 4 == d.getInt("prop"))).collect(Collectors.toList()); + List expectedDocs = createdDocuments.stream().filter(d -> (3 == d.getInt("prop") || 4 == d.getInt("prop"))).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) - .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); try { validateQuerySuccess(queryObservable, validator, 10000); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -150,28 +140,28 @@ public void queryDocuments_ParameterizedQuery() throws Exception { SqlQuerySpec sqs = new SqlQuerySpec(query, params); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(5); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryItems(sqs, options); + options.maxItemCount(5); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(sqs, options); - List expectedDocs = createdDocuments.stream().filter(d -> 3 == d.getInt("prop")).collect(Collectors.toList()); + List expectedDocs = createdDocuments.stream().filter(d -> 3 == d.getInt("prop")).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) - .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); try { validateQuerySuccess(queryObservable, validator, 10000); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -184,13 +174,13 @@ public void queryDocuments_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -201,29 +191,29 @@ public void queryDocumentsWithPageSize() throws Exception { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(3); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.maxItemCount(3); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments; - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + List expectedDocs = createdDocuments; + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .exactlyContainsInAnyOrder(createdDocuments .stream() - .map(d -> d.getResourceId()) + .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); try { validateQuerySuccess(queryObservable, validator); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -236,27 +226,27 @@ public void queryOrderBy() throws Exception { String query = "SELECT * FROM r ORDER BY r.prop ASC"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setMaxItemCount(3); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.enableCrossPartitionQuery(true); + options.maxItemCount(3); + Flux> queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments; - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + List expectedDocs = createdDocuments; + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(createdDocuments.stream() .sorted((e1, e2) -> Integer.compare(e1.getInt("prop"), e2.getInt("prop"))) - .map(d -> d.getResourceId()).collect(Collectors.toList())) + .map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); try { validateQuerySuccess(queryObservable, validator); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -268,37 +258,37 @@ public void queryOrderBy() throws Exception { public void continuationToken() throws Exception { String query = "SELECT * FROM r ORDER BY r.prop ASC"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setMaxItemCount(3); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.enableCrossPartitionQuery(true); + options.maxItemCount(3); + Flux> queryObservable = createdCollection.queryItems(query, options); - TestSubscriber> subscriber = new TestSubscriber<>(); + TestSubscriber> subscriber = new TestSubscriber<>(); queryObservable.take(1).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertComplete(); subscriber.assertNoErrors(); assertThat(subscriber.valueCount()).isEqualTo(1); - FeedResponse page = ((FeedResponse) subscriber.getEvents().get(0).get(0)); - assertThat(page.getResults()).hasSize(3); + FeedResponse page = ((FeedResponse) subscriber.getEvents().get(0).get(0)); + assertThat(page.results()).hasSize(3); - assertThat(page.getResponseContinuation()).isNotEmpty(); + assertThat(page.continuationToken()).isNotEmpty(); - options.setRequestContinuation(page.getResponseContinuation()); + options.requestContinuation(page.continuationToken()); queryObservable = createdCollection.queryItems(query, options); - List expectedDocs = createdDocuments.stream().filter(d -> (d.getInt("prop") > 2)).collect(Collectors.toList()); - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + List expectedDocs = createdDocuments.stream().filter(d -> (d.getInt("prop") > 2)).collect(Collectors.toList()); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); assertThat(expectedDocs).hasSize(createdDocuments.size() -3); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(expectedDocs.stream() .sorted((e1, e2) -> Integer.compare(e1.getInt("prop"), e2.getInt("prop"))) - .map(d -> d.getResourceId()).collect(Collectors.toList())) + .map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -308,20 +298,20 @@ public void continuationToken() throws Exception { public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.enableCrossPartitionQuery(true); + Flux> queryObservable = createdCollection.queryItems(query, options); FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) + .instanceOf(CosmosClientException.class) .statusCode(400) .notNullActivityId() .build(); validateQueryFailure(queryObservable, validator); } - public CosmosItemSettings createDocument(CosmosContainer cosmosContainer, int cnt) { - CosmosItemSettings docDefinition = getDocumentDefinition(cnt); - return cosmosContainer.createItem(docDefinition, new CosmosItemRequestOptions()).block().getCosmosItemSettings(); + public CosmosItemProperties createDocument(CosmosContainer cosmosContainer, int cnt) { + CosmosItemProperties docDefinition = getDocumentDefinition(cnt); + return cosmosContainer.createItem(docDefinition, new CosmosItemRequestOptions()).block().properties(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) @@ -346,9 +336,9 @@ public void afterClass() { safeClose(client); } - private static CosmosItemSettings getDocumentDefinition(int cnt) { + private static CosmosItemProperties getDocumentDefinition(int cnt) { String uuid = UUID.randomUUID().toString(); - CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"prop\" : %d, " + "\"mypk\": \"%s\", " diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionReadFeedDocumentsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java similarity index 75% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionReadFeedDocumentsTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java index df1d077dc382f..6ce5cdec20a58 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/SinglePartitionReadFeedDocumentsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java @@ -20,14 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Flux; @@ -44,7 +44,7 @@ public class SinglePartitionReadFeedDocumentsTest extends TestSuiteBase { private CosmosContainer createdCollection; - private List createdDocuments; + private List createdDocuments; private CosmosClient client; @@ -56,16 +56,16 @@ public SinglePartitionReadFeedDocumentsTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) public void readDocuments() { final FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setMaxItemCount(2); - final Flux> feedObservable = createdCollection.listItems(options); - final int expectedPageSize = (createdDocuments.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + options.enableCrossPartitionQuery(true); + options.maxItemCount(2); + final Flux> feedObservable = createdCollection.listItems(options); + final int expectedPageSize = (createdDocuments.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdDocuments.size()) .numberOfPages(expectedPageSize) - .exactlyContainsInAnyOrder(createdDocuments.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .exactlyContainsInAnyOrder(createdDocuments.stream().map(d -> d.resourceId()).collect(Collectors.toList())) + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -77,7 +77,7 @@ public void beforeClass() { createdCollection = getSharedSinglePartitionCosmosContainer(client); truncateCollection(createdCollection); - List docDefList = new ArrayList<>(); + List docDefList = new ArrayList<>(); for(int i = 0; i < 5; i++) { docDefList.add(getDocumentDefinition()); @@ -92,9 +92,9 @@ public void afterClass() { safeClose(client); } - private CosmosItemSettings getDocumentDefinition() { + private CosmosItemProperties getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - CosmosItemSettings doc = new CosmosItemSettings(String.format("{ " + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java similarity index 81% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java index df2b779d0a066..df45db1efb007 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java @@ -20,24 +20,24 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.UUID; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosResponse; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmos.CosmosStoredProcedure; -import com.microsoft.azure.cosmos.CosmosStoredProcedureRequestOptions; -import com.microsoft.azure.cosmos.CosmosStoredProcedureResponse; -import com.microsoft.azure.cosmos.CosmosStoredProcedureSettings; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosResponse; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosStoredProcedure; +import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; +import com.azure.data.cosmos.CosmosStoredProcedureResponse; +import com.azure.data.cosmos.CosmosStoredProcedureSettings; import reactor.core.publisher.Mono; @@ -57,14 +57,14 @@ public void createStoredProcedure() throws Exception { // create a stored procedure CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); - storedProcedureDef.setId(UUID.randomUUID().toString()); - storedProcedureDef.setBody("function() {var x = 10;}"); + storedProcedureDef.id(UUID.randomUUID().toString()); + storedProcedureDef.body("function() {var x = 10;}"); Mono createObservable = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()); // validate stored procedure creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(storedProcedureDef.getId()) + .withId(storedProcedureDef.id()) .withStoredProcedureBody("function() {var x = 10;}") .notNullEtag() .build(); @@ -75,17 +75,17 @@ public void createStoredProcedure() throws Exception { public void readStoredProcedure() throws Exception { // create a stored procedure CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); - storedProcedureDef.setId(UUID.randomUUID().toString()); - storedProcedureDef.setBody("function() {var x = 10;}"); + storedProcedureDef.id(UUID.randomUUID().toString()); + storedProcedureDef.body("function() {var x = 10;}"); CosmosStoredProcedure storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()) - .block().getStoredProcedure(); + .block().storedProcedure(); // read stored procedure waitIfNeededForReplicasToCatchUp(clientBuilder); Mono readObservable = storedProcedure.read(null); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(storedProcedureDef.getId()) + .withId(storedProcedureDef.id()) .withStoredProcedureBody("function() {var x = 10;}") .notNullEtag() .build(); @@ -96,10 +96,10 @@ public void readStoredProcedure() throws Exception { public void deleteStoredProcedure() throws Exception { // create a stored procedure CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); - storedProcedureDef.setId(UUID.randomUUID().toString()); - storedProcedureDef.setBody("function() {var x = 10;}"); + storedProcedureDef.id(UUID.randomUUID().toString()); + storedProcedureDef.body("function() {var x = 10;}"); CosmosStoredProcedure storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()) - .block().getStoredProcedure(); + .block().storedProcedure(); // delete Mono deleteObservable = storedProcedure.delete(new CosmosStoredProcedureRequestOptions()); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java similarity index 81% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java index acdbdb61ebedc..84900152f62db 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -29,8 +29,9 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.directconnectivity.Protocol; import reactor.core.publisher.Flux; @@ -40,12 +41,11 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosStoredProcedureSettings; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosStoredProcedureSettings; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; public class StoredProcedureQueryTest extends TestSuiteBase { @@ -62,21 +62,21 @@ public StoredProcedureQueryTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryWithFilter() throws Exception { - String filterId = createdStoredProcs.get(0).getId(); + String filterId = createdStoredProcs.get(0).id(); String query = String.format("SELECT * from c where c.id = '%s'", filterId); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(5); + options.maxItemCount(5); Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); - List expectedDocs = createdStoredProcs.stream().filter(sp -> filterId.equals(sp.getId()) ).collect(Collectors.toList()); + List expectedDocs = createdStoredProcs.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) - .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -85,8 +85,8 @@ public void queryWithFilter() throws Exception { try { validateQuerySuccess(queryObservable, validator, 10000); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -99,7 +99,7 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() @@ -116,19 +116,19 @@ public void queryAll() throws Exception { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(3); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(3); + options.enableCrossPartitionQuery(true); Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); List expectedDocs = createdStoredProcs; - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() - .map(d -> d.getResourceId()) + .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() @@ -138,8 +138,8 @@ public void queryAll() throws Exception { try { validateQuerySuccess(queryObservable, validator); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -151,11 +151,11 @@ public void queryAll() throws Exception { public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) + .instanceOf(CosmosClientException.class) .statusCode(400) .notNullActivityId() .build(); @@ -164,7 +164,7 @@ public void invalidQuerySytax() throws Exception { public CosmosStoredProcedureSettings createStoredProc(CosmosContainer cosmosContainer) { CosmosStoredProcedureSettings storedProcedure = getStoredProcedureDef(); - return cosmosContainer.createStoredProcedure(storedProcedure).block().getStoredProcedureSettings(); + return cosmosContainer.createStoredProcedure(storedProcedure).block().settings(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) @@ -187,8 +187,8 @@ public void afterClass() { private static CosmosStoredProcedureSettings getStoredProcedureDef() { CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); - storedProcedureDef.setId(UUID.randomUUID().toString()); - storedProcedureDef.setBody("function() {var x = 10;}"); + storedProcedureDef.id(UUID.randomUUID().toString()); + storedProcedureDef.body("function() {var x = 10;}"); return storedProcedureDef; } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java similarity index 79% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureUpsertReplaceTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java index 00fc53360ed12..e30089fd1c7e1 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/StoredProcedureUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java @@ -20,14 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; import java.util.UUID; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.directconnectivity.Protocol; import reactor.core.publisher.Mono; @@ -37,15 +37,15 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmos.CosmosStoredProcedure; -import com.microsoft.azure.cosmos.CosmosStoredProcedureRequestOptions; -import com.microsoft.azure.cosmos.CosmosStoredProcedureResponse; -import com.microsoft.azure.cosmos.CosmosStoredProcedureSettings; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.RequestOptions; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosStoredProcedure; +import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; +import com.azure.data.cosmos.CosmosStoredProcedureResponse; +import com.azure.data.cosmos.CosmosStoredProcedureSettings; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.RequestOptions; public class StoredProcedureUpsertReplaceTest extends TestSuiteBase { @@ -63,30 +63,30 @@ public void replaceStoredProcedure() throws Exception { // create a stored procedure CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); - storedProcedureDef.setId(UUID.randomUUID().toString()); - storedProcedureDef.setBody("function() {var x = 10;}"); - CosmosStoredProcedureSettings readBackSp = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().getStoredProcedureSettings(); + storedProcedureDef.id(UUID.randomUUID().toString()); + storedProcedureDef.body("function() {var x = 10;}"); + CosmosStoredProcedureSettings readBackSp = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().settings(); // read stored procedure to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder); - Mono readObservable = createdCollection.getStoredProcedure(readBackSp.getId()).read(null); + Mono readObservable = createdCollection.getStoredProcedure(readBackSp.id()).read(null); // validate stored procedure creation CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() - .withId(readBackSp.getId()) + .withId(readBackSp.id()) .withStoredProcedureBody("function() {var x = 10;}") .notNullEtag() .build(); validateSuccess(readObservable, validatorForRead); //update stored procedure - readBackSp.setBody("function() {var x = 11;}"); + readBackSp.body("function() {var x = 11;}"); - Mono replaceObservable = createdCollection.getStoredProcedure(readBackSp.getId()).replace(readBackSp, new RequestOptions()); + Mono replaceObservable = createdCollection.getStoredProcedure(readBackSp.id()).replace(readBackSp, new RequestOptions()); //validate stored procedure replace CosmosResponseValidator validatorForReplace = new CosmosResponseValidator.Builder() - .withId(readBackSp.getId()) + .withId(readBackSp.id()) .withStoredProcedureBody("function() {var x = 11;}") .notNullEtag() .build(); @@ -110,10 +110,10 @@ public void executeStoredProcedure() throws Exception { CosmosStoredProcedure storedProcedure = null; try { - storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().getStoredProcedure(); + storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -125,10 +125,10 @@ public void executeStoredProcedure() throws Exception { try { RequestOptions options = new RequestOptions(); options.setPartitionKey(PartitionKey.None); - result = storedProcedure.execute(null, options).block().getResponseAsString(); + result = storedProcedure.execute(null, options).block().responseAsString(); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java similarity index 80% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index ceb94dabf8877..17374b62bc9a9 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doAnswer; @@ -36,22 +36,17 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.internal.Utils; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.Index; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.RetryOptions; -import com.microsoft.azure.cosmosdb.SqlQuerySpec; -import com.microsoft.azure.cosmosdb.internal.PathParser; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; -import com.microsoft.azure.cosmosdb.rx.internal.Configs; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.PathParser; +import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.Configs; import io.reactivex.subscribers.TestSubscriber; import reactor.core.publisher.Flux; @@ -69,34 +64,6 @@ import org.testng.annotations.BeforeSuite; import org.testng.annotations.DataProvider; -import com.microsoft.azure.cosmos.CosmosBridgeInternal; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseResponse; -import com.microsoft.azure.cosmos.CosmosDatabaseSettings; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmos.CosmosRequestOptions; -import com.microsoft.azure.cosmos.CosmosResponse; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmos.CosmosUser; -import com.microsoft.azure.cosmos.CosmosUserSettings; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import com.microsoft.azure.cosmosdb.CompositePath; -import com.microsoft.azure.cosmosdb.CompositePathSortOrder; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; - import org.testng.annotations.Test; public class TestSuiteBase { @@ -149,7 +116,7 @@ protected static CosmosContainer getSharedSinglePartitionCosmosContainer(CosmosC allEqualOrLowerConsistencies(accountConsistency))); preferredLocations = immutableListOrNull(parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS)); protocols = ObjectUtils.defaultIfNull(immutableListOrNull(parseProtocols(TestConfigurations.PROTOCOLS)), - ImmutableList.of(Protocol.Https, Protocol.Tcp)); + ImmutableList.of(Protocol.HTTPS, Protocol.TCP)); } protected TestSuiteBase() { @@ -169,7 +136,7 @@ public void beforeMethod(Method method) { if (this.clientBuilder != null) { logger.info("Starting {}::{} using {} {} mode with {} consistency", method.getDeclaringClass().getSimpleName(), method.getName(), - this.clientBuilder.getConnectionPolicy().getConnectionMode(), + this.clientBuilder.getConnectionPolicy().connectionMode(), this.clientBuilder.getConfigs().getProtocol(), this.clientBuilder.getDesiredConsistencyLevel()); return; @@ -237,21 +204,21 @@ public static void afterSuite() { } protected static void truncateCollection(CosmosContainer cosmosContainer) { - CosmosContainerSettings cosmosContainerSettings = cosmosContainer.read().block().getCosmosContainerSettings(); - String cosmosContainerId = cosmosContainerSettings.getId(); + CosmosContainerSettings cosmosContainerSettings = cosmosContainer.read().block().settings(); + String cosmosContainerId = cosmosContainerSettings.id(); logger.info("Truncating collection {} ...", cosmosContainerId); CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); try { - List paths = cosmosContainerSettings.getPartitionKey().getPaths(); + List paths = cosmosContainerSettings.partitionKey().paths(); FeedOptions options = new FeedOptions(); - options.setMaxDegreeOfParallelism(-1); - options.setEnableCrossPartitionQuery(true); - options.setMaxItemCount(100); + options.maxDegreeOfParallelism(-1); + options.enableCrossPartitionQuery(true); + options.maxItemCount(100); - logger.info("Truncating collection {} documents ...", cosmosContainer.getId()); + logger.info("Truncating collection {} documents ...", cosmosContainer.id()); cosmosContainer.queryItems("SELECT * FROM root", options) - .flatMap(page -> Flux.fromIterable(page.getResults())) + .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(doc -> { Object propertyValue = null; @@ -263,51 +230,51 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { } } - return cosmosContainer.getItem(doc.getId(), propertyValue).delete(); + return cosmosContainer.getItem(doc.id(), propertyValue).delete(); }).collectList().block(); logger.info("Truncating collection {} triggers ...", cosmosContainerId); cosmosContainer.queryTriggers("SELECT * FROM root", options) - .flatMap(page -> Flux.fromIterable(page.getResults())) + .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(trigger -> { CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = trigger.getObjectByPath(PathParser.getPathParts(paths.get(0))); -// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); +// requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getTrigger(trigger.getId()).delete(requestOptions); + return cosmosContainer.getTrigger(trigger.id()).delete(requestOptions); }).collectList().block(); logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); cosmosContainer.queryStoredProcedures("SELECT * FROM root", options) - .flatMap(page -> Flux.fromIterable(page.getResults())) + .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(storedProcedure -> { CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = storedProcedure.getObjectByPath(PathParser.getPathParts(paths.get(0))); -// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); +// requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getStoredProcedure(storedProcedure.getId()).delete(requestOptions); + return cosmosContainer.getStoredProcedure(storedProcedure.id()).delete(requestOptions); }).collectList().block(); logger.info("Truncating collection {} udfs ...", cosmosContainerId); cosmosContainer.queryUserDefinedFunctions("SELECT * FROM root", options) - .flatMap(page -> Flux.fromIterable(page.getResults())) + .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(udf -> { CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = udf.getObjectByPath(PathParser.getPathParts(paths.get(0))); -// requestOptions.setPartitionKey(new PartitionKey(propertyValue)); +// requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getUserDefinedFunction(udf.getId()).delete(requestOptions); + return cosmosContainer.getUserDefinedFunction(udf.id()).delete(requestOptions); }).collectList().block(); } finally { @@ -319,9 +286,9 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { switch (clientBuilder.getDesiredConsistencyLevel()) { - case Eventual: - case ConsistentPrefix: - logger.info(" additional wait in Eventual mode so the replica catch up"); + case EVENTUAL: + case CONSISTENT_PREFIX: + logger.info(" additional wait in EVENTUAL mode so the replica catch up"); // give times to replicas to catch up after a write try { TimeUnit.MILLISECONDS.sleep(WAIT_REPLICA_CATCH_UP_IN_MILLIS); @@ -329,9 +296,9 @@ protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clien logger.error("unexpected failure", e); } - case Session: - case BoundedStaleness: - case Strong: + case SESSION: + case BOUNDED_STALENESS: + case STRONG: default: break; } @@ -339,7 +306,7 @@ protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clien public static CosmosContainer createCollection(CosmosDatabase database, CosmosContainerSettings cosmosContainerSettings, CosmosContainerRequestOptions options) { - return database.createContainer(cosmosContainerSettings, options).block().getContainer(); + return database.createContainer(cosmosContainerSettings, options).block().container(); } private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { @@ -359,7 +326,7 @@ private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWith PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition(); ArrayList partitionKeyPaths = new ArrayList(); partitionKeyPaths.add("/" + PARTITION_KEY); - partitionKeyDefinition.setPaths(partitionKeyPaths); + partitionKeyDefinition.paths(partitionKeyPaths); CosmosContainerSettings cosmosContainerSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDefinition); @@ -369,12 +336,12 @@ private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWith //Simple ArrayList compositeIndexSimple = new ArrayList(); CompositePath compositePath1 = new CompositePath(); - compositePath1.setPath("/" + NUMBER_FIELD); - compositePath1.setOrder(CompositePathSortOrder.Ascending); + compositePath1.path("/" + NUMBER_FIELD); + compositePath1.order(CompositePathSortOrder.ASCENDING); CompositePath compositePath2 = new CompositePath(); - compositePath2.setPath("/" + STRING_FIELD); - compositePath2.setOrder(CompositePathSortOrder.Descending); + compositePath2.path("/" + STRING_FIELD); + compositePath2.order(CompositePathSortOrder.DESCENDING); compositeIndexSimple.add(compositePath1); compositeIndexSimple.add(compositePath2); @@ -382,20 +349,20 @@ private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWith //Max Columns ArrayList compositeIndexMaxColumns = new ArrayList(); CompositePath compositePath3 = new CompositePath(); - compositePath3.setPath("/" + NUMBER_FIELD); - compositePath3.setOrder(CompositePathSortOrder.Descending); + compositePath3.path("/" + NUMBER_FIELD); + compositePath3.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath4 = new CompositePath(); - compositePath4.setPath("/" + STRING_FIELD); - compositePath4.setOrder(CompositePathSortOrder.Ascending); + compositePath4.path("/" + STRING_FIELD); + compositePath4.order(CompositePathSortOrder.ASCENDING); CompositePath compositePath5 = new CompositePath(); - compositePath5.setPath("/" + NUMBER_FIELD_2); - compositePath5.setOrder(CompositePathSortOrder.Descending); + compositePath5.path("/" + NUMBER_FIELD_2); + compositePath5.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath6 = new CompositePath(); - compositePath6.setPath("/" + STRING_FIELD_2); - compositePath6.setOrder(CompositePathSortOrder.Ascending); + compositePath6.path("/" + STRING_FIELD_2); + compositePath6.order(CompositePathSortOrder.ASCENDING); compositeIndexMaxColumns.add(compositePath3); compositeIndexMaxColumns.add(compositePath4); @@ -405,20 +372,20 @@ private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWith //Primitive Values ArrayList compositeIndexPrimitiveValues = new ArrayList(); CompositePath compositePath7 = new CompositePath(); - compositePath7.setPath("/" + NUMBER_FIELD); - compositePath7.setOrder(CompositePathSortOrder.Descending); + compositePath7.path("/" + NUMBER_FIELD); + compositePath7.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath8 = new CompositePath(); - compositePath8.setPath("/" + STRING_FIELD); - compositePath8.setOrder(CompositePathSortOrder.Ascending); + compositePath8.path("/" + STRING_FIELD); + compositePath8.order(CompositePathSortOrder.ASCENDING); CompositePath compositePath9 = new CompositePath(); - compositePath9.setPath("/" + BOOL_FIELD); - compositePath9.setOrder(CompositePathSortOrder.Descending); + compositePath9.path("/" + BOOL_FIELD); + compositePath9.order(CompositePathSortOrder.DESCENDING); CompositePath compositePath10 = new CompositePath(); - compositePath10.setPath("/" + NULL_FIELD); - compositePath10.setOrder(CompositePathSortOrder.Ascending); + compositePath10.path("/" + NULL_FIELD); + compositePath10.order(CompositePathSortOrder.ASCENDING); compositeIndexPrimitiveValues.add(compositePath7); compositeIndexPrimitiveValues.add(compositePath8); @@ -428,16 +395,16 @@ private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWith //Long Strings ArrayList compositeIndexLongStrings = new ArrayList(); CompositePath compositePath11 = new CompositePath(); - compositePath11.setPath("/" + STRING_FIELD); + compositePath11.path("/" + STRING_FIELD); CompositePath compositePath12 = new CompositePath(); - compositePath12.setPath("/" + SHORT_STRING_FIELD); + compositePath12.path("/" + SHORT_STRING_FIELD); CompositePath compositePath13 = new CompositePath(); - compositePath13.setPath("/" + MEDIUM_STRING_FIELD); + compositePath13.path("/" + MEDIUM_STRING_FIELD); CompositePath compositePath14 = new CompositePath(); - compositePath14.setPath("/" + LONG_STRING_FIELD); + compositePath14.path("/" + LONG_STRING_FIELD); compositeIndexLongStrings.add(compositePath11); compositeIndexLongStrings.add(compositePath12); @@ -449,51 +416,51 @@ private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWith compositeIndexes.add(compositeIndexPrimitiveValues); compositeIndexes.add(compositeIndexLongStrings); - indexingPolicy.setCompositeIndexes(compositeIndexes); - cosmosContainerSettings.setIndexingPolicy(indexingPolicy); + indexingPolicy.compositeIndexes(compositeIndexes); + cosmosContainerSettings.indexingPolicy(indexingPolicy); return cosmosContainerSettings; } public static CosmosContainer createCollection(CosmosClient client, String dbId, CosmosContainerSettings collectionDefinition) { - return client.getDatabase(dbId).createContainer(collectionDefinition).block().getContainer(); + return client.getDatabase(dbId).createContainer(collectionDefinition).block().container(); } public static void deleteCollection(CosmosClient client, String dbId, String collectionId) { client.getDatabase(dbId).getContainer(collectionId).delete().block(); } - public static CosmosItem createDocument(CosmosContainer cosmosContainer, CosmosItemSettings item) { - return cosmosContainer.createItem(item).block().getCosmosItem(); + public static CosmosItem createDocument(CosmosContainer cosmosContainer, CosmosItemProperties item) { + return cosmosContainer.createItem(item).block().item(); } /* // TODO: respect concurrencyLevel; public Flux bulkInsert(CosmosContainer cosmosContainer, - List documentDefinitionList, + List documentDefinitionList, int concurrencyLevel) { - CosmosItemSettings first = documentDefinitionList.remove(0); + CosmosItemProperties first = documentDefinitionList.remove(0); Flux result = Flux.from(cosmosContainer.createItem(first)); - for (CosmosItemSettings docDef : documentDefinitionList) { + for (CosmosItemProperties docDef : documentDefinitionList) { result.concatWith(cosmosContainer.createItem(docDef)); } return result; } */ - public List bulkInsertBlocking(CosmosContainer cosmosContainer, - List documentDefinitionList) { + public List bulkInsertBlocking(CosmosContainer cosmosContainer, + List documentDefinitionList) { /* return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) .parallel() .runOn(Schedulers.parallel()) - .map(CosmosItemResponse::getCosmosItemSettings) + .map(CosmosItemResponse::properties) .sequential() .collectList() .block(); */ return Flux.merge(documentDefinitionList.stream() - .map(d -> cosmosContainer.createItem(d).map(response -> response.getCosmosItemSettings())) + .map(d -> cosmosContainer.createItem(d).map(response -> response.properties())) .collect(Collectors.toList())).collectList().block(); } @@ -502,16 +469,16 @@ public static ConsistencyLevel getAccountDefaultConsistencyLevel(CosmosClient cl } public static CosmosUser createUser(CosmosClient client, String databaseId, CosmosUserSettings userSettings) { - return client.getDatabase(databaseId).read().block().getDatabase().createUser(userSettings).block().getUser(); + return client.getDatabase(databaseId).read().block().database().createUser(userSettings).block().user(); } public static CosmosUser safeCreateUser(CosmosClient client, String databaseId, CosmosUserSettings user) { - deleteUserIfExists(client, databaseId, user.getId()); + deleteUserIfExists(client, databaseId, user.id()); return createUser(client, databaseId, user); } private static CosmosContainer safeCreateCollection(CosmosClient client, String databaseId, CosmosContainerSettings collection, CosmosContainerRequestOptions options) { - deleteCollectionIfExists(client, databaseId, collection.getId()); + deleteCollectionIfExists(client, databaseId, collection.id()); return createCollection(client.getDatabase(databaseId), collection, options); } @@ -519,7 +486,7 @@ static protected CosmosContainerSettings getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); @@ -530,33 +497,33 @@ static protected CosmosContainerSettings getCollectionDefinitionWithRangeRangeIn PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); - includedPath.setPath("/*"); + includedPath.path("/*"); Collection indexes = new ArrayList<>(); - Index stringIndex = Index.Range(DataType.String); + Index stringIndex = Index.Range(DataType.STRING); stringIndex.set("precision", -1); indexes.add(stringIndex); - Index numberIndex = Index.Range(DataType.Number); + Index numberIndex = Index.Range(DataType.NUMBER); numberIndex.set("precision", -1); indexes.add(numberIndex); - includedPath.setIndexes(indexes); + includedPath.indexes(indexes); includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); CosmosContainerSettings cosmosContainerSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); - cosmosContainerSettings.setIndexingPolicy(indexingPolicy); + cosmosContainerSettings.indexingPolicy(indexingPolicy); return cosmosContainerSettings; } public static void deleteCollectionIfExists(CosmosClient client, String databaseId, String collectionId) { - CosmosDatabase database = client.getDatabase(databaseId).read().block().getDatabase(); + CosmosDatabase database = client.getDatabase(databaseId).read().block().database(); List res = database.queryContainers(String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null) - .flatMap(page -> Flux.fromIterable(page.getResults())) + .flatMap(page -> Flux.fromIterable(page.results())) .collectList() .block(); @@ -575,11 +542,11 @@ public static void deleteCollection(CosmosContainer cosmosContainer) { public static void deleteDocumentIfExists(CosmosClient client, String databaseId, String collectionId, String docId) { FeedOptions options = new FeedOptions(); - options.setPartitionKey(new PartitionKey(docId)); - CosmosContainer cosmosContainer = client.getDatabase(databaseId).read().block().getDatabase().getContainer(collectionId).read().block().getContainer(); - List res = cosmosContainer + options.partitionKey(new PartitionKey(docId)); + CosmosContainer cosmosContainer = client.getDatabase(databaseId).read().block().database().getContainer(collectionId).read().block().container(); + List res = cosmosContainer .queryItems(String.format("SELECT * FROM root r where r.id = '%s'", docId), options) - .flatMap(page -> Flux.fromIterable(page.getResults())) + .flatMap(page -> Flux.fromIterable(page.results())) .collectList().block(); if (!res.isEmpty()) { @@ -590,10 +557,10 @@ public static void deleteDocumentIfExists(CosmosClient client, String databaseId public static void safeDeleteDocument(CosmosContainer cosmosContainer, String documentId, Object partitionKey) { if (cosmosContainer != null && documentId != null) { try { - cosmosContainer.getItem(documentId, partitionKey).read().block().getCosmosItem().delete().block(); + cosmosContainer.getItem(documentId, partitionKey).read().block().item().delete().block(); } catch (Exception e) { - DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e, DocumentClientException.class); - if (dce == null || dce.getStatusCode() != 404) { + CosmosClientException dce = Utils.as(e, CosmosClientException.class); + if (dce == null || dce.statusCode() != 404) { throw e; } } @@ -601,14 +568,14 @@ public static void safeDeleteDocument(CosmosContainer cosmosContainer, String do } public static void deleteDocument(CosmosContainer cosmosContainer, String documentId) { - cosmosContainer.getItem(documentId, PartitionKey.None).read().block().getCosmosItem().delete(); + cosmosContainer.getItem(documentId, PartitionKey.None).read().block().item().delete(); } public static void deleteUserIfExists(CosmosClient client, String databaseId, String userId) { - CosmosDatabase database = client.getDatabase(databaseId).read().block().getDatabase(); + CosmosDatabase database = client.getDatabase(databaseId).read().block().database(); List res = database .queryUsers(String.format("SELECT * FROM root r where r.id = '%s'", userId), null) - .flatMap(page -> Flux.fromIterable(page.getResults())) + .flatMap(page -> Flux.fromIterable(page.results())) .collectList().block(); if (!res.isEmpty()) { deleteUser(database, userId); @@ -616,29 +583,29 @@ public static void deleteUserIfExists(CosmosClient client, String databaseId, St } public static void deleteUser(CosmosDatabase database, String userId) { - database.getUser(userId).read().block().getUser().delete(null).block(); + database.getUser(userId).read().block().user().delete(null).block(); } static private CosmosDatabase safeCreateDatabase(CosmosClient client, CosmosDatabaseSettings databaseSettings) { - safeDeleteDatabase(client.getDatabase(databaseSettings.getId())); - return client.createDatabase(databaseSettings).block().getDatabase(); + safeDeleteDatabase(client.getDatabase(databaseSettings.id())); + return client.createDatabase(databaseSettings).block().database(); } static protected CosmosDatabase createDatabase(CosmosClient client, String databaseId) { CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings(databaseId); - return client.createDatabase(databaseSettings).block().getDatabase(); + return client.createDatabase(databaseSettings).block().database(); } static protected CosmosDatabase createDatabaseIfNotExists(CosmosClient client, String databaseId) { List res = client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null) - .flatMap(p -> Flux.fromIterable(p.getResults())) + .flatMap(p -> Flux.fromIterable(p.results())) .collectList() .block(); if (res.size() != 0) { - return client.getDatabase(databaseId).read().block().getDatabase(); + return client.getDatabase(databaseId).read().block().database(); } else { CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings(databaseId); - return client.createDatabase(databaseSettings).block().getDatabase(); + return client.createDatabase(databaseSettings).block().database(); } } @@ -654,12 +621,12 @@ static protected void safeDeleteDatabase(CosmosDatabase database) { static protected void safeDeleteAllCollections(CosmosDatabase database) { if (database != null) { List collections = database.listContainers() - .flatMap(p -> Flux.fromIterable(p.getResults())) + .flatMap(p -> Flux.fromIterable(p.results())) .collectList() .block(); for(CosmosContainerSettings collection: collections) { - database.getContainer(collection.getId()).delete().block(); + database.getContainer(collection.id()).delete().block(); } } } @@ -676,7 +643,7 @@ static protected void safeDeleteCollection(CosmosContainer collection) { static protected void safeDeleteCollection(CosmosDatabase database, String collectionId) { if (database != null && collectionId != null) { try { - database.getContainer(collectionId).read().block().getContainer().delete().block(); + database.getContainer(collectionId).read().block().container().delete().block(); } catch (Exception e) { } } @@ -848,15 +815,15 @@ public static void validateQueryFailure(Flux parsePreferredLocation(String preferredLocations) { @@ -882,8 +849,8 @@ static List parsePreferredLocation(String preferredLocations) { return objectMapper.readValue(preferredLocations, new TypeReference>() { }); } catch (Exception e) { - logger.error("Invalid configured test preferredLocations [{}].", preferredLocations); - throw new IllegalStateException("Invalid configured test preferredLocations " + preferredLocations); + logger.error("INVALID configured test preferredLocations [{}].", preferredLocations); + throw new IllegalStateException("INVALID configured test preferredLocations " + preferredLocations); } } @@ -896,8 +863,8 @@ static List parseProtocols(String protocols) { return objectMapper.readValue(protocols, new TypeReference>() { }); } catch (Exception e) { - logger.error("Invalid configured test protocols [{}].", protocols); - throw new IllegalStateException("Invalid configured test protocols " + protocols); + logger.error("INVALID configured test protocols [{}].", protocols); + throw new IllegalStateException("INVALID configured test protocols " + protocols); } } @@ -908,17 +875,17 @@ public static Object[][] simpleClientBuildersWithDirect() { @DataProvider public static Object[][] simpleClientBuildersWithDirectHttps() { - return simpleClientBuildersWithDirect(Protocol.Https); + return simpleClientBuildersWithDirect(Protocol.HTTPS); } private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) { logger.info("Max test consistency to use is [{}]", accountConsistency); - List testConsistencies = ImmutableList.of(ConsistencyLevel.Eventual); + List testConsistencies = ImmutableList.of(ConsistencyLevel.EVENTUAL); - boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.Session; + boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List cosmosConfigurations = new ArrayList<>(); - cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null)); + cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null)); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, @@ -928,7 +895,7 @@ private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) } cosmosConfigurations.forEach(c -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", - c.getConnectionPolicy().getConnectionMode(), + c.getConnectionPolicy().connectionMode(), c.getDesiredConsistencyLevel(), c.getConfigs().getProtocol() )); @@ -943,7 +910,7 @@ public static Object[][] clientBuildersWithDirect() { @DataProvider public static Object[][] clientBuildersWithDirectHttps() { - return clientBuildersWithDirectAllConsistencies(Protocol.Https); + return clientBuildersWithDirectAllConsistencies(Protocol.HTTPS); } @DataProvider @@ -957,7 +924,7 @@ static Protocol[] toArray(List protocols) { private static Object[][] clientBuildersWithDirectSession(Protocol... protocols) { return clientBuildersWithDirect(new ArrayList() {{ - add(ConsistencyLevel.Session); + add(ConsistencyLevel.SESSION); }}, protocols); } @@ -975,8 +942,8 @@ static List parseDesiredConsistencies(String consistencies) { return objectMapper.readValue(consistencies, new TypeReference>() { }); } catch (Exception e) { - logger.error("Invalid consistency test desiredConsistencies [{}].", consistencies); - throw new IllegalStateException("Invalid configured test desiredConsistencies " + consistencies); + logger.error("INVALID consistency test desiredConsistencies [{}].", consistencies); + throw new IllegalStateException("INVALID configured test desiredConsistencies " + consistencies); } } @@ -984,28 +951,28 @@ static List allEqualOrLowerConsistencies(ConsistencyLevel acco List testConsistencies = new ArrayList<>(); switch (accountConsistency) { - case Strong: - testConsistencies.add(ConsistencyLevel.Strong); - case BoundedStaleness: - testConsistencies.add(ConsistencyLevel.BoundedStaleness); - case Session: - testConsistencies.add(ConsistencyLevel.Session); - case ConsistentPrefix: - testConsistencies.add(ConsistencyLevel.ConsistentPrefix); - case Eventual: - testConsistencies.add(ConsistencyLevel.Eventual); + case STRONG: + testConsistencies.add(ConsistencyLevel.STRONG); + case BOUNDED_STALENESS: + testConsistencies.add(ConsistencyLevel.BOUNDED_STALENESS); + case SESSION: + testConsistencies.add(ConsistencyLevel.SESSION); + case CONSISTENT_PREFIX: + testConsistencies.add(ConsistencyLevel.CONSISTENT_PREFIX); + case EVENTUAL: + testConsistencies.add(ConsistencyLevel.EVENTUAL); break; default: - throw new IllegalStateException("Invalid configured test consistency " + accountConsistency); + throw new IllegalStateException("INVALID configured test consistency " + accountConsistency); } return testConsistencies; } private static Object[][] clientBuildersWithDirect(List testConsistencies, Protocol... protocols) { - boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.Session; + boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List cosmosConfigurations = new ArrayList<>(); - cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.Session, isMultiMasterEnabled, preferredLocations)); + cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations)); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, @@ -1015,7 +982,7 @@ private static Object[][] clientBuildersWithDirect(List testCo } cosmosConfigurations.forEach(c -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", - c.getConnectionPolicy().getConnectionMode(), + c.getConnectionPolicy().connectionMode(), c.getDesiredConsistencyLevel(), c.getConfigs().getProtocol() )); @@ -1025,21 +992,21 @@ private static Object[][] clientBuildersWithDirect(List testCo static protected CosmosClientBuilder createGatewayHouseKeepingDocumentClient() { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); RetryOptions options = new RetryOptions(); - options.setMaxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); - connectionPolicy.setRetryOptions(options); + options.maxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); + connectionPolicy.retryOptions(options); return CosmosClient.builder().endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .connectionPolicy(connectionPolicy) - .consistencyLevel(ConsistencyLevel.Session); + .consistencyLevel(ConsistencyLevel.SESSION); } static protected CosmosClientBuilder createGatewayRxDocumentClient(ConsistencyLevel consistencyLevel, boolean multiMasterEnabled, List preferredLocations) { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Gateway); - connectionPolicy.setUsingMultipleWriteLocations(multiMasterEnabled); - connectionPolicy.setPreferredLocations(preferredLocations); + connectionPolicy.connectionMode(ConnectionMode.GATEWAY); + connectionPolicy.usingMultipleWriteLocations(multiMasterEnabled); + connectionPolicy.preferredLocations(preferredLocations); return CosmosClient.builder().endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .connectionPolicy(connectionPolicy) @@ -1047,7 +1014,7 @@ static protected CosmosClientBuilder createGatewayRxDocumentClient(ConsistencyLe } static protected CosmosClientBuilder createGatewayRxDocumentClient() { - return createGatewayRxDocumentClient(ConsistencyLevel.Session, false, null); + return createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null); } static protected CosmosClientBuilder createDirectRxDocumentClient(ConsistencyLevel consistencyLevel, @@ -1055,14 +1022,14 @@ static protected CosmosClientBuilder createDirectRxDocumentClient(ConsistencyLev boolean multiMasterEnabled, List preferredLocations) { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(ConnectionMode.Direct); + connectionPolicy.connectionMode(ConnectionMode.DIRECT); if (preferredLocations != null) { - connectionPolicy.setPreferredLocations(preferredLocations); + connectionPolicy.preferredLocations(preferredLocations); } - if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.Session) { - connectionPolicy.setUsingMultipleWriteLocations(true); + if (multiMasterEnabled && consistencyLevel == ConsistencyLevel.SESSION) { + connectionPolicy.usingMultipleWriteLocations(true); } Configs configs = spy(new Configs()); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TokenResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java similarity index 81% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TokenResolverTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java index 5877d771244f4..76facad3c1254 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TokenResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java @@ -21,31 +21,32 @@ * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; - -import com.microsoft.azure.cosmosdb.BridgeInternal; -import com.microsoft.azure.cosmosdb.ChangeFeedOptions; -import com.microsoft.azure.cosmosdb.ConnectionMode; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.CosmosResourceType; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.DocumentCollection; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.Permission; -import com.microsoft.azure.cosmosdb.PermissionMode; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.Resource; -import com.microsoft.azure.cosmosdb.ResourceResponse; -import com.microsoft.azure.cosmosdb.StoredProcedure; -import com.microsoft.azure.cosmosdb.StoredProcedureResponse; -import com.microsoft.azure.cosmosdb.TokenResolver; -import com.microsoft.azure.cosmosdb.User; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; -import com.microsoft.azure.cosmosdb.rx.internal.TestSuiteBase; +package com.azure.data.cosmos.rx; + +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosResourceType; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.PermissionMode; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.StoredProcedure; +import com.azure.data.cosmos.StoredProcedureResponse; +import com.azure.data.cosmos.TokenResolver; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -57,6 +58,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.time.OffsetDateTime; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; @@ -96,8 +98,8 @@ public TokenResolverTest(AsyncDocumentClient.Builder clientBuilder) { @DataProvider(name = "connectionMode") public Object[][] connectionMode() { return new Object[][]{ - {ConnectionMode.Gateway}, - {ConnectionMode.Direct}, + {ConnectionMode.GATEWAY}, + {ConnectionMode.DIRECT}, }; } @@ -108,12 +110,12 @@ public void beforeClass() { client = clientBuilder.build(); - userWithReadPermission = createUser(client, createdDatabase.getId(), getUserDefinition()); - readPermission = client.createPermission(userWithReadPermission.getSelfLink(), getPermission(createdCollection, "ReadPermissionOnColl", PermissionMode.Read), null).toBlocking().single() + userWithReadPermission = createUser(client, createdDatabase.id(), getUserDefinition()); + readPermission = client.createPermission(userWithReadPermission.selfLink(), getPermission(createdCollection, "ReadPermissionOnColl", PermissionMode.READ), null).toBlocking().single() .getResource(); - userWithAllPermission = createUser(client, createdDatabase.getId(), getUserDefinition()); - allPermission = client.createPermission(userWithAllPermission.getSelfLink(), getPermission(createdCollection, "AllPermissionOnColl", PermissionMode.All), null).toBlocking().single() + userWithAllPermission = createUser(client, createdDatabase.id(), getUserDefinition()); + allPermission = client.createPermission(userWithAllPermission.selfLink(), getPermission(createdCollection, "AllPermissionOnColl", PermissionMode.ALL), null).toBlocking().single() .getResource(); } @@ -124,15 +126,15 @@ public void readDocumentWithReadPermission(ConnectionMode connectionMode) { .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).toBlocking().first(); AsyncDocumentClient asyncClientWithTokenResolver = null; try { - asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.Read); + asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.READ); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceResponse.getResource().get("mypk"))); HashMap properties = new HashMap(); properties.put("UserId", "readUser"); requestOptions.setProperties(properties); - Observable> readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().getSelfLink(), requestOptions); + Observable> readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().selfLink(), requestOptions); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(resourceResponse.getResource().getId()).build(); + .withId(resourceResponse.getResource().id()).build(); validateSuccess(readObservable, validator); } finally { safeClose(asyncClientWithTokenResolver); @@ -146,10 +148,10 @@ public void deleteDocumentWithReadPermission(ConnectionMode connectionMode) { .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).toBlocking().first(); AsyncDocumentClient asyncClientWithTokenResolver = null; try { - asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.Read); + asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.READ); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceResponse.getResource().get("mypk"))); - Observable> readObservable = asyncClientWithTokenResolver.deleteDocument(resourceResponse.getResource().getSelfLink(), requestOptions); + Observable> readObservable = asyncClientWithTokenResolver.deleteDocument(resourceResponse.getResource().selfLink(), requestOptions); FailureValidator validator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.FORBIDDEN).build(); validateFailure(readObservable, validator); } finally { @@ -161,8 +163,8 @@ public void deleteDocumentWithReadPermission(ConnectionMode connectionMode) { public void writeDocumentWithReadPermission(ConnectionMode connectionMode) { AsyncDocumentClient asyncClientWithTokenResolver = null; try { - asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.Read); - Observable> readObservable = asyncClientWithTokenResolver.createDocument(createdCollection.getSelfLink(), getDocumentDefinition(), null, true); + asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.READ); + Observable> readObservable = asyncClientWithTokenResolver.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, true); FailureValidator validator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.FORBIDDEN).build(); validateFailure(readObservable, validator); } finally { @@ -174,11 +176,11 @@ public void writeDocumentWithReadPermission(ConnectionMode connectionMode) { public void writeDocumentWithAllPermission(ConnectionMode connectionMode) { AsyncDocumentClient asyncClientWithTokenResolver = null; try { - asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.All); + asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.ALL); Document documentDefinition = getDocumentDefinition(); - Observable> readObservable = asyncClientWithTokenResolver.createDocument(createdCollection.getSelfLink(), documentDefinition, null, true); + Observable> readObservable = asyncClientWithTokenResolver.createDocument(createdCollection.selfLink(), documentDefinition, null, true); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(documentDefinition.getId()).build(); + .withId(documentDefinition.id()).build(); validateSuccess(readObservable, validator); } finally { safeClose(asyncClientWithTokenResolver); @@ -192,10 +194,10 @@ public void deleteDocumentWithAllPermission(ConnectionMode connectionMode) { .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).toBlocking().first(); AsyncDocumentClient asyncClientWithTokenResolver = null; try { - asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.All); + asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.ALL); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceResponse.getResource().get("mypk"))); - Observable> readObservable = asyncClientWithTokenResolver.deleteDocument(resourceResponse.getResource().getSelfLink(), requestOptions); + Observable> readObservable = asyncClientWithTokenResolver.deleteDocument(resourceResponse.getResource().selfLink(), requestOptions); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .nullResource().build(); validateSuccess(readObservable, validator); @@ -208,10 +210,10 @@ public void deleteDocumentWithAllPermission(ConnectionMode connectionMode) { public void readCollectionWithReadPermission(ConnectionMode connectionMode) { AsyncDocumentClient asyncClientWithTokenResolver = null; try { - asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.Read); - Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.getSelfLink(), null); + asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.READ); + Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), null); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(createdCollection.getId()).build(); + .withId(createdCollection.id()).build(); validateSuccess(readObservable, validator); } finally { safeClose(asyncClientWithTokenResolver); @@ -222,8 +224,8 @@ public void readCollectionWithReadPermission(ConnectionMode connectionMode) { public void deleteCollectionWithReadPermission(ConnectionMode connectionMode) { AsyncDocumentClient asyncClientWithTokenResolver = null; try { - asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.Read); - Observable> readObservable = asyncClientWithTokenResolver.deleteCollection(createdCollection.getSelfLink(), null); + asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.READ); + Observable> readObservable = asyncClientWithTokenResolver.deleteCollection(createdCollection.selfLink(), null); FailureValidator validator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.FORBIDDEN).build(); validateFailure(readObservable, validator); } finally { @@ -239,7 +241,7 @@ public void verifyingAuthTokenAPISequence(ConnectionMode connectionMode) { AsyncDocumentClient asyncClientWithTokenResolver = null; try { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(connectionMode); + connectionPolicy.connectionMode(connectionMode); //Unauthorized error with invalid token resolver, valid master key and valid permission feed, making it sure tokenResolver has higher priority than all. List permissionFeed = new ArrayList<>(); @@ -247,14 +249,14 @@ public void verifyingAuthTokenAPISequence(ConnectionMode connectionMode) { asyncClientWithTokenResolver = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .withTokenResolver(getTokenResolver(null)) //TokenResolver always generating invalid token. .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withPermissionFeed(permissionFeed) .build(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceResponse.getResource().get("mypk"))); - Observable> readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().getSelfLink(), requestOptions); + Observable> readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().selfLink(), requestOptions); FailureValidator failureValidator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.UNAUTHORIZED).build(); validateFailure(readObservable, failureValidator); @@ -262,14 +264,14 @@ public void verifyingAuthTokenAPISequence(ConnectionMode connectionMode) { asyncClientWithTokenResolver = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) - .withTokenResolver(getTokenResolver(PermissionMode.Read)) + .withConsistencyLevel(ConsistencyLevel.SESSION) + .withTokenResolver(getTokenResolver(PermissionMode.READ)) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withPermissionFeed(permissionFeed) .build(); - readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().getSelfLink(), requestOptions); + readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().selfLink(), requestOptions); ResourceResponseValidator sucessValidator = new ResourceResponseValidator.Builder() - .withId(resourceResponse.getResource().getId()).build(); + .withId(resourceResponse.getResource().id()).build(); validateSuccess(readObservable, sucessValidator); @@ -277,10 +279,10 @@ public void verifyingAuthTokenAPISequence(ConnectionMode connectionMode) { asyncClientWithTokenResolver = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .withPermissionFeed(permissionFeed) .build(); - readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().getSelfLink(), requestOptions); + readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().selfLink(), requestOptions); validateSuccess(readObservable, sucessValidator); @@ -288,10 +290,10 @@ public void verifyingAuthTokenAPISequence(ConnectionMode connectionMode) { asyncClientWithTokenResolver = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .build(); - readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().getSelfLink(), requestOptions); + readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().selfLink(), requestOptions); validateSuccess(readObservable, sucessValidator); } finally { @@ -303,7 +305,7 @@ public void verifyingAuthTokenAPISequence(ConnectionMode connectionMode) { public void createAndExecuteSprocWithWritePermission(ConnectionMode connectionMode) throws InterruptedException { AsyncDocumentClient asyncClientWithTokenResolver = null; try { - asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.All); + asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.ALL); String sprocId = "storedProcedure" + UUID.randomUUID().toString(); StoredProcedure sproc = new StoredProcedure( "{" + @@ -313,22 +315,22 @@ public void createAndExecuteSprocWithWritePermission(ConnectionMode connectionMo " var mytext = \"x\";" + " var myval = 1;" + " try {" + - " getContext().getResponse().setBody(\"Success!\");" + + " getContext().getResponse().body(\"Success!\");" + " }" + " catch(err) {" + - " getContext().getResponse().setBody(\"inline err: [\" + err.number + \"] \" + err);" + + " getContext().getResponse().body(\"inline err: [\" + err.number + \"] \" + err);" + " }" + " }'" + "}"); - Observable> createObservable = asyncClientWithTokenResolver.createStoredProcedure(createdCollection.getSelfLink(), sproc, null); + Observable> createObservable = asyncClientWithTokenResolver.createStoredProcedure(createdCollection.selfLink(), sproc, null); ResourceResponseValidator createSucessValidator = new ResourceResponseValidator.Builder() .withId(sprocId).build(); validateSuccess(createObservable, createSucessValidator); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey("")); - String sprocLink = "dbs/" + createdDatabase.getId() + "/colls/" + createdCollection.getId() + "/sprocs/" + sprocId; + String sprocLink = "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id() + "/sprocs/" + sprocId; StoredProcedureResponse result = asyncClientWithTokenResolver.executeStoredProcedure(sprocLink, options, null).toBlocking().single(); assertThat(result.getResponseAsString()).isEqualTo("\"Success!\""); } finally { @@ -343,21 +345,21 @@ public void readDocumentsWithAllPermission(ConnectionMode connectionMode) { String id2 = UUID.randomUUID().toString(); try { - asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.All); - Document document1 = asyncClientWithTokenResolver.createDocument(createdCollection.getSelfLink(), new Document("{'id': '" + id1 + "'}"), null, false) + asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.ALL); + Document document1 = asyncClientWithTokenResolver.createDocument(createdCollection.selfLink(), new Document("{'id': '" + id1 + "'}"), null, false) .toBlocking().single().getResource(); - Document document2 = asyncClientWithTokenResolver.createDocument(createdCollection.getSelfLink(), new Document("{'id': '" + id2 + "'}"), null, false) + Document document2 = asyncClientWithTokenResolver.createDocument(createdCollection.selfLink(), new Document("{'id': '" + id2 + "'}"), null, false) .toBlocking().single().getResource(); List expectedIds = new ArrayList(); - String rid1 = document1.getResourceId(); - String rid2 = document2.getResourceId(); + String rid1 = document1.resourceId(); + String rid2 = document2.resourceId(); expectedIds.add(rid1); expectedIds.add(rid2); String query = "SELECT * FROM r WHERE r._rid=\"" + rid1 + "\" or r._rid=\"" + rid2 + "\""; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - Observable> queryObservable = asyncClientWithTokenResolver.queryDocuments(createdCollection.getSelfLink(), query, options); + options.enableCrossPartitionQuery(true); + Observable> queryObservable = asyncClientWithTokenResolver.queryDocuments(createdCollection.selfLink(), query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .numberOfPages(1) .exactlyContainsInAnyOrder(expectedIds).build(); @@ -378,38 +380,38 @@ public void readChangeFeedWithAllPermission(ConnectionMode connectionMode) throw AsyncDocumentClient asyncClientWithTokenResolver = null; String id1 = UUID.randomUUID().toString(); String id2 = UUID.randomUUID().toString(); - String partitionKey = createdCollection.getPartitionKey().getPaths().get(0).substring(1); + String partitionKey = createdCollection.getPartitionKey().paths().get(0).substring(1); String partitionKeyValue = "pk"; Document document1 = new Document(); - document1.setId(id1); + document1.id(id1); document1.set(partitionKey, partitionKeyValue); Document document2 = new Document(); - document2.setId(id2); + document2.id(id2); document2.set(partitionKey, partitionKeyValue); try { - asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.All); - ZonedDateTime befTime = ZonedDateTime.now(); + asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.ALL); + OffsetDateTime befTime = OffsetDateTime.now(); Thread.sleep(1000); document1 = asyncClientWithTokenResolver - .createDocument(createdCollection.getSelfLink(), document1, null, false).toBlocking().single() + .createDocument(createdCollection.selfLink(), document1, null, false).toBlocking().single() .getResource(); document2 = asyncClientWithTokenResolver - .createDocument(createdCollection.getSelfLink(), document2, null, false).toBlocking().single() + .createDocument(createdCollection.selfLink(), document2, null, false).toBlocking().single() .getResource(); List expectedIds = new ArrayList(); - String rid1 = document1.getResourceId(); - String rid2 = document2.getResourceId(); + String rid1 = document1.resourceId(); + String rid2 = document2.resourceId(); expectedIds.add(rid1); expectedIds.add(rid2); ChangeFeedOptions options = new ChangeFeedOptions(); - options.setPartitionKey(new PartitionKey(partitionKeyValue)); - options.setStartDateTime(befTime); + options.partitionKey(new PartitionKey(partitionKeyValue)); + options.startDateTime(befTime); Thread.sleep(1000); Observable> queryObservable = asyncClientWithTokenResolver - .queryDocumentChangeFeed(createdCollection.getSelfLink(), options); + .queryDocumentChangeFeed(createdCollection.selfLink(), options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .exactlyContainsInAnyOrder(expectedIds).build(); validateQuerySuccess(queryObservable, validator, 10000); @@ -424,17 +426,17 @@ public void verifyRuntimeExceptionWhenUserModifiesProperties(ConnectionMode conn try { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(connectionMode); + connectionPolicy.connectionMode(connectionMode); asyncClientWithTokenResolver = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .withTokenResolver(getBadTokenResolver()) .build(); RequestOptions options = new RequestOptions(); options.setProperties(new HashMap()); - Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.getSelfLink(), options); + Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); FailureValidator validator = new FailureValidator.Builder().withRuntimeExceptionClass(UnsupportedOperationException.class).build(); validateFailure(readObservable, validator); } finally { @@ -451,27 +453,27 @@ public void verifyBlockListedUserThrows(ConnectionMode connectionMode) { AsyncDocumentClient asyncClientWithTokenResolver = null; try { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(connectionMode); + connectionPolicy.connectionMode(connectionMode); asyncClientWithTokenResolver = new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) - .withTokenResolver(getTokenResolverWithBlockList(PermissionMode.Read, field, blockListedUser, errorMessage)) + .withConsistencyLevel(ConsistencyLevel.SESSION) + .withTokenResolver(getTokenResolverWithBlockList(PermissionMode.READ, field, blockListedUser, errorMessage)) .build(); RequestOptions options = new RequestOptions(); HashMap properties = new HashMap(); properties.put(field, blockListedUser); options.setProperties(properties); - Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.getSelfLink(), options); + Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); FailureValidator validator = new FailureValidator.Builder().withRuntimeExceptionMessage(errorMessage).build(); validateFailure(readObservable, validator); properties.put(field, new UserClass("valid user", 1)); options.setProperties(properties); - readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.getSelfLink(), options); + readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); ResourceResponseValidator sucessValidator = new ResourceResponseValidator.Builder() - .withId(createdCollection.getId()).build(); + .withId(createdCollection.id()).build(); validateSuccess(readObservable, sucessValidator); } finally { safeClose(asyncClientWithTokenResolver); @@ -496,26 +498,26 @@ private Document getDocumentDefinition() { private AsyncDocumentClient buildClient(ConnectionMode connectionMode, PermissionMode permissionMode) { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.setConnectionMode(connectionMode); + connectionPolicy.connectionMode(connectionMode); return new AsyncDocumentClient.Builder() .withServiceEndpoint(TestConfigurations.HOST) .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.Session) + .withConsistencyLevel(ConsistencyLevel.SESSION) .withTokenResolver(getTokenResolver(permissionMode)) .build(); } private static User getUserDefinition() { User user = new User(); - user.setId(UUID.randomUUID().toString()); + user.id(UUID.randomUUID().toString()); return user; } private Permission getPermission(Resource resource, String permissionId, PermissionMode permissionMode) { Permission permission = new Permission(); - permission.setId(permissionId); + permission.id(permissionId); permission.setPermissionMode(permissionMode); - permission.setResourceLink(resource.getSelfLink()); + permission.setResourceLink(resource.selfLink()); return permission; } @@ -523,7 +525,7 @@ private TokenResolver getTokenResolver(PermissionMode permissionMode) { return (String requestVerb, String resourceIdOrFullName, CosmosResourceType resourceType, Map properties) -> { if (permissionMode == null) { return "invalid"; - } else if (permissionMode.equals(PermissionMode.Read)) { + } else if (permissionMode.equals(PermissionMode.READ)) { return readPermission.getToken(); } else { return allPermission.getToken(); @@ -555,7 +557,7 @@ private TokenResolver getTokenResolverWithBlockList(PermissionMode permissionMod } else if (currentUser != null && !currentUser.userName.equals(blockListedUser.userName) && currentUser.userId != blockListedUser.userId) { - if (permissionMode.equals(PermissionMode.Read)) { + if (permissionMode.equals(PermissionMode.READ)) { return readPermission.getToken(); } else { return allPermission.getToken(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java similarity index 68% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java index de9569b2afe31..507f422ac706b 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TopQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -30,30 +30,30 @@ import java.util.Set; import java.util.concurrent.TimeUnit; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmosdb.RetryAnalyzer; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.RetryAnalyzer; +import com.azure.data.cosmos.directconnectivity.Protocol; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.rx.internal.Utils.ValueHolder; -import com.microsoft.azure.cosmosdb.rx.internal.query.TakeContinuationToken; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.Utils.ValueHolder; +import com.azure.data.cosmos.internal.query.TakeContinuationToken; import io.reactivex.subscribers.TestSubscriber; import reactor.core.publisher.Flux; public class TopQueryTests extends TestSuiteBase { private CosmosContainer createdCollection; - private ArrayList docs = new ArrayList(); + private ArrayList docs = new ArrayList(); private String partitionKey = "mypk"; private int firstPk = 0; @@ -71,26 +71,26 @@ public TopQueryTests(CosmosClientBuilder clientBuilder) { public void queryDocumentsWithTop(boolean qmEnabled) throws Exception { FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); - options.setMaxItemCount(9); - options.setMaxDegreeOfParallelism(2); - options.setPopulateQueryMetrics(qmEnabled); + options.enableCrossPartitionQuery(true); + options.maxItemCount(9); + options.maxDegreeOfParallelism(2); + options.populateQueryMetrics(qmEnabled); int expectedTotalSize = 20; int expectedNumberOfPages = 3; int[] expectedPageLengths = new int[] { 9, 9, 2 }; for (int i = 0; i < 2; i++) { - Flux> queryObservable1 = createdCollection.queryItems("SELECT TOP 0 value AVG(c.field) from c", options); + Flux> queryObservable1 = createdCollection.queryItems("SELECT TOP 0 value AVG(c.field) from c", options); - FeedResponseListValidator validator1 = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator1 = new FeedResponseListValidator.Builder() .totalSize(0).build(); try { validateQuerySuccess(queryObservable1, validator1, TIMEOUT); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); @@ -98,24 +98,24 @@ public void queryDocumentsWithTop(boolean qmEnabled) throws Exception { throw error; } - Flux> queryObservable2 = createdCollection.queryItems("SELECT TOP 1 value AVG(c.field) from c", options); + Flux> queryObservable2 = createdCollection.queryItems("SELECT TOP 1 value AVG(c.field) from c", options); - FeedResponseListValidator validator2 = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator2 = new FeedResponseListValidator.Builder() .totalSize(1).build(); validateQuerySuccess(queryObservable2, validator2, TIMEOUT); - Flux> queryObservable3 = createdCollection.queryItems("SELECT TOP 20 * from c", options); + Flux> queryObservable3 = createdCollection.queryItems("SELECT TOP 20 * from c", options); - FeedResponseListValidator validator3 = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator3 = new FeedResponseListValidator.Builder() .totalSize(expectedTotalSize).numberOfPages(expectedNumberOfPages).pageLengths(expectedPageLengths) .hasValidQueryMetrics(qmEnabled).build(); validateQuerySuccess(queryObservable3, validator3, TIMEOUT); if (i == 0) { - options.setPartitionKey(new PartitionKey(firstPk)); - options.setEnableCrossPartitionQuery(false); + options.partitionKey(new PartitionKey(firstPk)); + options.enableCrossPartitionQuery(false); expectedTotalSize = 10; expectedNumberOfPages = 2; @@ -157,39 +157,39 @@ public void queryDocumentsWithTopContinuationTokens() throws Exception { private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, int topCount) { for (int pageSize : pageSizes) { - List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); + List receivedDocuments = this.queryWithContinuationTokens(query, pageSize); Set actualIds = new HashSet(); - for (CosmosItemSettings document : receivedDocuments) { - actualIds.add(document.getResourceId()); + for (CosmosItemProperties document : receivedDocuments) { + actualIds.add(document.resourceId()); } assertThat(actualIds.size()).describedAs("total number of results").isEqualTo(topCount); } } - private List queryWithContinuationTokens(String query, int pageSize) { + private List queryWithContinuationTokens(String query, int pageSize) { String requestContinuation = null; List continuationTokens = new ArrayList(); - List receivedDocuments = new ArrayList(); + List receivedDocuments = new ArrayList(); do { FeedOptions options = new FeedOptions(); - options.setMaxItemCount(pageSize); - options.setEnableCrossPartitionQuery(true); - options.setMaxDegreeOfParallelism(2); - options.setRequestContinuation(requestContinuation); - Flux> queryObservable = createdCollection.queryItems(query, options); + options.maxItemCount(pageSize); + options.enableCrossPartitionQuery(true); + options.maxDegreeOfParallelism(2); + options.requestContinuation(requestContinuation); + Flux> queryObservable = createdCollection.queryItems(query, options); //Observable> firstPageObservable = queryObservable.first(); - TestSubscriber> testSubscriber = new TestSubscriber<>(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); queryObservable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); - FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); - requestContinuation = firstPage.getResponseContinuation(); - receivedDocuments.addAll(firstPage.getResults()); + FeedResponse firstPage = (FeedResponse) testSubscriber.getEvents().get(0).get(0); + requestContinuation = firstPage.continuationToken(); + receivedDocuments.addAll(firstPage.results()); continuationTokens.add(requestContinuation); } while (requestContinuation != null); @@ -207,16 +207,16 @@ public void bulkInsert(CosmosClient client) { public void generateTestData() { for (int i = 0; i < 10; i++) { - CosmosItemSettings d = new CosmosItemSettings(); - d.setId(Integer.toString(i)); + CosmosItemProperties d = new CosmosItemProperties(); + d.id(Integer.toString(i)); d.set(field, i); d.set(partitionKey, firstPk); docs.add(d); } for (int i = 10; i < 20; i++) { - CosmosItemSettings d = new CosmosItemSettings(); - d.setId(Integer.toString(i)); + CosmosItemProperties d = new CosmosItemProperties(); + d.id(Integer.toString(i)); d.set(field, i); d.set(partitionKey, secondPk); docs.add(d); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java similarity index 70% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java index f9d4008fe70b9..1e5674b7bb5ab 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java @@ -20,27 +20,27 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.UUID; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosRequestOptions; -import com.microsoft.azure.cosmos.CosmosResponse; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmos.CosmosTrigger; -import com.microsoft.azure.cosmos.CosmosTriggerResponse; -import com.microsoft.azure.cosmos.CosmosTriggerSettings; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.TriggerOperation; -import com.microsoft.azure.cosmosdb.TriggerType; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosRequestOptions; +import com.azure.data.cosmos.CosmosResponse; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosTrigger; +import com.azure.data.cosmos.CosmosTriggerResponse; +import com.azure.data.cosmos.CosmosTriggerSettings; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.TriggerOperation; +import com.azure.data.cosmos.TriggerType; import reactor.core.publisher.Mono; @@ -59,18 +59,18 @@ public void createTrigger() throws Exception { // create a trigger CosmosTriggerSettings trigger = new CosmosTriggerSettings(); - trigger.setId(UUID.randomUUID().toString()); - trigger.setBody("function() {var x = 10;}"); - trigger.setTriggerOperation(TriggerOperation.Create); - trigger.setTriggerType(TriggerType.Pre); + trigger.id(UUID.randomUUID().toString()); + trigger.body("function() {var x = 10;}"); + trigger.triggerOperation(TriggerOperation.CREATE); + trigger.triggerType(TriggerType.PRE); Mono createObservable = createdCollection.createTrigger(trigger, new CosmosRequestOptions()); // validate trigger creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(trigger.getId()) + .withId(trigger.id()) .withTriggerBody("function() {var x = 10;}") - .withTriggerInternals(TriggerType.Pre, TriggerOperation.Create) + .withTriggerInternals(TriggerType.PRE, TriggerOperation.CREATE) .notNullEtag() .build(); validateSuccess(createObservable, validator); @@ -80,11 +80,11 @@ public void createTrigger() throws Exception { public void readTrigger() throws Exception { // create a trigger CosmosTriggerSettings trigger = new CosmosTriggerSettings(); - trigger.setId(UUID.randomUUID().toString()); - trigger.setBody("function() {var x = 10;}"); - trigger.setTriggerOperation(TriggerOperation.Create); - trigger.setTriggerType(TriggerType.Pre); - CosmosTrigger readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().getCosmosTrigger(); + trigger.id(UUID.randomUUID().toString()); + trigger.body("function() {var x = 10;}"); + trigger.triggerOperation(TriggerOperation.CREATE); + trigger.triggerType(TriggerType.PRE); + CosmosTrigger readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().trigger(); // read trigger waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -92,9 +92,9 @@ public void readTrigger() throws Exception { // validate read trigger CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(trigger.getId()) + .withId(trigger.id()) .withTriggerBody("function() {var x = 10;}") - .withTriggerInternals(TriggerType.Pre, TriggerOperation.Create) + .withTriggerInternals(TriggerType.PRE, TriggerOperation.CREATE) .notNullEtag() .build(); validateSuccess(readObservable, validator); @@ -104,11 +104,11 @@ public void readTrigger() throws Exception { public void deleteTrigger() throws Exception { // create a trigger CosmosTriggerSettings trigger = new CosmosTriggerSettings(); - trigger.setId(UUID.randomUUID().toString()); - trigger.setBody("function() {var x = 10;}"); - trigger.setTriggerOperation(TriggerOperation.Create); - trigger.setTriggerType(TriggerType.Pre); - CosmosTrigger readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().getCosmosTrigger(); + trigger.id(UUID.randomUUID().toString()); + trigger.body("function() {var x = 10;}"); + trigger.triggerOperation(TriggerOperation.CREATE); + trigger.triggerType(TriggerType.PRE); + CosmosTrigger readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().trigger(); // delete trigger Mono deleteObservable = readBackTrigger.delete(new CosmosRequestOptions()); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java similarity index 78% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java index 9bb191ec70133..4b2f9104bb382 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -29,23 +29,12 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.*; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosRequestOptions; -import com.microsoft.azure.cosmos.CosmosTriggerSettings; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; -import com.microsoft.azure.cosmosdb.Trigger; -import com.microsoft.azure.cosmosdb.TriggerOperation; -import com.microsoft.azure.cosmosdb.TriggerType; - import reactor.core.publisher.Flux; public class TriggerQueryTest extends TestSuiteBase { @@ -63,21 +52,24 @@ public TriggerQueryTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryWithFilter() throws Exception { - String filterId = createdTriggers.get(0).getId(); + String filterId = createdTriggers.get(0).id(); String query = String.format("SELECT * from c where c.id = '%s'", filterId); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(5); + options.maxItemCount(5); Flux> queryObservable = createdCollection.queryTriggers(query, options); - List expectedDocs = createdTriggers.stream().filter(sp -> filterId.equals(sp.getId()) ).collect(Collectors.toList()); + List expectedDocs = createdTriggers + .stream() + .filter(sp -> filterId.equals(sp.id()) ) + .collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) - .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -91,7 +83,7 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); Flux> queryObservable = createdCollection.queryTriggers(query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() @@ -108,19 +100,19 @@ public void queryAll() throws Exception { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(3); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(3); + options.enableCrossPartitionQuery(true); Flux> queryObservable = createdCollection.queryTriggers(query, options); List expectedDocs = createdTriggers; - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() - .map(d -> d.getResourceId()) + .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() @@ -133,11 +125,11 @@ public void queryAll() throws Exception { public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); Flux> queryObservable = createdCollection.queryTriggers(query, options); FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) + .instanceOf(CosmosClientException.class) .statusCode(400) .notNullActivityId() .build(); @@ -146,7 +138,7 @@ public void invalidQuerySytax() throws Exception { public CosmosTriggerSettings createTrigger(CosmosContainer cosmosContainer) { CosmosTriggerSettings storedProcedure = getTriggerDef(); - return cosmosContainer.createTrigger(storedProcedure, new CosmosRequestOptions()).block().getCosmosTriggerSettings(); + return cosmosContainer.createTrigger(storedProcedure, new CosmosRequestOptions()).block().settings(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) @@ -169,10 +161,10 @@ public void afterClass() { private static CosmosTriggerSettings getTriggerDef() { CosmosTriggerSettings trigger = new CosmosTriggerSettings(); - trigger.setId(UUID.randomUUID().toString()); - trigger.setBody("function() {var x = 10;}"); - trigger.setTriggerOperation(TriggerOperation.Create); - trigger.setTriggerType(TriggerType.Pre); + trigger.id(UUID.randomUUID().toString()); + trigger.body("function() {var x = 10;}"); + trigger.triggerOperation(TriggerOperation.CREATE); + trigger.triggerType(TriggerType.PRE); return trigger; } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java similarity index 71% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerUpsertReplaceTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java index fe2796bcef075..d764dbc6c6aa0 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/TriggerUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java @@ -20,25 +20,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.UUID; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosRequestOptions; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmos.CosmosTriggerResponse; -import com.microsoft.azure.cosmos.CosmosTriggerSettings; -import com.microsoft.azure.cosmosdb.RequestOptions; -import com.microsoft.azure.cosmosdb.TriggerOperation; -import com.microsoft.azure.cosmosdb.TriggerType; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosRequestOptions; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosTriggerResponse; +import com.azure.data.cosmos.CosmosTriggerSettings; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.TriggerOperation; +import com.azure.data.cosmos.TriggerType; import reactor.core.publisher.Mono; @@ -58,35 +58,35 @@ public void replaceTrigger() throws Exception { // create a trigger CosmosTriggerSettings trigger = new CosmosTriggerSettings(); - trigger.setId(UUID.randomUUID().toString()); - trigger.setBody("function() {var x = 10;}"); - trigger.setTriggerOperation(TriggerOperation.Create); - trigger.setTriggerType(TriggerType.Pre); - CosmosTriggerSettings readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().getCosmosTriggerSettings(); + trigger.id(UUID.randomUUID().toString()); + trigger.body("function() {var x = 10;}"); + trigger.triggerOperation(TriggerOperation.CREATE); + trigger.triggerType(TriggerType.PRE); + CosmosTriggerSettings readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().settings(); // read trigger to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder); - Mono readObservable = createdCollection.getTrigger(readBackTrigger.getId()).read(new RequestOptions()); + Mono readObservable = createdCollection.getTrigger(readBackTrigger.id()).read(new RequestOptions()); // validate trigger creation CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() - .withId(readBackTrigger.getId()) + .withId(readBackTrigger.id()) .withTriggerBody("function() {var x = 10;}") - .withTriggerInternals(TriggerType.Pre, TriggerOperation.Create) + .withTriggerInternals(TriggerType.PRE, TriggerOperation.CREATE) .notNullEtag() .build(); validateSuccess(readObservable, validatorForRead); //update trigger - readBackTrigger.setBody("function() {var x = 11;}"); + readBackTrigger.body("function() {var x = 11;}"); - Mono updateObservable = createdCollection.getTrigger(readBackTrigger.getId()).replace(readBackTrigger, new RequestOptions()); + Mono updateObservable = createdCollection.getTrigger(readBackTrigger.id()).replace(readBackTrigger, new RequestOptions()); // validate trigger replace CosmosResponseValidator validatorForUpdate = new CosmosResponseValidator.Builder() - .withId(readBackTrigger.getId()) + .withId(readBackTrigger.id()) .withTriggerBody("function() {var x = 11;}") - .withTriggerInternals(TriggerType.Pre, TriggerOperation.Create) + .withTriggerInternals(TriggerType.PRE, TriggerOperation.CREATE) .notNullEtag() .build(); validateSuccess(updateObservable, validatorForUpdate); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UniqueIndexTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java similarity index 56% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UniqueIndexTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java index e95adb5735ce8..368045bb2bf25 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UniqueIndexTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; @@ -30,38 +30,20 @@ import java.util.UUID; import java.util.stream.Collectors; +import com.azure.data.cosmos.*; +import com.azure.data.cosmos.internal.Utils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.azure.data.cosmos.*; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosContainerRequestOptions; -import com.microsoft.azure.cosmos.CosmosContainerSettings; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import com.microsoft.azure.cosmos.CosmosItem; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemSettings; -import com.microsoft.azure.cosmosdb.ConnectionPolicy; -import com.microsoft.azure.cosmosdb.ConsistencyLevel; -import com.microsoft.azure.cosmosdb.DataType; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.ExcludedPath; -import com.microsoft.azure.cosmosdb.HashIndex; -import com.microsoft.azure.cosmosdb.IncludedPath; -import com.microsoft.azure.cosmosdb.IndexingMode; -import com.microsoft.azure.cosmosdb.IndexingPolicy; -import com.microsoft.azure.cosmosdb.PartitionKey; -import com.microsoft.azure.cosmosdb.PartitionKeyDefinition; -import com.microsoft.azure.cosmosdb.UniqueKey; -import com.microsoft.azure.cosmosdb.UniqueKeyPolicy; -import com.microsoft.azure.cosmosdb.internal.HttpConstants; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.HttpConstants; public class UniqueIndexTest extends TestSuiteBase { protected static final int TIMEOUT = 30000; @@ -79,30 +61,30 @@ public void insertWithUniqueIndex() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); - uniqueKey.setPaths(ImmutableList.of("/name", "/description")); - uniqueKeyPolicy.setUniqueKeys(Collections.singleton(uniqueKey)); - collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); + uniqueKey.paths(ImmutableList.of("/name", "/description")); + uniqueKeyPolicy.uniqueKeys(Collections.singleton(uniqueKey)); + collectionDefinition.uniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); - indexingPolicy.setIndexingMode(IndexingMode.Consistent); + indexingPolicy.indexingMode(IndexingMode.CONSISTENT); ExcludedPath excludedPath = new ExcludedPath(); - excludedPath.setPath("/*"); - indexingPolicy.setExcludedPaths(Collections.singletonList(excludedPath)); + excludedPath.path("/*"); + indexingPolicy.excludedPaths(Collections.singletonList(excludedPath)); IncludedPath includedPath1 = new IncludedPath(); - includedPath1.setPath("/name/?"); - includedPath1.setIndexes(Collections.singletonList(new HashIndex(DataType.String, 7))); + includedPath1.path("/name/?"); + includedPath1.indexes(Collections.singletonList(new HashIndex(DataType.STRING, 7))); IncludedPath includedPath2 = new IncludedPath(); - includedPath2.setPath("/description/?"); - includedPath2.setIndexes(Collections.singletonList(new HashIndex(DataType.String, 7))); + includedPath2.path("/description/?"); + includedPath2.indexes(Collections.singletonList(new HashIndex(DataType.STRING, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); - collectionDefinition.setIndexingPolicy(indexingPolicy); + collectionDefinition.indexingPolicy(indexingPolicy); ObjectMapper om = new ObjectMapper(); @@ -110,20 +92,20 @@ public void insertWithUniqueIndex() throws Exception { JsonNode doc2 = om.readValue("{\"name\":\"Alexander Pushkin\",\"description\":\"playwright\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); JsonNode doc3 = om.readValue("{\"name\":\"حافظ شیرازی\",\"description\":\"poet\",\"id\": \"" + UUID.randomUUID().toString() + "\"}", JsonNode.class); - collection = database.createContainer(collectionDefinition).block().getContainer(); + collection = database.createContainer(collectionDefinition).block().container(); - CosmosItem item = collection.createItem(doc1).block().getCosmosItem(); + CosmosItem item = collection.createItem(doc1).block().item(); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); - options.setPartitionKey(PartitionKey.None); - CosmosItemSettings itemSettings = item.read(options).block().getCosmosItemSettings(); - assertThat(itemSettings.getId()).isEqualTo(doc1.get("id").textValue()); + options.partitionKey(PartitionKey.None); + CosmosItemProperties itemSettings = item.read(options).block().properties(); + assertThat(itemSettings.id()).isEqualTo(doc1.get("id").textValue()); try { collection.createItem(doc1).block(); fail("Did not throw due to unique constraint (create)"); } catch (RuntimeException e) { - assertThat(getDocumentClientException(e).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); + assertThat(getDocumentClientException(e).statusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } collection.createItem(doc2).block(); @@ -135,16 +117,16 @@ public void replaceAndDeleteWithUniqueIndex() throws Exception { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); - uniqueKey.setPaths(ImmutableList.of("/name", "/description")); - uniqueKeyPolicy.setUniqueKeys(Collections.singleton(uniqueKey)); - collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); + uniqueKey.paths(ImmutableList.of("/name", "/description")); + uniqueKeyPolicy.uniqueKeys(Collections.singleton(uniqueKey)); + collectionDefinition.uniqueKeyPolicy(uniqueKeyPolicy); - collection = database.createContainer(collectionDefinition).block().getContainer(); + collection = database.createContainer(collectionDefinition).block().container(); ObjectMapper om = new ObjectMapper(); @@ -152,26 +134,26 @@ public void replaceAndDeleteWithUniqueIndex() throws Exception { ObjectNode doc3 = om.readValue("{\"name\":\"Rabindranath Tagore\",\"description\":\"poet\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); ObjectNode doc2 = om.readValue("{\"name\":\"عمر خیّام\",\"description\":\"mathematician\",\"id\": \""+ UUID.randomUUID().toString() +"\"}", ObjectNode.class); - CosmosItemSettings doc1Inserted = collection.createItem(doc1, new CosmosItemRequestOptions()).block().getCosmosItemSettings(); + CosmosItemProperties doc1Inserted = collection.createItem(doc1, new CosmosItemRequestOptions()).block().properties(); - collection.getItem(doc1.get("id").asText(), PartitionKey.None).replace(doc1Inserted, new CosmosItemRequestOptions()).block().getCosmosItemSettings(); // Replace with same values -- OK. + collection.getItem(doc1.get("id").asText(), PartitionKey.None).replace(doc1Inserted, new CosmosItemRequestOptions()).block().properties(); // REPLACE with same values -- OK. - CosmosItemSettings doc2Inserted = collection.createItem(doc2, new CosmosItemRequestOptions()).block().getCosmosItemSettings(); - CosmosItemSettings doc2Replacement = new CosmosItemSettings(doc1Inserted.toJson()); - doc2Replacement.setId( doc2Inserted.getId()); + CosmosItemProperties doc2Inserted = collection.createItem(doc2, new CosmosItemRequestOptions()).block().properties(); + CosmosItemProperties doc2Replacement = new CosmosItemProperties(doc1Inserted.toJson()); + doc2Replacement.id( doc2Inserted.id()); try { - collection.getItem(doc2Inserted.getId(), PartitionKey.None).replace(doc2Replacement, new CosmosItemRequestOptions()).block(); // Replace doc2 with values from doc1 -- Conflict. + collection.getItem(doc2Inserted.id(), PartitionKey.None).replace(doc2Replacement, new CosmosItemRequestOptions()).block(); // REPLACE doc2 with values from doc1 -- Conflict. fail("Did not throw due to unique constraint"); } catch (RuntimeException ex) { - assertThat(getDocumentClientException(ex).getStatusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); + assertThat(getDocumentClientException(ex).statusCode()).isEqualTo(HttpConstants.StatusCodes.CONFLICT); } - doc3.put("id", doc1Inserted.getId()); - collection.getItem(doc1Inserted.getId(), PartitionKey.None).replace(doc3).block(); // Replace with values from doc3 -- OK. + doc3.put("id", doc1Inserted.id()); + collection.getItem(doc1Inserted.id(), PartitionKey.None).replace(doc3).block(); // REPLACE with values from doc3 -- OK. - collection.getItem(doc1Inserted.getId(), PartitionKey.None).delete().block(); + collection.getItem(doc1Inserted.id(), PartitionKey.None).delete().block(); collection.createItem(doc1, new CosmosItemRequestOptions()).block(); } @@ -180,48 +162,48 @@ public void uniqueKeySerializationDeserialization() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); - partitionKeyDef.setPaths(paths); + partitionKeyDef.paths(paths); CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); - uniqueKey.setPaths(ImmutableList.of("/name", "/description")); - uniqueKeyPolicy.setUniqueKeys(Collections.singleton(uniqueKey)); - collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); + uniqueKey.paths(ImmutableList.of("/name", "/description")); + uniqueKeyPolicy.uniqueKeys(Collections.singleton(uniqueKey)); + collectionDefinition.uniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); - indexingPolicy.setIndexingMode(IndexingMode.Consistent); + indexingPolicy.indexingMode(IndexingMode.CONSISTENT); ExcludedPath excludedPath = new ExcludedPath(); - excludedPath.setPath("/*"); - indexingPolicy.setExcludedPaths(Collections.singletonList(excludedPath)); + excludedPath.path("/*"); + indexingPolicy.excludedPaths(Collections.singletonList(excludedPath)); IncludedPath includedPath1 = new IncludedPath(); - includedPath1.setPath("/name/?"); - includedPath1.setIndexes(Collections.singletonList(new HashIndex(DataType.String, 7))); + includedPath1.path("/name/?"); + includedPath1.indexes(Collections.singletonList(new HashIndex(DataType.STRING, 7))); IncludedPath includedPath2 = new IncludedPath(); - includedPath2.setPath("/description/?"); - includedPath2.setIndexes(Collections.singletonList(new HashIndex(DataType.String, 7))); + includedPath2.path("/description/?"); + includedPath2.indexes(Collections.singletonList(new HashIndex(DataType.STRING, 7))); indexingPolicy.setIncludedPaths(ImmutableList.of(includedPath1, includedPath2)); - collectionDefinition.setIndexingPolicy(indexingPolicy); + collectionDefinition.indexingPolicy(indexingPolicy); - CosmosContainer createdCollection = database.createContainer(collectionDefinition).block().getContainer(); + CosmosContainer createdCollection = database.createContainer(collectionDefinition).block().container(); - CosmosContainerSettings collection = createdCollection.read().block().getCosmosContainerSettings(); + CosmosContainerSettings collection = createdCollection.read().block().settings(); - assertThat(collection.getUniqueKeyPolicy()).isNotNull(); - assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()).isNotNull(); - assertThat(collection.getUniqueKeyPolicy().getUniqueKeys()) - .hasSameSizeAs(collectionDefinition.getUniqueKeyPolicy().getUniqueKeys()); - assertThat(collection.getUniqueKeyPolicy().getUniqueKeys() - .stream().map(ui -> ui.getPaths()).collect(Collectors.toList())) + assertThat(collection.uniqueKeyPolicy()).isNotNull(); + assertThat(collection.uniqueKeyPolicy().uniqueKeys()).isNotNull(); + assertThat(collection.uniqueKeyPolicy().uniqueKeys()) + .hasSameSizeAs(collectionDefinition.uniqueKeyPolicy().uniqueKeys()); + assertThat(collection.uniqueKeyPolicy().uniqueKeys() + .stream().map(ui -> ui.paths()).collect(Collectors.toList())) .containsExactlyElementsOf( ImmutableList.of(ImmutableList.of("/name", "/description"))); } - private DocumentClientException getDocumentClientException(RuntimeException e) { - DocumentClientException dce = com.microsoft.azure.cosmosdb.rx.internal.Utils.as(e.getCause(), DocumentClientException.class); + private CosmosClientException getDocumentClientException(RuntimeException e) { + CosmosClientException dce = Utils.as(e.getCause(), CosmosClientException.class); assertThat(dce).isNotNull(); return dce; } @@ -232,8 +214,8 @@ public void beforeClass() { client = CosmosClient.builder() .endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) - .connectionPolicy(ConnectionPolicy.GetDefault()) - .consistencyLevel(ConsistencyLevel.Session).build(); + .connectionPolicy(ConnectionPolicy.defaultPolicy()) + .consistencyLevel(ConsistencyLevel.SESSION).build(); database = createDatabase(client, databaseId); } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java similarity index 83% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java index 2159a78724cea..58bd41650a280 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java @@ -20,24 +20,24 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.UUID; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmos.CosmosUser; -import com.microsoft.azure.cosmos.CosmosUserResponse; -import com.microsoft.azure.cosmos.CosmosUserSettings; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosUser; +import com.azure.data.cosmos.CosmosUserResponse; +import com.azure.data.cosmos.CosmosUserSettings; import reactor.core.publisher.Mono; @@ -58,13 +58,13 @@ public UserCrudTest(CosmosClientBuilder clientBuilder) { public void createUser() throws Exception { //create user CosmosUserSettings user = new CosmosUserSettings(); - user.setId(UUID.randomUUID().toString()); + user.id(UUID.randomUUID().toString()); Mono createObservable = createdDatabase.createUser(user, null); // validate user creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(user.getId()) + .withId(user.id()) .notNullEtag() .build(); validateSuccess(createObservable, validator); @@ -75,16 +75,16 @@ public void readUser() throws Exception { //create user CosmosUserSettings user = new CosmosUserSettings(); - user.setId(UUID.randomUUID().toString()); + user.id(UUID.randomUUID().toString()); - CosmosUser readBackUser = createdDatabase.createUser(user, null).block().getUser(); + CosmosUser readBackUser = createdDatabase.createUser(user, null).block().user(); // read user Mono readObservable = readBackUser.read(null); //validate user read CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(readBackUser.getId()) + .withId(readBackUser.id()) .notNullEtag() .build(); @@ -95,9 +95,9 @@ public void readUser() throws Exception { public void deleteUser() throws Exception { //create user CosmosUserSettings user = new CosmosUserSettings(); - user.setId(UUID.randomUUID().toString()); + user.id(UUID.randomUUID().toString()); - CosmosUser readBackUser = createdDatabase.createUser(user, null).block().getUser(); + CosmosUser readBackUser = createdDatabase.createUser(user, null).block().user(); // delete user Mono deleteObservable = readBackUser.delete(null); @@ -119,13 +119,13 @@ public void upsertUser() throws Exception { //create user CosmosUserSettings user = new CosmosUserSettings(); - user.setId(UUID.randomUUID().toString()); + user.id(UUID.randomUUID().toString()); Mono upsertObservable = createdDatabase.upsertUser(user, null); //validate user upsert CosmosResponseValidator validatorForUpsert = new CosmosResponseValidator.Builder() - .withId(user.getId()) + .withId(user.id()) .notNullEtag() .build(); @@ -137,30 +137,30 @@ public void replaceUser() throws Exception { //create user CosmosUserSettings user = new CosmosUserSettings(); - user.setId(UUID.randomUUID().toString()); + user.id(UUID.randomUUID().toString()); - CosmosUserSettings readBackUser = createdDatabase.createUser(user, null).block().getCosmosUserSettings(); + CosmosUserSettings readBackUser = createdDatabase.createUser(user, null).block().settings(); // read user to validate creation - Mono readObservable = createdDatabase.getUser(user.getId()).read(); + Mono readObservable = createdDatabase.getUser(user.id()).read(); //validate user read CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() - .withId(readBackUser.getId()) + .withId(readBackUser.id()) .notNullEtag() .build(); validateSuccess(readObservable, validatorForRead); //update user - String oldId = readBackUser.getId(); - readBackUser.setId(UUID.randomUUID().toString()); + String oldId = readBackUser.id(); + readBackUser.id(UUID.randomUUID().toString()); Mono updateObservable = createdDatabase.getUser(oldId).replace(readBackUser, null); // validate user replace CosmosResponseValidator validatorForUpdate = new CosmosResponseValidator.Builder() - .withId(readBackUser.getId()) + .withId(readBackUser.id()) .notNullEtag() .build(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java similarity index 81% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java index 81f6109709890..49f6f9c99e379 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java @@ -20,24 +20,24 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.UUID; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosRequestOptions; -import com.microsoft.azure.cosmos.CosmosResponse; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmos.CosmosUserDefinedFunction; -import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionResponse; -import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionSettings; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosRequestOptions; +import com.azure.data.cosmos.CosmosResponse; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosUserDefinedFunction; +import com.azure.data.cosmos.CosmosUserDefinedFunctionResponse; +import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; import reactor.core.publisher.Mono; @@ -55,14 +55,14 @@ public UserDefinedFunctionCrudTest(CosmosClientBuilder clientBuilder) { public void createUserDefinedFunction() throws Exception { // create udf CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); - udf.setId(UUID.randomUUID().toString()); - udf.setBody("function() {var x = 10;}"); + udf.id(UUID.randomUUID().toString()); + udf.body("function() {var x = 10;}"); Mono createObservable = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()); // validate udf creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(udf.getId()) + .withId(udf.id()) .withUserDefinedFunctionBody("function() {var x = 10;}") .notNullEtag() .build(); @@ -73,9 +73,9 @@ public void createUserDefinedFunction() throws Exception { public void readUserDefinedFunction() throws Exception { // create a udf CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); - udf.setId(UUID.randomUUID().toString()); - udf.setBody("function() {var x = 10;}"); - CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().getCosmosUserDefinedFunction(); + udf.id(UUID.randomUUID().toString()); + udf.body("function() {var x = 10;}"); + CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); // read udf waitIfNeededForReplicasToCatchUp(clientBuilder); @@ -83,7 +83,7 @@ public void readUserDefinedFunction() throws Exception { //validate udf read CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(udf.getId()) + .withId(udf.id()) .withUserDefinedFunctionBody("function() {var x = 10;}") .notNullEtag() .build(); @@ -94,9 +94,9 @@ public void readUserDefinedFunction() throws Exception { public void deleteUserDefinedFunction() throws Exception { // create a udf CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); - udf.setId(UUID.randomUUID().toString()); - udf.setBody("function() {var x = 10;}"); - CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().getCosmosUserDefinedFunction(); + udf.id(UUID.randomUUID().toString()); + udf.body("function() {var x = 10;}"); + CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); // delete udf Mono deleteObservable = readBackUdf.delete(new CosmosRequestOptions()); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java similarity index 80% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java index aa0449c0a7f30..ca86d0ed408da 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -29,20 +29,20 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosRequestOptions; -import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionSettings; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.DocumentClientException; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosRequestOptions; +import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Flux; @@ -55,7 +55,7 @@ public class UserDefinedFunctionQueryTest extends TestSuiteBase { private CosmosClient client; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); + return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } @Factory(dataProvider = "clientBuildersWithDirect") @@ -66,21 +66,21 @@ public UserDefinedFunctionQueryTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryWithFilter() throws Exception { - String filterId = createdUDF.get(0).getId(); + String filterId = createdUDF.get(0).id(); String query = String.format("SELECT * from c where c.id = '%s'", filterId); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(5); + options.maxItemCount(5); Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); - List expectedDocs = createdUDF.stream().filter(sp -> filterId.equals(sp.getId()) ).collect(Collectors.toList()); + List expectedDocs = createdUDF.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) - .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -94,7 +94,7 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() @@ -111,19 +111,19 @@ public void queryAll() throws Exception { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(3); - options.setEnableCrossPartitionQuery(true); + options.maxItemCount(3); + options.enableCrossPartitionQuery(true); Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); List expectedDocs = createdUDF; - int expectedPageSize = (expectedDocs.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() - .map(d -> d.getResourceId()) + .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() @@ -136,11 +136,11 @@ public void queryAll() throws Exception { public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); FailureValidator validator = new FailureValidator.Builder() - .instanceOf(DocumentClientException.class) + .instanceOf(CosmosClientException.class) .statusCode(400) .notNullActivityId() .build(); @@ -149,7 +149,7 @@ public void invalidQuerySytax() throws Exception { public CosmosUserDefinedFunctionSettings createUserDefinedFunction(CosmosContainer cosmosContainer) { CosmosUserDefinedFunctionSettings storedProcedure = getUserDefinedFunctionDef(); - return cosmosContainer.createUserDefinedFunction(storedProcedure, new CosmosRequestOptions()).block().getCosmosUserDefinedFunctionSettings(); + return cosmosContainer.createUserDefinedFunction(storedProcedure, new CosmosRequestOptions()).block().settings(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) @@ -172,8 +172,8 @@ public void afterClass() { private static CosmosUserDefinedFunctionSettings getUserDefinedFunctionDef() { CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); - udf.setId(UUID.randomUUID().toString()); - udf.setBody("function() {var x = 10;}"); + udf.id(UUID.randomUUID().toString()); + udf.body("function() {var x = 10;}"); return udf; } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java similarity index 76% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionUpsertReplaceTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java index 793b5ad6581bc..3b2c62aa66025 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserDefinedFunctionUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java @@ -20,25 +20,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import java.util.UUID; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.directconnectivity.Protocol; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosRequestOptions; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionResponse; -import com.microsoft.azure.cosmos.CosmosUserDefinedFunctionSettings; -import com.microsoft.azure.cosmosdb.RequestOptions; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosRequestOptions; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosUserDefinedFunctionResponse; +import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; +import com.azure.data.cosmos.RequestOptions; import reactor.core.publisher.Mono; @@ -58,16 +58,16 @@ public void replaceUserDefinedFunction() throws Exception { // create a udf CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); - udf.setId(UUID.randomUUID().toString()); - udf.setBody("function() {var x = 10;}"); + udf.id(UUID.randomUUID().toString()); + udf.body("function() {var x = 10;}"); CosmosUserDefinedFunctionSettings readBackUdf = null; try { - readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().getCosmosUserDefinedFunctionSettings(); + readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().settings(); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -76,24 +76,24 @@ public void replaceUserDefinedFunction() throws Exception { // read udf to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder); - Mono readObservable = createdCollection.getUserDefinedFunction(readBackUdf.getId()).read(new RequestOptions()); + Mono readObservable = createdCollection.getUserDefinedFunction(readBackUdf.id()).read(new RequestOptions()); // validate udf creation CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() - .withId(readBackUdf.getId()) + .withId(readBackUdf.id()) .withUserDefinedFunctionBody("function() {var x = 10;}") .notNullEtag() .build(); validateSuccess(readObservable, validatorForRead); //update udf - readBackUdf.setBody("function() {var x = 11;}"); + readBackUdf.body("function() {var x = 11;}"); - Mono replaceObservable = createdCollection.getUserDefinedFunction(readBackUdf.getId()).replace(readBackUdf, new RequestOptions()); + Mono replaceObservable = createdCollection.getUserDefinedFunction(readBackUdf.id()).replace(readBackUdf, new RequestOptions()); //validate udf replace CosmosResponseValidator validatorForReplace = new CosmosResponseValidator.Builder() - .withId(readBackUdf.getId()) + .withId(readBackUdf.id()) .withUserDefinedFunctionBody("function() {var x = 11;}") .notNullEtag() .build(); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java similarity index 84% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java index 5003dd13cfe1e..2f45a51463818 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/UserQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; +package com.azure.data.cosmos.rx; import static org.assertj.core.api.Assertions.assertThat; @@ -29,19 +29,19 @@ import java.util.UUID; import java.util.stream.Collectors; -import com.microsoft.azure.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientBuilder; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosDatabase; -import com.microsoft.azure.cosmos.CosmosDatabaseForTest; -import com.microsoft.azure.cosmos.CosmosUserSettings; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.FeedResponse; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosUserSettings; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Flux; @@ -62,23 +62,23 @@ public UserQueryTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryUsersWithFilter() throws Exception { - String filterUserId = createdUsers.get(0).getId(); + String filterUserId = createdUsers.get(0).id(); String query = String.format("SELECT * from c where c.id = '%s'", filterUserId); FeedOptions options = new FeedOptions(); - options.setMaxItemCount(5); + options.maxItemCount(5); Flux> queryObservable = createdDatabase.queryUsers(query, options); List expectedUsers = createdUsers.stream() - .filter(c -> StringUtils.equals(filterUserId, c.getId()) ).collect(Collectors.toList()); + .filter(c -> StringUtils.equals(filterUserId, c.id()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); - int expectedPageSize = (expectedUsers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedUsers.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedUsers.size()) - .exactlyContainsInAnyOrder(expectedUsers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedUsers.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -93,7 +93,7 @@ public void queryAllUsers() throws Exception { String query = "SELECT * from c"; FeedOptions options = new FeedOptions(); - options.setMaxItemCount(2); + options.maxItemCount(2); String databaseLink = Utils.getDatabaseNameLink(databaseId); Flux> queryObservable = createdDatabase.queryUsers(query, options); @@ -101,11 +101,11 @@ public void queryAllUsers() throws Exception { assertThat(expectedUsers).isNotEmpty(); - int expectedPageSize = (expectedUsers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount(); + int expectedPageSize = (expectedUsers.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedUsers.size()) - .exactlyContainsInAnyOrder(expectedUsers.stream().map(d -> d.getResourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedUsers.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -138,8 +138,8 @@ public void beforeClass() throws Exception { for(int i = 0; i < 5; i++) { CosmosUserSettings user = new CosmosUserSettings(); - user.setId(UUID.randomUUID().toString()); - createdUsers.add(createUser(client, databaseId, user).read().block().getCosmosUserSettings()); + user.id(UUID.randomUUID().toString()); + createdUsers.add(createUser(client, databaseId, user).read().block().settings()); } waitIfNeededForReplicasToCatchUp(clientBuilder); diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java similarity index 82% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java index 99750757ed8d0..5cdd86ecbce70 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/VeryLargeDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java @@ -20,19 +20,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx; - -import com.microsoft.azure.cosmos.CosmosClient; -import com.microsoft.azure.cosmos.CosmosClientBuilder; -import com.microsoft.azure.cosmos.CosmosContainer; -import com.microsoft.azure.cosmos.CosmosItemRequestOptions; -import com.microsoft.azure.cosmos.CosmosItemResponse; -import com.microsoft.azure.cosmos.CosmosResponseValidator; -import com.microsoft.azure.cosmosdb.Database; -import com.microsoft.azure.cosmosdb.Document; -import com.microsoft.azure.cosmosdb.FeedOptions; -import com.microsoft.azure.cosmosdb.RetryAnalyzer; -import com.microsoft.azure.cosmosdb.internal.directconnectivity.Protocol; +package com.azure.data.cosmos.rx; + +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.CosmosItemResponse; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.RetryAnalyzer; +import com.azure.data.cosmos.directconnectivity.Protocol; import reactor.core.publisher.Mono; @@ -69,12 +69,12 @@ public void queryLargeDocuments() throws InterruptedException { try { FeedOptions options = new FeedOptions(); - options.setEnableCrossPartitionQuery(true); + options.enableCrossPartitionQuery(true); validateQuerySuccess(createdCollection.queryItems("SELECT * FROM r", options), new FeedResponseListValidator.Builder().totalSize(cnt).build()); } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.Tcp) { - String message = String.format("Direct TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); + if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { + String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); logger.info(message, error); throw new SkipException(message, error); } @@ -92,7 +92,7 @@ private void createLargeDocument() throws InterruptedException { Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.getId()) + .withId(docDefinition.id()) .build(); validateSuccess(createObservable, validator); @@ -121,6 +121,6 @@ private static Document getDocumentDefinition() { } public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.getId(), createdCollection.getId()); + return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } } diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyChannelInitializer.java b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java similarity index 97% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyChannelInitializer.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java index 7b1f613713c14..93a6eefef7687 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyChannelInitializer.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.proxy; +package com.azure.data.cosmos.rx.proxy; import java.util.concurrent.atomic.AtomicLong; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyClientHandler.java b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java similarity index 98% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyClientHandler.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java index 4afdcc7181a58..40d71b34997c8 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyClientHandler.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.proxy; +package com.azure.data.cosmos.rx.proxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyClientHeader.java b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHeader.java similarity index 98% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyClientHeader.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHeader.java index 287f54151c8de..f58c47cc23d55 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyClientHeader.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHeader.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.proxy; +package com.azure.data.cosmos.rx.proxy; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyRemoteHandler.java b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java similarity index 98% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyRemoteHandler.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java index cf72b251d5fb3..7a0bb6833feeb 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyRemoteHandler.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.proxy; +package com.azure.data.cosmos.rx.proxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyServer.java b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java similarity index 98% rename from sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyServer.java rename to sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java index 49d49a86db5a2..575c738dc8948 100644 --- a/sdk/src/test/java/com/microsoft/azure/cosmosdb/rx/proxy/HttpProxyServer.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.microsoft.azure.cosmosdb.rx.proxy; +package com.azure.data.cosmos.rx.proxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sdk/src/test/resources/emulator-testng.xml b/sdk/src/test/resources/emulator-testng.xml index 8af636bea2f5f..16bec3b3b396c 100644 --- a/sdk/src/test/resources/emulator-testng.xml +++ b/sdk/src/test/resources/emulator-testng.xml @@ -29,7 +29,7 @@ - + diff --git a/sdk/src/test/resources/fast-testng.xml b/sdk/src/test/resources/fast-testng.xml index b4d5f30b252ad..b78fb1cab3254 100644 --- a/sdk/src/test/resources/fast-testng.xml +++ b/sdk/src/test/resources/fast-testng.xml @@ -29,7 +29,7 @@ - + diff --git a/sdk/src/test/resources/long-testng.xml b/sdk/src/test/resources/long-testng.xml index e96812dfbe416..debd90ba2136e 100644 --- a/sdk/src/test/resources/long-testng.xml +++ b/sdk/src/test/resources/long-testng.xml @@ -29,7 +29,7 @@ - + From 4dde12d5b60188ed08d66e7c2e0f7e92b7420557 Mon Sep 17 00:00:00 2001 From: Srinath Narayanan Date: Thu, 13 Jun 2019 13:29:31 -0700 Subject: [PATCH 37/85] Multiple fixes for making v3 branch healthy (#185) * changes to ConsistencyLevel * removed changes to DocumentCrudTests edited manner in which ConsistencyLevel.toString is implemented * Refactored Direct TCP into v3 namespace, Updated CosmosClientException and TransportException which are now stackless (for performance), and fixed a dependency issue (see pom.xml changes). * Revised a long-standing TODO which ensures that the DirectHttpsClientUnderTest is created with Protocol.HTTPS. Added names to all Cosmos Client tests that derive from TestSuiteBase and--in the case of the examples--NamedCosmosClientTest. Test names include the class name, method name, connection mode, and consistency level. Also: Optimized imports. * Added two base test classes from which each variant of TestSuiteBase inherits: CosmosClientTest and DocumentClientTest --- benchmark/pom.xml | 77 +- .../data/cosmos/benchmark/AsyncBenchmark.java | 12 +- .../cosmos/benchmark/AsyncQueryBenchmark.java | 5 +- .../AsyncQuerySinglePartitionMultiple.java | 1 - .../cosmos/benchmark/AsyncReadBenchmark.java | 3 +- .../cosmos/benchmark/AsyncWriteBenchmark.java | 10 +- .../data/cosmos/benchmark/Configuration.java | 21 +- .../data/cosmos/benchmark/DocDBUtils.java | 2 +- .../com/azure/data/cosmos/benchmark/Main.java | 5 +- .../cosmos/benchmark/ReadMyWriteWorkflow.java | 2 +- .../cosmos/benchmark/QueryBuilderTest.java | 2 +- .../ReadMyWritesConsistencyTest.java | 6 +- .../azure/data/cosmos/benchmark/Utils.java | 2 +- .../data/cosmos/benchmark/WorkflowTest.java | 4 +- commons-test-utils/pom.xml | 45 +- .../data/cosmos/rx/FailureValidator.java | 2 +- .../cosmos/rx/FeedResponseListValidator.java | 18 +- .../data/cosmos/rx/FeedResponseValidator.java | 8 +- .../cosmos/rx/ResourceResponseValidator.java | 27 +- .../data/cosmos/rx/ResourceValidator.java | 4 +- .../data/cosmos/rx/TestConfigurations.java | 3 +- commons/pom.xml | 6 - .../azure/data/cosmos/AccessCondition.java | 2 + .../com/azure/data/cosmos/BridgeInternal.java | 8 +- .../azure/data/cosmos/ChangeFeedOptions.java | 3 + .../cosmos/ClientSideRequestStatistics.java | 14 +- .../com/azure/data/cosmos/CompositePath.java | 6 +- .../data/cosmos/ConflictResolutionMode.java | 10 +- .../data/cosmos/ConflictResolutionPolicy.java | 6 +- .../azure/data/cosmos/ConnectionPolicy.java | 11 + .../azure/data/cosmos/ConsistencyLevel.java | 10 +- .../azure/data/cosmos/ConsistencyPolicy.java | 9 +- .../data/cosmos/CosmosClientException.java | 72 +- .../data/cosmos/CosmosContainerSettings.java | 4 + .../data/cosmos/CosmosItemProperties.java | 2 +- .../data/cosmos/CosmosItemRequestOptions.java | 6 + .../CosmosStoredProcedureRequestOptions.java | 3 + .../data/cosmos/CosmosTriggerSettings.java | 8 +- .../CosmosUserDefinedFunctionSettings.java | 1 + .../azure/data/cosmos/CosmosUserSettings.java | 4 +- .../java/com/azure/data/cosmos/DataType.java | 10 +- .../java/com/azure/data/cosmos/Database.java | 3 +- .../azure/data/cosmos/DatabaseAccount.java | 7 +- .../java/com/azure/data/cosmos/Document.java | 6 +- .../java/com/azure/data/cosmos/Error.java | 2 +- .../com/azure/data/cosmos/ExcludedPath.java | 1 + .../com/azure/data/cosmos/FeedOptions.java | 8 + .../azure/data/cosmos/FeedOptionsBase.java | 5 + .../com/azure/data/cosmos/FeedResponse.java | 9 +- .../java/com/azure/data/cosmos/HashIndex.java | 8 +- .../com/azure/data/cosmos/IncludedPath.java | 9 +- .../java/com/azure/data/cosmos/Index.java | 6 +- .../java/com/azure/data/cosmos/IndexKind.java | 9 +- .../azure/data/cosmos/IndexingDirective.java | 9 +- .../com/azure/data/cosmos/IndexingMode.java | 9 +- .../com/azure/data/cosmos/IndexingPolicy.java | 9 +- .../azure/data/cosmos/JsonSerializable.java | 43 +- .../com/azure/data/cosmos/MediaResponse.java | 4 +- .../java/com/azure/data/cosmos/Offer.java | 3 +- .../com/azure/data/cosmos/PartitionKey.java | 2 +- .../data/cosmos/PartitionKeyDefinition.java | 14 +- .../azure/data/cosmos/PartitionKeyRange.java | 4 +- .../com/azure/data/cosmos/PartitionKind.java | 9 +- .../com/azure/data/cosmos/Permission.java | 6 +- .../com/azure/data/cosmos/PermissionMode.java | 8 + .../com/azure/data/cosmos/RangeIndex.java | 8 +- .../java/com/azure/data/cosmos/Resource.java | 10 +- .../azure/data/cosmos/ResourceResponse.java | 11 +- .../com/azure/data/cosmos/RetryOptions.java | 2 + .../com/azure/data/cosmos/SpatialIndex.java | 7 +- .../com/azure/data/cosmos/SpatialSpec.java | 10 +- .../com/azure/data/cosmos/SpatialType.java | 10 +- .../com/azure/data/cosmos/SqlParameter.java | 2 + .../com/azure/data/cosmos/SqlQuerySpec.java | 2 + .../data/cosmos/StoredProcedureResponse.java | 7 +- .../java/com/azure/data/cosmos/Trigger.java | 7 +- .../azure/data/cosmos/TriggerOperation.java | 7 + .../com/azure/data/cosmos/TriggerType.java | 7 + .../java/com/azure/data/cosmos/UniqueKey.java | 5 +- .../azure/data/cosmos/UniqueKeyPolicy.java | 4 +- .../AddressInformation.java | 2 +- .../cosmos/directconnectivity/Protocol.java | 7 + .../directconnectivity/StoreResult.java | 4 +- .../azure/data/cosmos/internal/Configs.java | 7 +- .../DocumentServiceRequestContext.java | 8 +- .../cosmos/internal/HttpClientFactory.java | 4 +- .../data/cosmos/internal/PathsHelper.java | 12 +- .../ResourceTokenAuthorizationHelper.java | 9 +- .../internal/RxDocumentServiceRequest.java | 20 +- .../internal/RxDocumentServiceResponse.java | 6 +- .../azure/data/cosmos/internal/Strings.java | 21 + .../com/azure/data/cosmos/internal/Utils.java | 15 +- .../routing/BoolPartitionKeyComponent.java | 6 +- .../routing/IPartitionKeyComponent.java | 4 +- .../InfinityPartitionKeyComponent.java | 6 +- .../MaxNumberPartitionKeyComponent.java | 6 +- .../MaxStringPartitionKeyComponent.java | 6 +- .../MinNumberPartitionKeyComponent.java | 6 +- .../MinStringPartitionKeyComponent.java | 6 +- .../routing/NullPartitionKeyComponent.java | 6 +- .../routing/NumberPartitionKeyComponent.java | 6 +- .../routing/PartitionKeyInternal.java | 8 +- .../data/cosmos/internal/routing/Range.java | 6 +- .../routing/StringPartitionKeyComponent.java | 6 +- .../UndefinedPartitionKeyComponent.java | 6 +- .../com/azure/data/cosmos/ConflictTests.java | 2 - .../cosmos/CosmosClientExceptionTest.java | 2 - .../data/cosmos/DocumentCollectionTests.java | 3 - .../com/azure/data/cosmos/DocumentTests.java | 6 +- .../azure/data/cosmos/IncludedPathTest.java | 15 +- .../data/cosmos/JsonSerializableTests.java | 14 +- .../com/azure/data/cosmos/PermissionTest.java | 7 +- .../azure/data/cosmos/ResourceIdTests.java | 9 +- .../directconnectivity/HttpUtilsTest.java | 18 +- .../directconnectivity/StoreResponseTest.java | 6 +- .../data/cosmos/internal/ConfigsTests.java | 6 +- .../data/cosmos/internal/PathsHelperTest.java | 1 + .../RxDocumentServiceRequestTest.java | 12 +- .../data/cosmos/internal/TimeTokenTest.java | 6 +- .../StringPartitionKeyComponentTest.java | 1 + direct-impl/pom.xml | 11 +- .../directconnectivity/AddressResolver.java | 16 +- .../BarrierRequestHelper.java | 8 +- .../directconnectivity/ConsistencyReader.java | 17 +- .../directconnectivity/ConsistencyWriter.java | 6 +- .../GatewayAddressCache.java | 14 +- .../GatewayServiceConfigurationReader.java | 20 +- .../GoneAndRetryWithRetryPolicy.java | 14 +- .../HttpTransportClient.java | 18 +- .../directconnectivity/QuorumReader.java | 6 +- .../ReplicatedResourceClient.java | 18 +- .../directconnectivity/RequestHelper.java | 4 +- .../RntbdTransportClient.java | 571 ++++++--------- .../directconnectivity/ServerStoreModel.java | 4 +- .../directconnectivity/StoreClient.java | 16 +- .../StoreClientFactory.java | 4 +- .../directconnectivity/StoreReader.java | 4 +- .../TransportException.java | 52 +- .../rntbd/RntbdClientChannelHandler.java | 139 ++++ .../rntbd/RntbdClientChannelInitializer.java | 102 --- .../rntbd/RntbdClientChannelPool.java | 266 +++++++ .../rntbd/RntbdConstants.java | 99 +-- .../rntbd/RntbdContext.java | 149 ++-- .../rntbd/RntbdContextDecoder.java | 27 +- .../rntbd/RntbdContextException.java | 61 ++ .../rntbd/RntbdContextNegotiator.java | 27 +- .../rntbd/RntbdContextRequest.java | 72 +- .../rntbd/RntbdContextRequestDecoder.java | 12 +- .../rntbd/RntbdContextRequestEncoder.java | 11 +- .../rntbd/RntbdEndpoint.java | 119 ++++ .../directconnectivity/rntbd/RntbdFramer.java | 64 +- .../rntbd/RntbdMetrics.java | 159 +++++ .../rntbd/RntbdObjectMapper.java | 69 +- .../rntbd/RntbdReporter.java | 85 +++ .../rntbd/RntbdRequest.java | 95 +-- .../rntbd/RntbdRequestArgs.java | 59 +- .../rntbd/RntbdRequestDecoder.java | 14 +- .../rntbd/RntbdRequestEncoder.java | 14 +- .../rntbd/RntbdRequestFrame.java | 66 +- .../rntbd/RntbdRequestFramer.java | 2 +- .../rntbd/RntbdRequestHeaders.java | 330 +++++---- .../rntbd/RntbdRequestManager.java | 658 +++++++++--------- .../rntbd/RntbdRequestRecord.java | 94 +++ .../rntbd/RntbdRequestTimer.java | 62 ++ .../rntbd/RntbdResponse.java | 85 +-- .../rntbd/RntbdResponseDecoder.java | 8 +- .../rntbd/RntbdResponseHeaders.java | 244 +++---- .../rntbd/RntbdResponseStatus.java | 30 +- .../rntbd/RntbdServiceEndpoint.java | 354 ++++++++++ .../directconnectivity/rntbd/RntbdToken.java | 143 ++-- .../rntbd/RntbdTokenStream.java | 39 +- .../rntbd/RntbdTokenType.java | 376 +++++----- .../directconnectivity/rntbd/RntbdUUID.java | 19 +- .../data/cosmos/PartitionKeyHashingTests.java | 13 +- .../AddressResolverTest.java | 14 +- .../AddressSelectorTest.java | 4 +- .../AddressSelectorWrapper.java | 4 +- .../ConsistencyReaderTest.java | 28 +- .../ConsistencyWriterTest.java | 4 +- .../directconnectivity/EndpointMock.java | 2 +- .../GoneAndRetryWithRetryPolicyTest.java | 6 +- .../HttpTransportClientTest.java | 12 +- .../MultiStoreResultValidator.java | 2 +- .../MurmurHash3_32Test.java | 2 +- .../PartitionKeyInternalTest.java | 6 +- .../directconnectivity/PartitionKeyTest.java | 4 +- .../directconnectivity/QuorumReaderTest.java | 12 +- ...catedResourceClientPartitionSplitTest.java | 12 +- .../ReplicatedResourceClientTest.java | 6 +- .../RntbdTransportClientTest.java | 302 ++++---- .../StoreReaderDotNetTest.java | 12 +- .../directconnectivity/StoreReaderTest.java | 22 +- .../StoreReaderUnderTest.java | 2 +- .../data/cosmos/internal/RetryUtilsTest.java | 23 +- examples/pom.xml | 45 +- .../azure/data/cosmos/examples/BasicDemo.java | 9 +- .../ChangeFeed/SampleChangeFeedProcessor.java | 10 +- .../ChangeFeed/SampleObserverImpl.java | 1 - .../rx/examples/multimaster/Helpers.java | 2 +- .../multimaster/samples/ConflictWorker.java | 14 +- .../samples/MultiMasterScenario.java | 4 +- .../azure/data/cosmos/DocumentClientTest.java | 73 ++ .../examples/CollectionCRUDAsyncAPITest.java | 76 +- .../cosmos/rx/examples/ConflictAPITest.java | 25 +- .../rx/examples/DatabaseCRUDAsyncAPITest.java | 60 +- .../rx/examples/DocumentCRUDAsyncAPITest.java | 102 +-- .../examples/DocumentQueryAsyncAPITest.java | 69 +- .../rx/examples/InMemoryGroupbyTest.java | 50 +- .../rx/examples/OfferCRUDAsyncAPITest.java | 39 +- .../examples/StoredProcedureAsyncAPITest.java | 69 +- .../rx/examples/TestConfigurations.java | 3 +- .../cosmos/rx/examples/TokenResolverTest.java | 49 +- .../rx/examples/UniqueIndexAsyncAPITest.java | 36 +- .../azure/data/cosmos/rx/examples/Utils.java | 2 +- gateway/pom.xml | 6 - .../cosmos/internal/BackoffRetryUtility.java | 5 +- .../BaseAuthorizationTokenProvider.java | 14 +- .../internal/GlobalEndpointManager.java | 5 +- .../internal/ICollectionRoutingMapCache.java | 1 - .../data/cosmos/internal/IRetryPolicy.java | 4 +- .../cosmos/internal/IRoutingMapProvider.java | 7 +- .../InvalidPartitionExceptionRetryPolicy.java | 7 +- .../PartitionKeyMismatchRetryPolicy.java | 9 +- .../PartitionKeyRangeGoneRetryPolicy.java | 9 +- ...enameCollectionAwareClientRetryPolicy.java | 5 +- .../ResetSessionTokenRetryPolicyFactory.java | 2 +- .../internal/ResourceThrottleRetryPolicy.java | 5 +- .../data/cosmos/internal/RetryUtils.java | 7 +- .../cosmos/internal/RxGatewayStoreModel.java | 7 +- .../cosmos/internal/caches/AsyncCache.java | 5 +- .../cosmos/internal/caches/AsyncLazy.java | 1 - .../caches/IPartitionKeyRangeCache.java | 11 +- .../caches/RxClientCollectionCache.java | 27 +- .../internal/caches/RxCollectionCache.java | 12 +- ...ggregateDocumentQueryExecutionContext.java | 19 +- .../query/CompositeContinuationToken.java | 3 +- .../DefaultDocumentQueryExecutionContext.java | 33 +- .../internal/query/DocumentProducer.java | 30 +- .../DocumentQueryExecutionContextBase.java | 23 +- .../DocumentQueryExecutionContextFactory.java | 13 +- .../data/cosmos/internal/query/Fetcher.java | 10 +- .../internal/query/IDocumentQueryClient.java | 5 +- .../IDocumentQueryExecutionComponent.java | 1 - .../query/IDocumentQueryExecutionContext.java | 1 - .../query/OrderByContinuationToken.java | 13 +- .../query/OrderByDocumentProducer.java | 19 +- .../OrderByDocumentQueryExecutionContext.java | 43 +- .../cosmos/internal/query/OrderByUtils.java | 21 +- .../data/cosmos/internal/query/Paginator.java | 2 +- ...ParallelDocumentQueryExecutionContext.java | 30 +- ...llelDocumentQueryExecutionContextBase.java | 19 +- .../query/PartitionedQueryExecutionInfo.java | 4 +- ...PartitionedQueryExecutionInfoInternal.java | 6 +- ...ipelinedDocumentQueryExecutionContext.java | 9 +- .../ProxyDocumentQueryExecutionContext.java | 16 +- .../data/cosmos/internal/query/QueryInfo.java | 9 +- .../internal/query/TakeContinuationToken.java | 1 - .../TopDocumentQueryExecutionContext.java | 9 +- .../query/aggregation/AverageAggregator.java | 4 +- .../query/orderbyquery/OrderByRowResult.java | 4 +- .../orderbyquery/OrderbyRowComparer.java | 15 +- .../routing/CollectionRoutingMap.java | 6 +- .../routing/InMemoryCollectionRoutingMap.java | 11 +- .../internal/routing/LocationCache.java | 7 +- .../internal/routing/RoutingMapProvider.java | 4 +- .../routing/RoutingMapProviderHelper.java | 4 +- .../cosmos/internal/SessionContainerTest.java | 4 +- .../internal/caches/AsyncCacheTest.java | 11 +- .../InMemoryCollectionRoutingMapTest.java | 13 +- .../internal/routing/LocationCacheTest.java | 10 +- .../routing/RoutingMapProviderHelperTest.java | 11 +- pom.xml | 50 +- sdk/pom.xml | 6 - .../data/cosmos/AsyncDocumentClient.java | 9 +- .../data/cosmos/ChangeFeedProcessor.java | 1 - .../com/azure/data/cosmos/CosmosClient.java | 3 +- .../azure/data/cosmos/CosmosContainer.java | 3 +- .../com/azure/data/cosmos/CosmosDatabase.java | 1 - .../data/cosmos/CosmosPermissionSettings.java | 3 +- .../changefeed/ChangeFeedContextClient.java | 4 +- .../data/cosmos/changefeed/LeaseManager.java | 1 - .../cosmos/changefeed/ServiceItemLease.java | 4 +- .../internal/ChangeFeedContextClientImpl.java | 8 +- .../ChangeFeedObserverContextImpl.java | 2 +- .../ChangeFeedObserverFactoryImpl.java | 2 +- .../ChangeFeedProcessorBuilderImpl.java | 2 +- .../internal/CheckpointerObserverFactory.java | 2 +- .../internal/DocumentServiceLeaseStore.java | 8 +- .../DocumentServiceLeaseUpdaterImpl.java | 6 +- ...onitoringPartitionControllerDecorator.java | 2 +- .../internal/LeaseStoreManagerImpl.java | 11 +- .../internal/PartitionControllerImpl.java | 4 +- .../internal/PartitionProcessorImpl.java | 12 +- .../PartitionSupervisorFactoryImpl.java | 2 +- .../internal/PartitionSupervisorImpl.java | 8 +- .../internal/PartitionSynchronizerImpl.java | 4 +- ...edByIdCollectionRequestOptionsFactory.java | 4 +- .../cosmos/internal/ChangeFeedQueryImpl.java | 9 +- .../cosmos/internal/RxDocumentClientImpl.java | 22 +- .../caches/RxPartitionKeyRangeCache.java | 38 +- .../GlobalAddressResolver.java | 8 +- .../data/cosmos/ClientUnderTestBuilder.java | 6 +- .../azure/data/cosmos/CosmosClientTest.java | 73 ++ .../data/cosmos/CosmosContainerCrudTest.java | 188 ----- .../data/cosmos/CosmosDatabaseCrudTest.java | 141 ---- .../data/cosmos/CosmosDatabaseForTest.java | 1 - .../azure/data/cosmos/CosmosItemCrudTest.java | 146 ---- .../data/cosmos/CosmosPartitionKeyTests.java | 50 +- .../data/cosmos/CosmosTestSuiteBase.java | 170 ----- .../azure/data/cosmos/DocumentClientTest.java | 73 ++ .../azure/data/cosmos/SpyClientBuilder.java | 1 - .../BarrierRequestHelperTest.java | 8 +- .../DCDocumentCrudTest.java | 39 +- .../GatewayAddressCacheTest.java | 20 +- ...GatewayServiceConfigurationReaderTest.java | 44 +- .../cosmos/internal/ConsistencyTests1.java | 2 +- .../cosmos/internal/ConsistencyTests2.java | 12 +- .../cosmos/internal/ConsistencyTestsBase.java | 2 +- .../DocumentQuerySpyWireContentTest.java | 37 +- .../cosmos/internal/NetworkFailureTest.java | 6 +- .../internal/RetryCreateDocumentTest.java | 14 +- .../cosmos/internal/RetryThrottleTest.java | 36 +- .../internal/RxDocumentClientUnderTest.java | 1 - .../data/cosmos/internal/SessionTest.java | 13 +- .../internal/SpyClientUnderTestFactory.java | 25 +- .../cosmos/internal/StoreHeaderTests.java | 8 +- .../data/cosmos/internal/TestSuiteBase.java | 115 +-- .../GlobalAddressResolverTest.java | 16 +- .../directconnectivity/ReflectionUtils.java | 4 +- .../internal/query/DocumentProducerTest.java | 16 +- .../internal/query/FeedResponseBuilder.java | 2 +- .../cosmos/internal/query/FetcherTest.java | 22 +- .../data/cosmos/rx/AggregateQueryTests.java | 36 +- .../rx/BackPressureCrossPartitionTest.java | 88 +-- .../data/cosmos/rx/BackPressureTest.java | 23 +- .../azure/data/cosmos/rx/ChangeFeedTest.java | 31 +- .../data/cosmos/rx/CollectionCrudTest.java | 52 +- .../data/cosmos/rx/CollectionQueryTest.java | 32 +- .../data/cosmos/rx/DatabaseCrudTest.java | 18 +- .../data/cosmos/rx/DatabaseQueryTest.java | 28 +- .../rx/DocumentClientResourceLeakTest.java | 59 +- .../data/cosmos/rx/DocumentCrudTest.java | 62 +- .../azure/data/cosmos/rx/LogLevelTest.java | 36 +- .../rx/MultiMasterConflictResolutionTest.java | 31 +- .../cosmos/rx/MultiOrderByQueryTests.java | 45 +- .../azure/data/cosmos/rx/OfferQueryTest.java | 32 +- .../data/cosmos/rx/OfferReadReplaceTest.java | 18 +- .../cosmos/rx/OrderbyDocumentQueryTest.java | 70 +- .../cosmos/rx/ParallelDocumentQueryTest.java | 105 ++- .../data/cosmos/rx/PermissionCrudTest.java | 20 +- .../data/cosmos/rx/PermissionQueryTest.java | 32 +- .../azure/data/cosmos/rx/ProxyHostTest.java | 36 +- .../cosmos/rx/ReadFeedCollectionsTest.java | 26 +- .../data/cosmos/rx/ReadFeedDatabasesTest.java | 28 +- .../data/cosmos/rx/ReadFeedDocumentsTest.java | 12 +- .../rx/ReadFeedExceptionHandlingTest.java | 24 +- .../data/cosmos/rx/ReadFeedOffersTest.java | 24 +- .../cosmos/rx/ReadFeedPermissionsTest.java | 26 +- .../data/cosmos/rx/ReadFeedPkrTests.java | 21 +- .../rx/ReadFeedStoredProceduresTest.java | 28 +- .../data/cosmos/rx/ReadFeedTriggersTest.java | 28 +- .../data/cosmos/rx/ReadFeedUdfsTest.java | 28 +- .../data/cosmos/rx/ReadFeedUsersTest.java | 30 +- .../data/cosmos/rx/ResourceTokenTest.java | 29 +- .../cosmos/rx/SimpleSerializationTest.java | 11 +- .../rx/SinglePartitionDocumentQueryTest.java | 92 +-- .../SinglePartitionReadFeedDocumentsTest.java | 10 +- .../cosmos/rx/StoredProcedureCrudTest.java | 24 +- .../cosmos/rx/StoredProcedureQueryTest.java | 55 +- .../rx/StoredProcedureUpsertReplaceTest.java | 76 +- .../azure/data/cosmos/rx/TestSuiteBase.java | 164 ++--- .../data/cosmos/rx/TokenResolverTest.java | 16 +- .../azure/data/cosmos/rx/TopQueryTests.java | 50 +- .../azure/data/cosmos/rx/TriggerCrudTest.java | 22 +- .../data/cosmos/rx/TriggerQueryTest.java | 30 +- .../cosmos/rx/TriggerUpsertReplaceTest.java | 22 +- .../azure/data/cosmos/rx/UniqueIndexTest.java | 44 +- .../azure/data/cosmos/rx/UserCrudTest.java | 20 +- .../rx/UserDefinedFunctionCrudTest.java | 22 +- .../rx/UserDefinedFunctionQueryTest.java | 32 +- .../UserDefinedFunctionUpsertReplaceTest.java | 37 +- .../azure/data/cosmos/rx/UserQueryTest.java | 32 +- .../cosmos/rx/VeryLargeDocumentQueryTest.java | 37 +- .../rx/proxy/HttpProxyChannelInitializer.java | 7 +- .../rx/proxy/HttpProxyClientHandler.java | 5 +- .../rx/proxy/HttpProxyRemoteHandler.java | 5 +- .../data/cosmos/rx/proxy/HttpProxyServer.java | 5 +- 387 files changed, 6052 insertions(+), 5279 deletions(-) rename {gateway => commons}/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java (97%) create mode 100644 direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelHandler.java delete mode 100644 direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelInitializer.java create mode 100644 direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelPool.java create mode 100644 direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java create mode 100644 direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdEndpoint.java create mode 100644 direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdMetrics.java create mode 100644 direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdReporter.java create mode 100644 direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java create mode 100644 direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestTimer.java create mode 100644 direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java create mode 100644 examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java create mode 100644 sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java delete mode 100644 sdk/src/test/java/com/azure/data/cosmos/CosmosContainerCrudTest.java delete mode 100644 sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseCrudTest.java delete mode 100644 sdk/src/test/java/com/azure/data/cosmos/CosmosItemCrudTest.java delete mode 100644 sdk/src/test/java/com/azure/data/cosmos/CosmosTestSuiteBase.java create mode 100644 sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java diff --git a/benchmark/pom.xml b/benchmark/pom.xml index 0b482581f1873..0625c7d4c60ac 100644 --- a/benchmark/pom.xml +++ b/benchmark/pom.xml @@ -38,9 +38,6 @@ UTF-8 - 1.7.6 - 1.2.17 - 3.2.6 @@ -123,48 +120,15 @@ azure-cosmos-commons-test-utils - io.netty - netty-tcnative - 2.0.20.Final - linux-x86_64 + com.beust + jcommander + ${jcommander.version} com.google.guava guava ${guava.version} - - io.reactivex - rxjava-guava - 1.0.3 - - - org.mockito - mockito-core - ${mockito.version} - test - - - org.hamcrest - hamcrest-all - 1.3 - test - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - slf4j-log4j12 - ${slf4j.version} - - - log4j - log4j - ${log4j.version} - io.dropwizard.metrics metrics-core @@ -181,9 +145,20 @@ ${metrics.version} - com.beust - jcommander - 1.58 + io.netty + netty-tcnative + ${netty-tcnative.version} + linux-x86_64 + + + io.reactivex + rxjava-guava + ${rxjava-guava.version} + + + log4j + log4j + ${log4j.version} org.apache.commons @@ -191,10 +166,14 @@ ${commons-lang3.version} - org.testng - testng - ${testng.version} - test + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-log4j12 + ${slf4j.version} org.assertj @@ -203,9 +182,9 @@ test - org.mockito - mockito-all - ${mockito.version} + org.testng + testng + ${testng.version} test diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java index ade143a0eb03d..c6cc58fa2625b 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java @@ -23,6 +23,12 @@ package com.azure.data.cosmos.benchmark; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.benchmark.Configuration.Operation; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricFilter; @@ -34,12 +40,6 @@ import com.codahale.metrics.jvm.CachedThreadStatesGaugeSet; import com.codahale.metrics.jvm.GarbageCollectorMetricSet; import com.codahale.metrics.jvm.MemoryUsageGaugeSet; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.benchmark.Configuration.Operation; -import com.azure.data.cosmos.AsyncDocumentClient; import org.apache.commons.lang3.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java index 2974efeafeccf..7fef7ef37a2d0 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java @@ -23,18 +23,17 @@ package com.azure.data.cosmos.benchmark; -import java.util.Random; - import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.benchmark.Configuration.Operation; - import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; +import java.util.Random; + class AsyncQueryBenchmark extends AsyncBenchmark> { private int pageCount = 0; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java index db2bacdd97c68..5a7a3b703fdb0 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java @@ -27,7 +27,6 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; - import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java index 2a404cdc12891..128e7e895a67a 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java @@ -23,13 +23,12 @@ package com.azure.data.cosmos.benchmark; -import com.codahale.metrics.Timer; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.benchmark.Configuration.Operation; - +import com.codahale.metrics.Timer; import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java index bb1b7a8aa168d..e723b4f1a0aad 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java @@ -23,19 +23,17 @@ package com.azure.data.cosmos.benchmark; -import java.util.UUID; - -import org.apache.commons.lang3.RandomStringUtils; - -import com.codahale.metrics.Timer; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.benchmark.Configuration.Operation; - +import com.codahale.metrics.Timer; +import org.apache.commons.lang3.RandomStringUtils; import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; +import java.util.UUID; + class AsyncWriteBenchmark extends AsyncBenchmark> { private final String uuid; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java index f3349fed910f8..0a54017429e28 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java @@ -23,21 +23,20 @@ package com.azure.data.cosmos.benchmark; -import java.time.Duration; -import java.util.Arrays; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -import com.beust.jcommander.IStringConverter; -import com.beust.jcommander.Parameter; -import com.beust.jcommander.ParameterException; -import com.google.common.base.Strings; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.benchmark.Configuration.Operation.OperationTypeConverter; +import com.beust.jcommander.IStringConverter; +import com.beust.jcommander.Parameter; +import com.beust.jcommander.ParameterException; +import com.google.common.base.Strings; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import java.time.Duration; +import java.util.Arrays; class Configuration { private final static int GRAPHITE_SERVER_DEFAULT_PORT = 2003; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java index e9bed9328d8ce..99b6a71ee9f80 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java @@ -23,13 +23,13 @@ package com.azure.data.cosmos.benchmark; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.SqlParameter; import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.AsyncDocumentClient; class DocDBUtils { diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Main.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Main.java index 5a278b5313d7f..edd3969c89f6e 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Main.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Main.java @@ -23,11 +23,10 @@ package com.azure.data.cosmos.benchmark; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class Main { diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java index 10429923e094f..132ee238a2b3d 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java @@ -31,8 +31,8 @@ import com.azure.data.cosmos.SqlParameter; import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.Utils; import org.apache.commons.lang3.RandomUtils; import rx.Observable; import rx.Subscriber; diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java index 01b461f89360b..6e0580ddcc018 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java @@ -23,8 +23,8 @@ package com.azure.data.cosmos.benchmark; -import com.google.common.collect.ImmutableList; import com.azure.data.cosmos.SqlParameter; +import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java index 860e500019ff9..a7a744451fd72 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java @@ -23,8 +23,7 @@ package com.azure.data.cosmos.benchmark; -import com.beust.jcommander.JCommander; -import com.google.common.base.Strings; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.DataType; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; @@ -33,8 +32,9 @@ import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.rx.TestConfigurations; +import com.beust.jcommander.JCommander; +import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java index b96c97760a201..1bf1693183dc7 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java @@ -47,6 +47,7 @@ */ +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DatabaseForTest; @@ -55,7 +56,6 @@ import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.rx.TestConfigurations; import rx.Observable; diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java index dab4f32b6c412..8219238ec17ae 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.benchmark; -import com.beust.jcommander.JCommander; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.DataType; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; @@ -32,8 +32,8 @@ import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.rx.TestConfigurations; +import com.beust.jcommander.JCommander; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/commons-test-utils/pom.xml b/commons-test-utils/pom.xml index 52a5c8abfec48..3b1098b8325ae 100644 --- a/commons-test-utils/pom.xml +++ b/commons-test-utils/pom.xml @@ -22,8 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> - + 4.0.0 com.microsoft.azure @@ -112,43 +112,48 @@ SOFTWARE. azure-cosmos-commons - org.slf4j - slf4j-api - ${slf4j.version} + com.google.guava + guava + ${guava.version} - org.testng - testng - ${testng.version} + io.projectreactor + reactor-core + + + log4j + log4j + ${log4j.version} org.assertj assertj-core ${assertj.version} + + org.hamcrest + hamcrest-core + ${hamcrest.version} + org.mockito - mockito-all + mockito-core ${mockito.version} org.slf4j - slf4j-log4j12 + slf4j-api ${slf4j.version} - log4j - log4j - ${log4j.version} + org.slf4j + slf4j-log4j12 + ${slf4j.version} - - io.projectreactor - reactor-core - - com.google.guava - guava - ${guava.version} + org.testng + testng + ${testng.version} diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java index 76bdc3671a43a..2d2d1556a0712 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java @@ -25,8 +25,8 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Error; -import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import java.util.ArrayList; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java index 7deee6988b3ea..ede2b5b14ebfc 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java @@ -22,7 +22,14 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CompositePath; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.Resource; +import com.fasterxml.jackson.databind.node.ArrayNode; import java.time.Duration; import java.util.ArrayList; @@ -31,14 +38,7 @@ import java.util.Map; import java.util.stream.Collectors; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.BridgeInternal; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.azure.data.cosmos.CompositePath; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.QueryMetrics; -import com.azure.data.cosmos.Resource; +import static org.assertj.core.api.Assertions.assertThat; public interface FeedResponseListValidator { diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseValidator.java index 24465d3d6fb29..7aeec1e6680cd 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseValidator.java @@ -22,15 +22,15 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.HttpConstants; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.internal.HttpConstants; +import static org.assertj.core.api.Assertions.assertThat; public interface FeedResponseValidator { diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java index ea54984a7bfce..bfdf71c732766 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java @@ -22,19 +22,6 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.time.Instant; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; - -import org.assertj.core.api.Condition; - import com.azure.data.cosmos.Attachment; import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.DocumentCollection; @@ -45,12 +32,24 @@ import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.SpatialSpec; +import com.azure.data.cosmos.SpatialType; import com.azure.data.cosmos.StoredProcedure; import com.azure.data.cosmos.Trigger; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; import com.azure.data.cosmos.UserDefinedFunction; -import com.azure.data.cosmos.SpatialType; +import org.assertj.core.api.Condition; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; + +import static org.assertj.core.api.Assertions.assertThat; public interface ResourceResponseValidator { diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceValidator.java index 38c72309d5417..b5a927d58b293 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceValidator.java @@ -22,12 +22,12 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; +import com.azure.data.cosmos.Resource; import java.util.ArrayList; import java.util.List; -import com.azure.data.cosmos.Resource; +import static org.assertj.core.api.Assertions.assertThat; interface ResourceValidator { diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java index 0acb0438ef6db..744b154c575aa 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java @@ -22,9 +22,8 @@ */ package com.azure.data.cosmos.rx; -import org.apache.commons.lang3.StringUtils; - import com.google.common.base.Strings; +import org.apache.commons.lang3.StringUtils; /** * Contains the configurations for tests. diff --git a/commons/pom.xml b/commons/pom.xml index 82b0280ba0974..831a7e85676fc 100644 --- a/commons/pom.xml +++ b/commons/pom.xml @@ -191,12 +191,6 @@ SOFTWARE. ${assertj.version} test - - org.mockito - mockito-all - ${mockito.version} - test - org.slf4j slf4j-log4j12 diff --git a/commons/src/main/java/com/azure/data/cosmos/AccessCondition.java b/commons/src/main/java/com/azure/data/cosmos/AccessCondition.java index 93e79486db4f3..4ea7951980ce8 100644 --- a/commons/src/main/java/com/azure/data/cosmos/AccessCondition.java +++ b/commons/src/main/java/com/azure/data/cosmos/AccessCondition.java @@ -44,6 +44,7 @@ public AccessConditionType type() { * Sets the condition type. * * @param type the condition type to use. + * @return the Access Condition */ public AccessCondition type(AccessConditionType type) { this.type = type; @@ -65,6 +66,7 @@ public String condition() { * be compared to. * * @param condition the condition to use. + * @return the Access Condition */ public AccessCondition condition(String condition) { this.condition = condition; diff --git a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java index e883125bd9cec..6650b5a9f7a00 100644 --- a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java @@ -23,13 +23,13 @@ package com.azure.data.cosmos; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; -import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import java.net.URI; import java.util.Collection; diff --git a/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java b/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java index 9341a1279ae5c..3ee76d9d52103 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java @@ -71,6 +71,7 @@ public String partitionKeyRangeId() { * * @param partitionKeyRangeId a string indicating the partition key range ID * @see PartitionKeyRange + * @return the ChangeFeedOptions. */ public ChangeFeedOptions partitionKeyRangeId(String partitionKeyRangeId) { this.partitionKeyRangeId = partitionKeyRangeId; @@ -94,6 +95,7 @@ public boolean startFromBeginning() { * * @param startFromBeginning a boolean value indicating change feed should start * from beginning or not + * @return the ChangeFeedOptions. */ public ChangeFeedOptions startFromBeginning(boolean startFromBeginning) { this.startFromBeginning = startFromBeginning; @@ -115,6 +117,7 @@ public OffsetDateTime startDateTime() { * this is specified, startFromBeginning is ignored. * * @param startDateTime a zoned date time to start looking for changes after. + * @return the ChangeFeedOptions. */ public ChangeFeedOptions startDateTime(OffsetDateTime startDateTime) { this.startDateTime = startDateTime; diff --git a/commons/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java b/commons/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java index 96bfff7d5bea3..5a918bcfae9f1 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java +++ b/commons/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java @@ -22,6 +22,13 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.directconnectivity.StoreResult; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; +import org.apache.commons.lang3.StringUtils; + import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; @@ -37,13 +44,6 @@ import java.util.Map; import java.util.Set; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.Utils; -import com.azure.data.cosmos.directconnectivity.StoreResult; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import org.apache.commons.lang3.StringUtils; - public class ClientSideRequestStatistics { private final static int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; diff --git a/commons/src/main/java/com/azure/data/cosmos/CompositePath.java b/commons/src/main/java/com/azure/data/cosmos/CompositePath.java index 5b61db6640d63..d20e46b4128c1 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CompositePath.java +++ b/commons/src/main/java/com/azure/data/cosmos/CompositePath.java @@ -23,10 +23,8 @@ package com.azure.data.cosmos; -import org.apache.commons.lang3.StringUtils; - import com.azure.data.cosmos.internal.Constants; -import org.apache.commons.text.WordUtils; +import org.apache.commons.lang3.StringUtils; /** * Represents a composite path of the IndexingPolicy in the Azure Cosmos DB database service. @@ -64,6 +62,7 @@ public String path() { * Sets path. * * @param path the path. + * @return the CompositePath. */ public CompositePath path(String path) { super.set(Constants.Properties.PATH, path); @@ -98,6 +97,7 @@ public CompositePathSortOrder order() { * then you need to make the order for "/age" "ascending" and the order for "/height" "descending". * * @param order the sort order. + * @return the CompositePath. */ public CompositePath order(CompositePathSortOrder order) { super.set(Constants.Properties.ORDER, order.toString()); diff --git a/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java index 7f504fdea2990..769b976ffc65f 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java @@ -23,6 +23,9 @@ package com.azure.data.cosmos; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.WordUtils; + public enum ConflictResolutionMode { /** * Last writer wins conflict resolution mode @@ -48,6 +51,11 @@ public enum ConflictResolutionMode { /** * INVALID or unknown mode. */ - INVALID + INVALID; + + @Override + public String toString() { + return StringUtils.remove(WordUtils.capitalizeFully(this.name(), '_'), '_'); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java index 286bbd66b33f8..b02cd87ef8eaa 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java @@ -3,8 +3,6 @@ import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.Strings; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; /** @@ -149,7 +147,7 @@ public ConflictResolutionMode mode() { if (!Strings.isNullOrEmpty(strValue)) { try { - return ConflictResolutionMode.valueOf(StringUtils.upperCase(super.getString(Constants.Properties.MODE))); + return ConflictResolutionMode.valueOf(Strings.fromCamelCaseToUpperCase(super.getString(Constants.Properties.MODE))); } catch (IllegalArgumentException e) { this.getLogger().warn("INVALID ConflictResolutionMode value {}.", super.getString(Constants.Properties.MODE)); return ConflictResolutionMode.INVALID; @@ -166,7 +164,7 @@ public ConflictResolutionMode mode() { * @param mode One of the values of the {@link ConflictResolutionMode} enum. */ ConflictResolutionPolicy mode(ConflictResolutionMode mode) { - super.set(Constants.Properties.MODE, mode.name()); + super.set(Constants.Properties.MODE, mode.toString()); return this; } diff --git a/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java b/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java index 3e1ec68dbe8f2..a1fcc1e996992 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java @@ -97,6 +97,7 @@ public int requestTimeoutInMillis() { * milliseconds. The default is 60 seconds. * * @param requestTimeoutInMillis the request timeout in milliseconds. + * @return the ConnectionPolicy. */ public ConnectionPolicy requestTimeoutInMillis(int requestTimeoutInMillis) { this.requestTimeoutInMillis = requestTimeoutInMillis; @@ -116,6 +117,7 @@ public ConnectionMode connectionMode() { * Sets the connection mode used in the client. * * @param connectionMode the connection mode. + * @return the ConnectionPolicy. */ public ConnectionPolicy connectionMode(ConnectionMode connectionMode) { this.connectionMode = connectionMode; @@ -136,6 +138,7 @@ public int maxPoolSize() { * is 1000. * * @param maxPoolSize The value of the connection pool size. + * @return the ConnectionPolicy. */ public ConnectionPolicy maxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; @@ -157,6 +160,7 @@ public int idleConnectionTimeoutInMillis() { * the connection will be automatically closed. * * @param idleConnectionTimeoutInMillis the timeout for an idle connection in seconds. + * @return the ConnectionPolicy. */ public ConnectionPolicy idleConnectionTimeoutInMillis(int idleConnectionTimeoutInMillis) { this.idleConnectionTimeoutInMillis = idleConnectionTimeoutInMillis; @@ -177,6 +181,7 @@ public String userAgentSuffix() { * * @param userAgentSuffix The value to be appended to the user-agent header, this is * used for monitoring purposes. + * @return the ConnectionPolicy. */ public ConnectionPolicy userAgentSuffix(String userAgentSuffix) { this.userAgentSuffix = userAgentSuffix; @@ -201,6 +206,7 @@ public RetryOptions retryOptions() { * more details. * * @param retryOptions the RetryOptions instance. + * @return the ConnectionPolicy. */ public ConnectionPolicy retryOptions(RetryOptions retryOptions) { if (retryOptions == null) { @@ -230,6 +236,7 @@ public boolean enableEndpointDiscovery() { * The default value for this property is true indicating endpoint discovery is enabled. * * @param enableEndpointDiscovery true if EndpointDiscovery is enabled. + * @return the ConnectionPolicy. */ public ConnectionPolicy enableEndpointDiscovery(boolean enableEndpointDiscovery) { this.enableEndpointDiscovery = enableEndpointDiscovery; @@ -283,6 +290,7 @@ public Boolean enableReadRequestsFallback() { * first region in PreferredLocations property. * * @param usingMultipleWriteLocations flag to enable writes on any locations (regions) for geo-replicated database accounts. + * @return the ConnectionPolicy. */ public ConnectionPolicy usingMultipleWriteLocations(boolean usingMultipleWriteLocations) { this.usingMultipleWriteLocations = usingMultipleWriteLocations; @@ -300,6 +308,7 @@ public ConnectionPolicy usingMultipleWriteLocations(boolean usingMultipleWriteLo * 2. the Azure Cosmos DB account has more than one region * * @param enableReadRequestsFallback flag to enable reads to go to multiple regions configured on an account of Azure Cosmos DB service. + * @return the ConnectionPolicy. */ public ConnectionPolicy enableReadRequestsFallback(Boolean enableReadRequestsFallback) { this.enableReadRequestsFallback = enableReadRequestsFallback; @@ -326,6 +335,7 @@ public List preferredLocations() { * If EnableEndpointDiscovery is set to false, this property is ignored. * * @param preferredLocations the list of preferred locations. + * @return the ConnectionPolicy. */ public ConnectionPolicy preferredLocations(List preferredLocations) { this.preferredLocations = preferredLocations; @@ -346,6 +356,7 @@ public InetSocketAddress proxy() { * all the requests to cosmoDB will route from this address. * @param proxyHost The proxy server host. * @param proxyPort The proxy server port. + * @return the ConnectionPolicy. */ public ConnectionPolicy proxy(String proxyHost, int proxyPort) { this.inetSocketProxyAddress = new InetSocketAddress(proxyHost, proxyPort); diff --git a/commons/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java b/commons/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java index bafdb8803b952..e64a5ef9976ec 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java @@ -23,6 +23,9 @@ package com.azure.data.cosmos; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.WordUtils; + /** * Represents the consistency levels supported for Cosmos DB client operations in the Azure Cosmos DB database service. *

@@ -59,5 +62,10 @@ public enum ConsistencyLevel { * CONSISTENT_PREFIX Consistency guarantees that reads will return some prefix of all writes with no gaps. ALL writes * will be eventually be available for reads. */ - CONSISTENT_PREFIX + CONSISTENT_PREFIX; + + @Override + public String toString() { + return StringUtils.remove(WordUtils.capitalizeFully(this.name(), '_'), '_'); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java b/commons/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java index f034eb8babb80..5cd9be8db75c9 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java @@ -24,10 +24,8 @@ package com.azure.data.cosmos; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; - import com.azure.data.cosmos.internal.Constants; +import org.apache.commons.lang3.StringUtils; /** * Encapsulates the settings for consistency policy in the Azure Cosmos DB database service. @@ -77,9 +75,10 @@ public ConsistencyLevel getDefaultConsistencyLevel() { * Set the name of the resource. * * @param level the consistency level. + * @return the ConsistenctPolicy. */ public ConsistencyPolicy defaultConsistencyLevel(ConsistencyLevel level) { - super.set(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL, level.name()); + super.set(Constants.Properties.DEFAULT_CONSISTENCY_LEVEL, level.toString()); return this; } @@ -102,6 +101,7 @@ public int maxStalenessPrefix() { * (aka version). * * @param maxStalenessPrefix the max staleness prefix. + * @return the ConsistenctPolicy. */ public ConsistencyPolicy maxStalenessPrefix(int maxStalenessPrefix) { super.set(Constants.Properties.MAX_STALENESS_PREFIX, maxStalenessPrefix); @@ -125,6 +125,7 @@ public int maxStalenessIntervalInSeconds() { * Sets the in bounded staleness consistency, the maximum allowed staleness in terms time interval. * * @param maxStalenessIntervalInSeconds the max staleness interval in seconds. + * @return the ConsistenctPolicy. */ public ConsistencyPolicy maxStalenessIntervalInSeconds(int maxStalenessIntervalInSeconds) { super.set(Constants.Properties.MAX_STALENESS_INTERVAL_IN_SECONDS, maxStalenessIntervalInSeconds); diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java b/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java index 328d35d5b1db6..2d0aa6184d5f9 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java @@ -23,15 +23,14 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.HttpConstants; +import org.apache.commons.lang3.StringUtils; + import java.net.URI; import java.util.HashMap; import java.util.Map; -import org.apache.commons.lang3.StringUtils; - -import com.azure.data.cosmos.internal.Constants; -import com.azure.data.cosmos.internal.HttpConstants; - /** * This class defines a custom exception type for all operations on * DocumentClient in the Azure Cosmos DB database service. Applications are @@ -51,15 +50,23 @@ public class CosmosClientException extends Exception { private static final long serialVersionUID = 1L; - private Error error; private final int statusCode; private final Map responseHeaders; + private ClientSideRequestStatistics clientSideRequestStatistics; - String resourceAddress; - String partitionKeyRangeId; - URI requestUri; + private Error error; + long lsn; + String partitionKeyRangeId; Map requestHeaders; + URI requestUri; + String resourceAddress; + + private CosmosClientException(int statusCode, String message, Map responseHeaders, Throwable cause) { + super(message, cause, /* enableSuppression */ true, /* writableStackTrace */ false); + this.statusCode = statusCode; + this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); + } /** * Creates a new instance of the CosmosClientException class. @@ -67,8 +74,7 @@ public class CosmosClientException extends Exception { * @param statusCode the http status code of the response. */ public CosmosClientException(int statusCode) { - this.statusCode = statusCode; - this.responseHeaders = new HashMap<>(); + this(statusCode, null, null, null); } /** @@ -78,11 +84,9 @@ public CosmosClientException(int statusCode) { * @param errorMessage the error message. */ public CosmosClientException(int statusCode, String errorMessage) { - Error error = new Error(); + this(statusCode, errorMessage, null, null); + this.error = new Error(); error.set(Constants.Properties.MESSAGE, errorMessage); - this.statusCode = statusCode; - this.error = error; - this.responseHeaders = new HashMap<>(); } /** @@ -92,9 +96,7 @@ public CosmosClientException(int statusCode, String errorMessage) { * @param innerException the original exception. */ public CosmosClientException(int statusCode, Exception innerException) { - super(innerException); - this.statusCode = statusCode; - this.responseHeaders = new HashMap<>(); + this(statusCode, null, null, innerException); } /** @@ -105,27 +107,21 @@ public CosmosClientException(int statusCode, Exception innerException) { * @param responseHeaders the response headers. */ public CosmosClientException(int statusCode, Error errorResource, Map responseHeaders) { - this(null, statusCode, errorResource, responseHeaders); + this(/* resourceAddress */ null, statusCode, errorResource, responseHeaders); } /** * Creates a new instance of the CosmosClientException class. * - * @param resourceAddress the address of the resource the request is associated - * with. + * @param resourceAddress the address of the resource the request is associated with. * @param statusCode the http status code of the response. * @param errorResource the error resource object. * @param responseHeaders the response headers. */ - public CosmosClientException(String resourceAddress, int statusCode, Error errorResource, - Map responseHeaders) { - - super(errorResource == null ? null : errorResource.getMessage()); - - this.responseHeaders = safeResponseHeaders(responseHeaders); + public CosmosClientException(String resourceAddress, int statusCode, Error errorResource, Map responseHeaders) { + this(statusCode, errorResource == null ? null : errorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; - this.statusCode = statusCode; this.error = errorResource; } @@ -136,17 +132,11 @@ public CosmosClientException(String resourceAddress, int statusCode, Error error * @param statusCode the http status code of the response. * @param exception the exception object. * @param responseHeaders the response headers. - * @param resourceAddress the address of the resource the request is associated - * with. + * @param resourceAddress the address of the resource the request is associated with. */ - public CosmosClientException(String message, Exception exception, Map responseHeaders, - int statusCode, String resourceAddress) { - - super(message, exception); - - this.responseHeaders = safeResponseHeaders(responseHeaders); + public CosmosClientException(String message, Exception exception, Map responseHeaders, int statusCode, String resourceAddress) { + this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; - this.statusCode = statusCode; } @Override @@ -295,12 +285,4 @@ private String causeInfo() { } return null; } - - private Map safeResponseHeaders(Map map) { - if (map != null) { - return new HashMap<>(map); - } else { - return new HashMap<>(); - } - } } diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosContainerSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerSettings.java index 420c6ad1f79b8..675306a95f050 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosContainerSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerSettings.java @@ -100,6 +100,7 @@ public IndexingPolicy indexingPolicy() { * Sets the container's indexing policy * * @param indexingPolicy {@link IndexingPolicy} the indexing policy + * @return the CosmosContainerSettings. */ public CosmosContainerSettings indexingPolicy(IndexingPolicy indexingPolicy) { if (indexingPolicy == null) { @@ -133,6 +134,7 @@ public UniqueKeyPolicy uniqueKeyPolicy() { * Sets the Containers unique key policy * * @param uniqueKeyPolicy the unique key policy + * @return the CosmosContainerSettings. */ public CosmosContainerSettings uniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) { if (uniqueKeyPolicy == null) { @@ -166,6 +168,7 @@ public PartitionKeyDefinition partitionKey() { * Sets the containers's partition key definition. * * @param partitionKeyDefinition the partition key definition. + * @return the CosmosContainerSettings. */ public CosmosContainerSettings setPartitionKey(PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition == null) { @@ -191,6 +194,7 @@ public ConflictResolutionPolicy conflictResolutionPolicy() { * on documents in different regions, in a collection in the Azure Cosmos DB service. * * @param value ConflictResolutionPolicy to be used. + * @return the CosmosContainerSettings. */ public CosmosContainerSettings conflictResolutionPolicy(ConflictResolutionPolicy value) { if (value == null) { diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java b/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java index 162685273ed5e..5ade63c37d69e 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java @@ -22,8 +22,8 @@ */ package com.azure.data.cosmos; -import com.fasterxml.jackson.databind.ObjectMapper; import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.List; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java index 3b711d222d8fe..e633a6200bba2 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java @@ -68,6 +68,7 @@ public ConsistencyLevel consistencyLevel() { * Sets the consistency level required for the request. * * @param consistencyLevel the consistency level. + * @return the CosmosItemRequestOptions. */ public CosmosItemRequestOptions consistencyLevel(ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; @@ -87,6 +88,7 @@ public IndexingDirective indexingDirective() { * Sets the indexing directive (index, do not index etc). * * @param indexingDirective the indexing directive. + * @return the CosmosItemRequestOptions. */ public CosmosItemRequestOptions indexingDirective(IndexingDirective indexingDirective) { this.indexingDirective = indexingDirective; @@ -106,6 +108,7 @@ public List preTriggerInclude() { * Sets the triggers to be invoked before the operation. * * @param preTriggerInclude the triggers to be invoked before the operation. + * @return the CosmosItemRequestOptions. */ public CosmosItemRequestOptions preTriggerInclude(List preTriggerInclude) { this.preTriggerInclude = preTriggerInclude; @@ -125,6 +128,7 @@ public List postTriggerInclude() { * Sets the triggers to be invoked after the operation. * * @param postTriggerInclude the triggers to be invoked after the operation. + * @return the CosmosItemRequestOptions. */ public CosmosItemRequestOptions postTriggerInclude(List postTriggerInclude) { this.postTriggerInclude = postTriggerInclude; @@ -144,6 +148,7 @@ public String sessionToken() { * Sets the token for use with session consistency. * * @param sessionToken the session token. + * @return the CosmosItemRequestOptions. */ public CosmosItemRequestOptions sessionToken(String sessionToken) { this.sessionToken = sessionToken; @@ -153,6 +158,7 @@ public CosmosItemRequestOptions sessionToken(String sessionToken) { /** * Sets the partition key * @param partitionKey the partition key + * @return the CosmosItemRequestOptions. */ public CosmosItemRequestOptions partitionKey(PartitionKey partitionKey) { this.partitionKey = partitionKey; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java index 97b401dbab585..b8a29b4a60097 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java @@ -43,6 +43,7 @@ public ConsistencyLevel consistencyLevel() { * Sets the consistency level required for the request. * * @param consistencyLevel the consistency level. + * @return the CosmosStoredProcedureRequestOptions. */ public CosmosStoredProcedureRequestOptions consistencyLevel(ConsistencyLevel consistencyLevel) { this.consistencyLevel = consistencyLevel; @@ -62,6 +63,7 @@ public PartitionKey partitionKey() { * Sets the partition key used to identify the current request's target partition. * * @param partitionKey the partition key value. + * @return the CosmosStoredProcedureRequestOptions. */ public CosmosStoredProcedureRequestOptions partitionKey(PartitionKey partitionKey) { this.partitionKey = partitionKey; @@ -81,6 +83,7 @@ public String sessionToken() { * Sets the token for use with session consistency. * * @param sessionToken the session token. + * @return the CosmosStoredProcedureRequestOptions. */ public CosmosStoredProcedureRequestOptions sessionToken(String sessionToken) { this.sessionToken = sessionToken; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java index 9b091919d0ae7..7dd8123d89840 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java @@ -24,7 +24,6 @@ import com.azure.data.cosmos.internal.Constants; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; import java.util.List; import java.util.stream.Collectors; @@ -64,6 +63,7 @@ public String body() { * Set the body of the trigger. * * @param body the body of the trigger. + * @return the CosmosTriggerSettings. */ public CosmosTriggerSettings body(String body) { super.set(Constants.Properties.BODY, body); @@ -91,9 +91,10 @@ public TriggerType triggerType() { * Set the type of the resource. * * @param triggerType the trigger type. + * @return the CosmosTriggerSettings. */ public CosmosTriggerSettings triggerType(TriggerType triggerType) { - super.set(Constants.Properties.TRIGGER_TYPE, triggerType.name()); + super.set(Constants.Properties.TRIGGER_TYPE, triggerType.toString()); return this; } @@ -118,9 +119,10 @@ public TriggerOperation triggerOperation() { * Set the operation type of the trigger. * * @param triggerOperation the trigger operation. + * @return the CosmosTriggerSettings. */ public CosmosTriggerSettings triggerOperation(TriggerOperation triggerOperation) { - super.set(Constants.Properties.TRIGGER_OPERATION, triggerOperation.name()); + super.set(Constants.Properties.TRIGGER_OPERATION, triggerOperation.toString()); return this; } diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java index 4b5618af7f15c..c1bb0fee7db21 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java @@ -62,6 +62,7 @@ public String body() { * Set the body of the user defined function. * * @param body the body. + * @return the CosmosUserDefinedFunctionSettings. */ public CosmosUserDefinedFunctionSettings body(String body) { super.set(Constants.Properties.BODY, body); diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java index cbc7003a99c6d..096921243331d 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java @@ -1,10 +1,10 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Constants; + import java.util.List; import java.util.stream.Collectors; -import com.azure.data.cosmos.internal.Constants; - public class CosmosUserSettings extends Resource { /** * Initialize a user object. diff --git a/commons/src/main/java/com/azure/data/cosmos/DataType.java b/commons/src/main/java/com/azure/data/cosmos/DataType.java index d5a7a211ffd77..d2aed00eb006a 100644 --- a/commons/src/main/java/com/azure/data/cosmos/DataType.java +++ b/commons/src/main/java/com/azure/data/cosmos/DataType.java @@ -23,6 +23,9 @@ package com.azure.data.cosmos; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.WordUtils; + /** * Data types in the Azure Cosmos DB database service. */ @@ -55,5 +58,10 @@ public enum DataType { /** * Represent a multi-polygon data type. */ - MULTI_POLYGON + MULTI_POLYGON; + + @Override + public String toString() { + return StringUtils.remove(WordUtils.capitalizeFully(this.name(), '_'), '_'); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/Database.java b/commons/src/main/java/com/azure/data/cosmos/Database.java index cd9c47da17777..ab3c01d47dad5 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Database.java +++ b/commons/src/main/java/com/azure/data/cosmos/Database.java @@ -23,9 +23,8 @@ package com.azure.data.cosmos; -import org.apache.commons.lang3.StringUtils; - import com.azure.data.cosmos.internal.Constants; +import org.apache.commons.lang3.StringUtils; /** * Represents a Database in the Azure Cosmos DB database service. A database manages users, permissions and a set of collections diff --git a/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java b/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java index 7aba691ef7450..7d89e56a4a77e 100644 --- a/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java +++ b/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java @@ -23,17 +23,16 @@ package com.azure.data.cosmos; -import com.fasterxml.jackson.core.type.TypeReference; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.type.TypeReference; +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.util.HashMap; import java.util.Map; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.commons.lang3.StringUtils; - /** * Represents a database account in the Azure Cosmos DB database service. */ diff --git a/commons/src/main/java/com/azure/data/cosmos/Document.java b/commons/src/main/java/com/azure/data/cosmos/Document.java index cb6db23dda37d..d01a0e4e04cc1 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Document.java +++ b/commons/src/main/java/com/azure/data/cosmos/Document.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos; -import java.io.IOException; - -import com.fasterxml.jackson.databind.ObjectMapper; import com.azure.data.cosmos.internal.Constants; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; /** * Represents a document in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/azure/data/cosmos/Error.java b/commons/src/main/java/com/azure/data/cosmos/Error.java index 80480af7dba68..76610706b9915 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Error.java +++ b/commons/src/main/java/com/azure/data/cosmos/Error.java @@ -23,8 +23,8 @@ package com.azure.data.cosmos; -import com.fasterxml.jackson.databind.node.ObjectNode; import com.azure.data.cosmos.internal.Constants; +import com.fasterxml.jackson.databind.node.ObjectNode; /** * Encapsulates error related details in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/azure/data/cosmos/ExcludedPath.java b/commons/src/main/java/com/azure/data/cosmos/ExcludedPath.java index 0aa4a9edaf630..d30ccfe850337 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ExcludedPath.java +++ b/commons/src/main/java/com/azure/data/cosmos/ExcludedPath.java @@ -59,6 +59,7 @@ public String path() { * Sets path. * * @param path the path. + * @return the Exculded path. */ public ExcludedPath path(String path) { super.set(Constants.Properties.PATH, path); diff --git a/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java b/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java index 4a656f2182aeb..0cb65f51724c9 100644 --- a/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java @@ -66,6 +66,7 @@ public String partitionKeyRangeIdInternal() { * Sets the partitionKeyRangeId. * * @param partitionKeyRangeId the partitionKeyRangeId. + * @return the FeedOptions. */ public FeedOptions partitionKeyRangeIdInternal(String partitionKeyRangeId) { this.partitionKeyRangeId = partitionKeyRangeId; @@ -85,6 +86,7 @@ public String sessionToken() { * Sets the session token for use with session consistency. * * @param sessionToken the session token. + * @return the FeedOptions. */ public FeedOptions sessionToken(String sessionToken) { this.sessionToken = sessionToken; @@ -106,6 +108,7 @@ public Boolean enableScanInQuery() { * indexing was opted out on the requested paths. * * @param enableScanInQuery the option of enable scan in query. + * @return the FeedOptions. */ public FeedOptions enableScanInQuery(Boolean enableScanInQuery) { this.enableScanInQuery = enableScanInQuery; @@ -127,6 +130,7 @@ public Boolean emitVerboseTracesInQuery() { * investigation. * * @param emitVerboseTracesInQuery the emit verbose traces in query. + * @return the FeedOptions. */ public FeedOptions emitVerboseTracesInQuery(Boolean emitVerboseTracesInQuery) { this.emitVerboseTracesInQuery = emitVerboseTracesInQuery; @@ -150,6 +154,7 @@ public Boolean enableCrossPartitionQuery() { * * @param enableCrossPartitionQuery whether to allow queries to run across all * partitions of the collection. + * @return the FeedOptions. */ public FeedOptions enableCrossPartitionQuery(Boolean enableCrossPartitionQuery) { this.enableCrossPartitionQuery = enableCrossPartitionQuery; @@ -172,6 +177,7 @@ public int maxDegreeOfParallelism() { * query execution. * * @param maxDegreeOfParallelism number of concurrent operations. + * @return the FeedOptions. */ public FeedOptions maxDegreeOfParallelism(int maxDegreeOfParallelism) { this.maxDegreeOfParallelism = maxDegreeOfParallelism; @@ -194,6 +200,7 @@ public int maxBufferedItemCount() { * parallel query execution. * * @param maxBufferedItemCount maximum number of items. + * @return the FeedOptions. */ public FeedOptions maxBufferedItemCount(int maxBufferedItemCount) { this.maxBufferedItemCount = maxBufferedItemCount; @@ -218,6 +225,7 @@ public FeedOptions maxBufferedItemCount(int maxBufferedItemCount) { * size. * * @param limitInKb continuation token size limit. + * @return the FeedOptions. */ public FeedOptions responseContinuationTokenLimitInKb(int limitInKb) { this.responseContinuationTokenLimitInKb = limitInKb; diff --git a/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java b/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java index 304b7c32b236a..63d9f3ac59d8f 100644 --- a/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java +++ b/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java @@ -59,6 +59,7 @@ public Integer maxItemCount() { * operation. * * @param maxItemCount the max number of items. + * @return the FeedOptionsBase. */ public FeedOptionsBase maxItemCount(Integer maxItemCount) { this.maxItemCount = maxItemCount; @@ -79,6 +80,7 @@ public String requestContinuation() { * * @param requestContinuation * the request continuation. + * @return the FeedOptionsBase. */ public FeedOptionsBase requestContinuation(String requestContinuation) { this.requestContinuation = requestContinuation; @@ -101,6 +103,7 @@ public PartitionKey partitionKey() { * * @param partitionkey * the partition key value. + * @return the FeedOptionsBase. */ public FeedOptionsBase partitionKey(PartitionKey partitionkey) { this.partitionkey = partitionkey; @@ -118,6 +121,7 @@ public boolean populateQueryMetrics() { /** * Sets the option to enable/disable getting metrics relating to query execution on document query requests * @param populateQueryMetrics whether to enable or disable query metrics + * @return the FeedOptionsBase. */ public FeedOptionsBase populateQueryMetrics(boolean populateQueryMetrics) { this.populateQueryMetrics = populateQueryMetrics; @@ -137,6 +141,7 @@ public Map properties() { * Sets the properties used to identify the request token. * * @param properties the properties. + * @return the FeedOptionsBase. */ public FeedOptionsBase properties(Map properties) { this.properties = properties; diff --git a/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java b/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java index 38b17e5a8c5c8..ecbb7ca536314 100644 --- a/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java @@ -23,17 +23,16 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.HttpConstants; +import org.apache.commons.lang3.StringUtils; + import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import org.apache.commons.lang3.StringUtils; - -import com.azure.data.cosmos.internal.Constants; -import com.azure.data.cosmos.internal.HttpConstants; - public class FeedResponse { private final List results; diff --git a/commons/src/main/java/com/azure/data/cosmos/HashIndex.java b/commons/src/main/java/com/azure/data/cosmos/HashIndex.java index 791146bd7d0ed..5c2936a9e0cb6 100644 --- a/commons/src/main/java/com/azure/data/cosmos/HashIndex.java +++ b/commons/src/main/java/com/azure/data/cosmos/HashIndex.java @@ -23,10 +23,8 @@ package com.azure.data.cosmos; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; - import com.azure.data.cosmos.internal.Constants; +import org.apache.commons.lang3.StringUtils; /** * Represents a hash index in the Azure Cosmos DB database service. @@ -105,9 +103,10 @@ public DataType dataType() { * Sets data type. * * @param dataType the data type. + * @return the Hash Index. */ public HashIndex dataType(DataType dataType) { - super.set(Constants.Properties.DATA_TYPE, dataType.name()); + super.set(Constants.Properties.DATA_TYPE, dataType.toString()); return this; } @@ -124,6 +123,7 @@ public int precision() { * Sets precision. * * @param precision the precision. + * @return the Hash Index. */ public HashIndex precision(int precision) { super.set(Constants.Properties.PRECISION, precision); diff --git a/commons/src/main/java/com/azure/data/cosmos/IncludedPath.java b/commons/src/main/java/com/azure/data/cosmos/IncludedPath.java index 0ff05623e8d0d..b18424cf89990 100644 --- a/commons/src/main/java/com/azure/data/cosmos/IncludedPath.java +++ b/commons/src/main/java/com/azure/data/cosmos/IncludedPath.java @@ -23,15 +23,13 @@ package com.azure.data.cosmos; -import java.util.ArrayList; -import java.util.Collection; - +import com.azure.data.cosmos.internal.Constants; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; -import com.azure.data.cosmos.internal.Constants; +import java.util.ArrayList; +import java.util.Collection; /** * Represents an included path of the IndexingPolicy in the Azure Cosmos DB database service. @@ -69,6 +67,7 @@ public String path() { * Sets path. * * @param path the path. + * @return the Included Path. */ public IncludedPath path(String path) { super.set(Constants.Properties.PATH, path); diff --git a/commons/src/main/java/com/azure/data/cosmos/Index.java b/commons/src/main/java/com/azure/data/cosmos/Index.java index de6d8ac14915d..1a23a508e4d97 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Index.java +++ b/commons/src/main/java/com/azure/data/cosmos/Index.java @@ -23,10 +23,8 @@ package com.azure.data.cosmos; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; - import com.azure.data.cosmos.internal.Constants; +import org.apache.commons.lang3.StringUtils; /** * Represents the index of a collection in the Azure Cosmos DB database service. @@ -162,7 +160,7 @@ public IndexKind kind() { * @param indexKind the index kind. */ private Index kind(IndexKind indexKind) { - super.set(Constants.Properties.INDEX_KIND, indexKind.name()); + super.set(Constants.Properties.INDEX_KIND, indexKind.toString()); return this; } } diff --git a/commons/src/main/java/com/azure/data/cosmos/IndexKind.java b/commons/src/main/java/com/azure/data/cosmos/IndexKind.java index 8c2139103deab..cea3ec493419b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/IndexKind.java +++ b/commons/src/main/java/com/azure/data/cosmos/IndexKind.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import org.apache.commons.text.WordUtils; + /** * These are the indexing types available for indexing a path in the Azure Cosmos DB database service. * For additional details, refer to @@ -40,5 +42,10 @@ public enum IndexKind { // The index entries are indexed to serve spatial queries like below: // SELECT * FROM Root r WHERE ST_DISTANCE({"type":"POINT","coordinates":[71.0589,42.3601]}, r.location) $LE 10000 - SPATIAL + SPATIAL; + + @Override + public String toString() { + return WordUtils.capitalizeFully(this.name()); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/IndexingDirective.java b/commons/src/main/java/com/azure/data/cosmos/IndexingDirective.java index cdec2ce598d17..3e692aa840225 100644 --- a/commons/src/main/java/com/azure/data/cosmos/IndexingDirective.java +++ b/commons/src/main/java/com/azure/data/cosmos/IndexingDirective.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import org.apache.commons.text.WordUtils; + /** * Specifies whether or not the resource is to be indexed in the Azure Cosmos DB database service. */ @@ -41,5 +43,10 @@ public enum IndexingDirective { /** * Do not index the resource. */ - EXCLUDE + EXCLUDE; + + @Override + public String toString() { + return WordUtils.capitalizeFully(this.name()); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/IndexingMode.java b/commons/src/main/java/com/azure/data/cosmos/IndexingMode.java index b11d01b94247a..e745eab1c68e3 100644 --- a/commons/src/main/java/com/azure/data/cosmos/IndexingMode.java +++ b/commons/src/main/java/com/azure/data/cosmos/IndexingMode.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import org.apache.commons.text.WordUtils; + /** * Specifies the supported indexing modes in the Azure Cosmos DB database service. */ @@ -49,5 +51,10 @@ public enum IndexingMode { * collection, to save the storage cost or improve the write throughput. Your queries will degenerate to scans of * the entire collection. */ - NONE + NONE; + + @Override + public String toString() { + return WordUtils.capitalizeFully(this.name()); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java b/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java index f75a217c412a9..863ce0b5d13fd 100644 --- a/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java @@ -23,10 +23,9 @@ package com.azure.data.cosmos; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.azure.data.cosmos.internal.Constants; +import com.fasterxml.jackson.databind.node.ArrayNode; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; import java.util.ArrayList; import java.util.Arrays; @@ -119,6 +118,7 @@ public Boolean automatic() { * indexing, documents can be explicitly included. * * @param automatic the automatic + * @return the Indexing Policy. */ public IndexingPolicy automatic(boolean automatic) { super.set(Constants.Properties.AUTOMATIC, automatic); @@ -144,9 +144,10 @@ public IndexingMode indexingMode() { * Sets the indexing mode (consistent or lazy). * * @param indexingMode the indexing mode. + * @return the Indexing Policy. */ public IndexingPolicy indexingMode(IndexingMode indexingMode) { - super.set(Constants.Properties.INDEXING_MODE, indexingMode.name()); + super.set(Constants.Properties.INDEXING_MODE, indexingMode.toString()); return this; } @@ -220,6 +221,7 @@ public Collection> compositeIndexes() { * Sets the composite indexes for additional indexes. * * @param compositeIndexes the composite indexes. + * @return the Indexing Policy. */ public IndexingPolicy compositeIndexes(Collection> compositeIndexes) { this.compositeIndexes = compositeIndexes; @@ -248,6 +250,7 @@ public Collection spatialIndexes() { * Sets the spatial indexes for additional indexes. * * @param spatialIndexes the spatial indexes. + * @return the Indexing Policy. */ public IndexingPolicy spatialIndexes(Collection spatialIndexes) { this.spatialIndexes = spatialIndexes; diff --git a/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java b/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java index 3fedeb3f80c9d..8beb2518625d9 100644 --- a/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java +++ b/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java @@ -23,21 +23,25 @@ package com.azure.data.cosmos; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; -import java.util.*; - +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.Utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.azure.data.cosmos.internal.Utils; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; /** * Represents a base resource that can be serialized to JSON in the Azure Cosmos DB database service. @@ -283,9 +287,11 @@ public Double getDouble(String propertyName) { * @param propertyName the property to get. * @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local) * and a static one. + * @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case separated by underscore, + * before converting to required class. * @return the object value. */ - public T getObject(String propertyName, Class c) { + public T getObject(String propertyName, Class c, boolean ... convertFromCamelCase) { if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) { JsonNode jsonObj = propertyBag.get(propertyName); if (Number.class.isAssignableFrom(c) || String.class.isAssignableFrom(c) @@ -294,7 +300,9 @@ public T getObject(String propertyName, Class c) { return c.cast(getValue(jsonObj)); } else if (Enum.class.isAssignableFrom(c)) { try { - return c.cast(c.getMethod("valueOf", String.class).invoke(null, String.class.cast(getValue(jsonObj)))); + String value = String.class.cast(getValue(jsonObj)); + value = convertFromCamelCase.length > 0 && convertFromCamelCase[0] ? Strings.fromCamelCaseToUpperCase(value) : value; + return c.cast(c.getMethod("valueOf", String.class).invoke(null, value)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException("Failed to create enum.", e); @@ -327,9 +335,11 @@ public T getObject(String propertyName, Class c) { * @param propertyName the property to get * @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local) * and a static one. + * @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case separated by underscore, + * before converting to required class. * @return the object collection. */ - public List getList(String propertyName, Class c) { + public List getList(String propertyName, Class c, boolean ... convertFromCamelCase) { if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) { ArrayNode jsonArray = (ArrayNode) this.propertyBag.get(propertyName); ArrayList result = new ArrayList(); @@ -356,8 +366,9 @@ public List getList(String propertyName, Class c) { result.add(c.cast(getValue(n))); } else if (isEnumClass) { try { - result.add(c.cast(c.getMethod("valueOf", String.class).invoke(null, - String.class.cast(getValue(n))))); + String value = String.class.cast(getValue(n)); + value = convertFromCamelCase.length > 0 && convertFromCamelCase[0] ? Strings.fromCamelCaseToUpperCase(value) : value; + result.add(c.cast(c.getMethod("valueOf", String.class).invoke(null, value))); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException("Failed to create enum.", e); @@ -391,10 +402,12 @@ public List getList(String propertyName, Class c) { * @param propertyName the property to get * @param c the class of the object. If c is a POJO class, it must be a member (and not an anonymous or local) * and a static one. + * @param convertFromCamelCase boolean indicating if String should be converted from camel case to upper case separated by underscore, + * before converting to required class. * @return the object collection. */ - public Collection getCollection(String propertyName, Class c) { - return getList(propertyName, c); + public Collection getCollection(String propertyName, Class c, boolean ... convertFromCamelCase) { + return getList(propertyName, c, convertFromCamelCase); } /** diff --git a/commons/src/main/java/com/azure/data/cosmos/MediaResponse.java b/commons/src/main/java/com/azure/data/cosmos/MediaResponse.java index 4d4aa5c0731c0..fa9202c4ddc31 100644 --- a/commons/src/main/java/com/azure/data/cosmos/MediaResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/MediaResponse.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; + import java.io.BufferedInputStream; import java.io.InputStream; import java.util.Map; -import com.azure.data.cosmos.internal.RxDocumentServiceResponse; - /** * Response associated with retrieving attachment content in the Azure Cosmos DB database service. */ diff --git a/commons/src/main/java/com/azure/data/cosmos/Offer.java b/commons/src/main/java/com/azure/data/cosmos/Offer.java index 3b6cf550e497a..5ec5a7ee39ba0 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Offer.java +++ b/commons/src/main/java/com/azure/data/cosmos/Offer.java @@ -23,10 +23,9 @@ package com.azure.data.cosmos; -import com.fasterxml.jackson.databind.node.ObjectNode; - import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.databind.node.ObjectNode; /** * Represents an offer in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java index bcdce13fd18f9..df3cf998c9791 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java +++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java @@ -23,8 +23,8 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; /** * Represents a partition key value in the Azure Cosmos DB database service. A diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java index 27530f1a1172a..90adb0df636d3 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java +++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java @@ -24,15 +24,13 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Constants; -import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; - /** * Represents a partition key definition in the Azure Cosmos DB database service. A partition key definition specifies which * document property is used as the partition key in a collection that has multiple partitions. @@ -67,7 +65,7 @@ public PartitionKeyDefinition(String jsonString) { */ public PartitionKind kind() { if (this.kind == null) { - this.kind = super.getObject(Constants.Properties.PARTITION_KIND, PartitionKind.class); + this.kind = super.getObject(Constants.Properties.PARTITION_KIND, PartitionKind.class, true); } return this.kind; @@ -77,6 +75,7 @@ public PartitionKind kind() { * Sets the partition algorithm used to calculate the partition id given a partition key. * * @param kind the partition algorithm. + * @return this PartitionKeyDefinition. */ public PartitionKeyDefinition kind(PartitionKind kind) { this.kind = kind; @@ -129,6 +128,7 @@ public List paths() { * Sets the document property paths for the partition key. * * @param paths the paths to document properties that form the partition key. + * @return this PartitionKeyDefinition. */ public PartitionKeyDefinition paths(List paths) { if (paths == null || paths.size() == 0) { @@ -167,14 +167,14 @@ PartitionKeyInternal getNonePartitionKeyValue() { @Override void populatePropertyBag() { if (this.kind != null) { - super.set(Constants.Properties.PARTITION_KIND, kind.name()); + super.set(Constants.Properties.PARTITION_KIND, kind.toString()); } if (this.paths != null) { super.set(Constants.Properties.PARTITION_KEY_PATHS, paths); } if (this.version != null) { - super.set(Constants.Properties.PARTITION_KEY_DEFINITION_VERSION, version.name()); + super.set(Constants.Properties.PARTITION_KEY_DEFINITION_VERSION, version.toString()); } super.populatePropertyBag(); } diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java index 44479d7acfe60..5b065f72ac93b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java +++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos; -import java.util.List; - import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.routing.Range; +import java.util.List; + /** * Represent a partition key range in the Azure Cosmos DB database service. */ diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKind.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKind.java index 1871e158ec7cd..62aac4aa3fcd1 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionKind.java +++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKind.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import org.apache.commons.text.WordUtils; + /** * Specifies the partition scheme for an multiple-partitioned collection in the Azure Cosmos DB database service. */ @@ -30,5 +32,10 @@ public enum PartitionKind { /** * The Partition of a document is calculated based on the hash value of the PartitionKey. */ - HASH + HASH; + + @Override + public String toString() { + return WordUtils.capitalizeFully(this.name()); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/Permission.java b/commons/src/main/java/com/azure/data/cosmos/Permission.java index 9b98a0f036894..d62aea6ba728d 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Permission.java +++ b/commons/src/main/java/com/azure/data/cosmos/Permission.java @@ -23,11 +23,9 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Constants; import com.fasterxml.jackson.databind.node.ArrayNode; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; - -import com.azure.data.cosmos.internal.Constants; /** * Represents a per-User Permission to access a specific resource e.g. Document or Collection in the Azure Cosmos DB database service. @@ -84,7 +82,7 @@ public PermissionMode getPermissionMode() { */ public void setPermissionMode(PermissionMode permissionMode) { this.set(Constants.Properties.PERMISSION_MODE, - permissionMode.name().toLowerCase()); + permissionMode.toString().toLowerCase()); } /** diff --git a/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java b/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java index f6369560337dd..6c9cd7bef86bf 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java +++ b/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java @@ -23,6 +23,9 @@ package com.azure.data.cosmos; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.WordUtils; + /** * Enumeration specifying applicability of permission in the Azure Cosmos DB database service. */ @@ -51,4 +54,9 @@ public enum PermissionMode { public int getValue() { return value; } + + @Override + public String toString() { + return WordUtils.capitalizeFully(this.name()); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java b/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java index 742ed958e735a..ca295e247ec04 100644 --- a/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java +++ b/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java @@ -23,10 +23,8 @@ package com.azure.data.cosmos; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; - import com.azure.data.cosmos.internal.Constants; +import org.apache.commons.lang3.StringUtils; /** * Represents a range index in the Azure Cosmos DB database service. @@ -101,9 +99,10 @@ public DataType dataType() { * Sets data type. * * @param dataType the data type. + * @return the RangeIndex. */ public RangeIndex dataType(DataType dataType) { - super.set(Constants.Properties.DATA_TYPE, dataType.name()); + super.set(Constants.Properties.DATA_TYPE, dataType.toString()); return this; } @@ -120,6 +119,7 @@ public int precision() { * Sets precision. * * @param precision the precision. + * @return the RangeIndex. */ public RangeIndex precision(int precision) { super.set(Constants.Properties.PRECISION, precision); diff --git a/commons/src/main/java/com/azure/data/cosmos/Resource.java b/commons/src/main/java/com/azure/data/cosmos/Resource.java index 1f90025ffef98..e8ea3e1bc173c 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Resource.java +++ b/commons/src/main/java/com/azure/data/cosmos/Resource.java @@ -23,14 +23,14 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Constants; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.azure.data.cosmos.internal.Constants; - /** * Represents the base resource in the Azure Cosmos DB database service. */ @@ -101,6 +101,7 @@ public String id() { * Sets the name of the resource. * * @param id the name of the resource. + * @return the resource. */ public Resource id(String id) { super.set(Constants.Properties.ID, id); @@ -121,6 +122,7 @@ public String resourceId() { * Set the ID associated with the resource. * * @param resourceId the ID associated with the resource. + * @return the resource. */ public Resource resourceId(String resourceId) { super.set(Constants.Properties.R_ID, resourceId); diff --git a/commons/src/main/java/com/azure/data/cosmos/ResourceResponse.java b/commons/src/main/java/com/azure/data/cosmos/ResourceResponse.java index c4769a675ef20..ef354f0fa67b0 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ResourceResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/ResourceResponse.java @@ -23,15 +23,14 @@ package com.azure.data.cosmos; -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import org.apache.commons.lang3.StringUtils; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; /** * Represents the service response to a request made from DocumentClient in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/azure/data/cosmos/RetryOptions.java b/commons/src/main/java/com/azure/data/cosmos/RetryOptions.java index bb9ec32572d33..e560f03dc2195 100644 --- a/commons/src/main/java/com/azure/data/cosmos/RetryOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/RetryOptions.java @@ -65,6 +65,7 @@ public int maxRetryAttemptsOnThrottledRequests() { * * @param maxRetryAttemptsOnThrottledRequests the max number of retry attempts on failed requests due to a * throttle error. + * @return the RetryOptions. */ public RetryOptions maxRetryAttemptsOnThrottledRequests(int maxRetryAttemptsOnThrottledRequests) { if (maxRetryAttemptsOnThrottledRequests < 0) { @@ -97,6 +98,7 @@ public int maxRetryWaitTimeInSeconds() { * The default value is 30 seconds. * * @param maxRetryWaitTimeInSeconds the maximum number of seconds a request will be retried. + * @return the RetryOptions. */ public RetryOptions maxRetryWaitTimeInSeconds(int maxRetryWaitTimeInSeconds) { if (maxRetryWaitTimeInSeconds < 0 || maxRetryWaitTimeInSeconds > Integer.MAX_VALUE / 1000) { diff --git a/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java b/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java index f710156705554..31a37369c8b4a 100644 --- a/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java +++ b/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java @@ -23,10 +23,8 @@ package com.azure.data.cosmos; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; - import com.azure.data.cosmos.internal.Constants; +import org.apache.commons.lang3.StringUtils; /** * Represents a spatial index in the Azure Cosmos DB database service. @@ -83,9 +81,10 @@ public DataType dataType() { * Sets data type. * * @param dataType the data type. + * @return the SpatialIndex. */ public SpatialIndex dataType(DataType dataType) { - super.set(Constants.Properties.DATA_TYPE, dataType.name()); + super.set(Constants.Properties.DATA_TYPE, dataType.toString()); return this; } } diff --git a/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java b/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java index abbc9de262b52..a3a7be4699673 100644 --- a/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java +++ b/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Constants; + import java.util.ArrayList; import java.util.Collection; -import com.azure.data.cosmos.internal.Constants; - public class SpatialSpec extends JsonSerializable { private Collection spatialTypes; @@ -62,6 +62,7 @@ public String path() { * Sets path. * * @param path the path. + * @return the SpatialSpec. */ public SpatialSpec path(String path) { super.set(Constants.Properties.PATH, path); @@ -75,7 +76,7 @@ public SpatialSpec path(String path) { */ public Collection spatialTypes() { if (this.spatialTypes == null) { - this.spatialTypes = super.getCollection(Constants.Properties.TYPES, SpatialType.class); + this.spatialTypes = super.getCollection(Constants.Properties.TYPES, SpatialType.class, true); if (this.spatialTypes == null) { this.spatialTypes = new ArrayList(); @@ -89,12 +90,13 @@ public Collection spatialTypes() { * Sets the collection of spatial types. * * @param spatialTypes the collection of spatial types. + * @return the SpatialSpec. */ public SpatialSpec spatialTypes(Collection spatialTypes) { this.spatialTypes = spatialTypes; Collection spatialTypeNames = new ArrayList(); for (SpatialType spatialType : this.spatialTypes) { - spatialTypeNames.add(spatialType.name()); + spatialTypeNames.add(spatialType.toString()); } super.set(Constants.Properties.TYPES, spatialTypeNames); return this; diff --git a/commons/src/main/java/com/azure/data/cosmos/SpatialType.java b/commons/src/main/java/com/azure/data/cosmos/SpatialType.java index 06e49d72e2649..cd53b197c4378 100644 --- a/commons/src/main/java/com/azure/data/cosmos/SpatialType.java +++ b/commons/src/main/java/com/azure/data/cosmos/SpatialType.java @@ -23,6 +23,9 @@ package com.azure.data.cosmos; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.WordUtils; + /** * Defines the target data type of an index path specification in the Azure Cosmos DB service. * @@ -46,6 +49,11 @@ public enum SpatialType { /** * Represent a multi-polygon data type. */ - MULTI_POLYGON + MULTI_POLYGON; + + @Override + public String toString() { + return StringUtils.remove(WordUtils.capitalizeFully(this.name(), '_'), '_'); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/SqlParameter.java b/commons/src/main/java/com/azure/data/cosmos/SqlParameter.java index e8aa7bb73a27e..e5da14d40a873 100644 --- a/commons/src/main/java/com/azure/data/cosmos/SqlParameter.java +++ b/commons/src/main/java/com/azure/data/cosmos/SqlParameter.java @@ -61,6 +61,7 @@ public String name() { * Sets the name of the parameter. * * @param name the name of the parameter. + * @return the SqlParameter. */ public SqlParameter name(String name) { super.set("name", name); @@ -82,6 +83,7 @@ public Object value(Class c) { * Sets the value of the parameter. * * @param value the value of the parameter. + * @return the SqlParameter. */ public SqlParameter value(Object value) { super.set("value", value); diff --git a/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java b/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java index 556e85df77935..85dfa4d027dc7 100644 --- a/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java +++ b/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java @@ -79,6 +79,7 @@ public String queryText() { * * @param queryText * the query text. + * @return the SqlQuerySpec. */ public SqlQuerySpec queryText(String queryText) { super.set("query", queryText); @@ -108,6 +109,7 @@ public SqlParameterCollection parameters() { * * @param parameters * the query parameters. + * @return the SqlQuerySpec. */ public SqlQuerySpec parameters(SqlParameterCollection parameters) { this.parameters = parameters; diff --git a/commons/src/main/java/com/azure/data/cosmos/StoredProcedureResponse.java b/commons/src/main/java/com/azure/data/cosmos/StoredProcedureResponse.java index 01c3e4ff225b7..903aa1d3f3597 100644 --- a/commons/src/main/java/com/azure/data/cosmos/StoredProcedureResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/StoredProcedureResponse.java @@ -23,13 +23,12 @@ package com.azure.data.cosmos; -import java.util.Map; - +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import java.util.Map; /** * Represents the response returned from a stored procedure in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/azure/data/cosmos/Trigger.java b/commons/src/main/java/com/azure/data/cosmos/Trigger.java index 4a92e07454f38..4cc3ebe42433d 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Trigger.java +++ b/commons/src/main/java/com/azure/data/cosmos/Trigger.java @@ -23,9 +23,8 @@ package com.azure.data.cosmos; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; import com.azure.data.cosmos.internal.Constants; +import org.apache.commons.lang3.StringUtils; /** * Represents a trigger in the Azure Cosmos DB database service. @@ -92,7 +91,7 @@ public TriggerType getTriggerType() { * @param triggerType the trigger type. */ public void setTriggerType(TriggerType triggerType) { - super.set(Constants.Properties.TRIGGER_TYPE, triggerType.name()); + super.set(Constants.Properties.TRIGGER_TYPE, triggerType.toString()); } /** @@ -118,6 +117,6 @@ public TriggerOperation getTriggerOperation() { * @param triggerOperation the trigger operation. */ public void setTriggerOperation(TriggerOperation triggerOperation) { - super.set(Constants.Properties.TRIGGER_OPERATION, triggerOperation.name()); + super.set(Constants.Properties.TRIGGER_OPERATION, triggerOperation.toString()); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/TriggerOperation.java b/commons/src/main/java/com/azure/data/cosmos/TriggerOperation.java index ea2dd535d5593..e7d624655db0f 100644 --- a/commons/src/main/java/com/azure/data/cosmos/TriggerOperation.java +++ b/commons/src/main/java/com/azure/data/cosmos/TriggerOperation.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import org.apache.commons.text.WordUtils; + /** * Specifies the operations on which a trigger should be executed in the Azure Cosmos DB database service. */ @@ -66,4 +68,9 @@ public enum TriggerOperation { public int getValue() { return value; } + + @Override + public String toString() { + return WordUtils.capitalizeFully(this.name()); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/TriggerType.java b/commons/src/main/java/com/azure/data/cosmos/TriggerType.java index 60ad25f4ccc5f..9717d7a01ab7b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/TriggerType.java +++ b/commons/src/main/java/com/azure/data/cosmos/TriggerType.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import org.apache.commons.text.WordUtils; + /** * The trigger type in the Azure Cosmos DB database service. */ @@ -51,4 +53,9 @@ public enum TriggerType { public int getValue() { return value; } + + @Override + public String toString() { + return WordUtils.capitalizeFully(this.name()); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java b/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java index 658fd4f701cbf..d1159cc315957 100644 --- a/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java +++ b/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java @@ -22,11 +22,11 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Constants; + import java.util.ArrayList; import java.util.Collection; -import com.azure.data.cosmos.internal.Constants; - /** * Represents a unique key on that enforces uniqueness constraint on documents in the collection in the Azure Cosmos DB service. * @@ -74,6 +74,7 @@ public Collection paths() { * such as "/name/first". * * @param paths the unique paths. + * @return the Unique Key. */ public UniqueKey paths(Collection paths) { this.paths = paths; diff --git a/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java b/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java index 8c5ae6d803d3f..20a160be66211 100644 --- a/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java @@ -22,11 +22,11 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Constants; + import java.util.ArrayList; import java.util.Collection; -import com.azure.data.cosmos.internal.Constants; - /** * Represents the unique key policy configuration for specifying uniqueness constraints on documents in the * collection in the Azure Cosmos DB service. diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/AddressInformation.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/AddressInformation.java index 642bdfe24186c..606288ca2072c 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/AddressInformation.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/AddressInformation.java @@ -63,7 +63,7 @@ public Protocol getProtocol() { } public String getProtocolName() { - return this.protocol.name(); + return this.protocol.toString(); } public String getProtocolScheme() { diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Protocol.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Protocol.java index b49ad34a907e8..c954146856ac6 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Protocol.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Protocol.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos.directconnectivity; +import org.apache.commons.text.WordUtils; + public enum Protocol { HTTPS, TCP; @@ -36,4 +38,9 @@ String scheme() { throw new IllegalStateException(); } } + + @Override + public String toString() { + return WordUtils.capitalizeFully(this.name()); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java index 7154fc3a6f831..0415be2f0bdba 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java @@ -25,12 +25,12 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ISessionToken; import com.azure.data.cosmos.internal.InternalServerErrorException; -import com.azure.data.cosmos.internal.RequestChargeTracker; -import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java b/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java index 7a338279f2634..bc19112bbf423 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java @@ -27,7 +27,6 @@ import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,8 +36,8 @@ public class Configs { private static final Logger logger = LoggerFactory.getLogger(Configs.class); private final SslContext sslContext; - private static final String PROTOCOL = "COSMOS.PROTOCOL"; - private static final Protocol DEFAULT_PROTOCOL = Protocol.HTTPS; + private static final String PROTOCOL = "cosmos.directModeProtocol"; + private static final Protocol DEFAULT_PROTOCOL = Protocol.TCP; private static final String UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS = "COSMOS.UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS"; @@ -87,7 +86,7 @@ public SslContext getSslContext() { } public Protocol getProtocol() { - String protocol = getJVMConfigAsString(PROTOCOL, DEFAULT_PROTOCOL.name()); + String protocol = getJVMConfigAsString(PROTOCOL, DEFAULT_PROTOCOL.toString()); try { return Protocol.valueOf(StringUtils.upperCase(protocol.toLowerCase())); } catch (Exception e) { diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java b/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java index 31db81195b595..09a5bf248839c 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java @@ -24,17 +24,17 @@ package com.azure.data.cosmos.internal; -import java.net.URL; -import java.util.List; - import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.directconnectivity.StoreResult; import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.azure.data.cosmos.directconnectivity.StoreResult; import com.azure.data.cosmos.directconnectivity.TimeoutHelper; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import java.net.URL; +import java.util.List; + public class DocumentServiceRequestContext implements Cloneable{ public volatile boolean forceAddressRefresh; public volatile boolean forceRefreshAddressCache; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java b/commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java index dbdb4bf42ed3a..3c4bd698e4656 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java @@ -39,11 +39,9 @@ import io.reactivex.netty.protocol.http.client.CompositeHttpClientBuilder; import io.reactivex.netty.protocol.http.client.HttpClient.HttpClientConfig; import io.reactivex.netty.protocol.http.client.HttpClientPipelineConfigurator; - -import javax.net.ssl.SSLEngine; - import org.slf4j.LoggerFactory; +import javax.net.ssl.SSLEngine; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java b/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java index 9894764217a13..c8d2d8627356d 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java @@ -23,10 +23,6 @@ package com.azure.data.cosmos.internal; -import java.util.ArrayList; -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.azure.data.cosmos.Attachment; import com.azure.data.cosmos.Conflict; import com.azure.data.cosmos.Database; @@ -39,10 +35,14 @@ import com.azure.data.cosmos.Trigger; import com.azure.data.cosmos.User; import com.azure.data.cosmos.UserDefinedFunction; - -import org.apache.commons.text.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.text.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; /** * Used internally to provide utility methods to work with the resource's path in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java b/commons/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java index f5f1f1ae83756..4a37d5b7574fa 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java @@ -22,15 +22,14 @@ */ package com.azure.data.cosmos.internal; -import java.util.List; -import java.util.Map; - +import com.azure.data.cosmos.internal.routing.PartitionKeyAndResourceTokenPair; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.azure.data.cosmos.internal.routing.PartitionKeyAndResourceTokenPair; -import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import java.util.List; +import java.util.Map; /** * This class is used internally and act as a helper in authorization of diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java index d373e3a2af83c..5dc17cd969f10 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java @@ -23,24 +23,22 @@ package com.azure.data.cosmos.internal; -import java.io.InputStream; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; - -import com.azure.data.cosmos.directconnectivity.WFConstants; -import org.apache.commons.lang3.StringUtils; - import com.azure.data.cosmos.FeedOptionsBase; import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; - +import org.apache.commons.lang3.StringUtils; import rx.Observable; import rx.observables.StringObservable; +import java.io.InputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + /** * This is core Transport/Connection agnostic request to the Azure Cosmos DB database service. */ @@ -468,7 +466,7 @@ public static RxDocumentServiceRequest create(ResourceType resourceType, if (querySpec.parameters() != null && querySpec.parameters().size() > 0) { throw new IllegalArgumentException( String.format("Unsupported argument in query compatibility mode '{%s}'", - queryCompatibilityMode.name())); + queryCompatibilityMode.toString())); } operation = OperationType.SqlQuery; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java index f195ca31b88cf..93fa1c5b3513a 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java @@ -23,9 +23,6 @@ package com.azure.data.cosmos.internal; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.azure.data.cosmos.Attachment; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ClientSideRequestStatistics; @@ -43,6 +40,9 @@ import com.azure.data.cosmos.UserDefinedFunction; import com.azure.data.cosmos.directconnectivity.Address; import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; import org.apache.commons.lang3.StringUtils; import java.io.IOException; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Strings.java b/commons/src/main/java/com/azure/data/cosmos/internal/Strings.java index 41f0b87a41937..7f03efc4d0e2c 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/Strings.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Strings.java @@ -69,4 +69,25 @@ public static String toCamelCase(String str) { return str.substring(0, 1).toUpperCase() + str.substring(1, str.length()).toLowerCase(); } + + public static String fromCamelCaseToUpperCase(String str) { + if (str == null) { + return null; + } + + StringBuilder result = new StringBuilder(str); + + int i = 1; + while (i < result.length()) { + if (Character.isUpperCase(result.charAt(i))) { + result.insert(i, '_'); + i += 2; + } else { + result.replace(i, i + 1, Character.toString(Character.toUpperCase(result.charAt(i)))); + i ++; + } + } + + return result.toString(); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java b/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java index f9a78fd63bf0a..f67d210adff6e 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java @@ -33,12 +33,23 @@ import org.apache.commons.lang3.StringUtils; import java.io.UnsupportedEncodingException; -import java.net.*; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLEncoder; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; -import java.util.*; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; /** * While this class is public, but it is not part of our published public APIs. diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java index 512ad440cbebf..053dea7c7eee2 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.JsonGenerator; + import java.io.IOException; import java.io.OutputStream; -import com.fasterxml.jackson.core.JsonGenerator; -import com.azure.data.cosmos.internal.Utils; - class BoolPartitionKeyComponent implements IPartitionKeyComponent { private final boolean value; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java index f9c8030c5c0a8..e65fade4fe831 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos.internal.routing; -import java.io.OutputStream; - import com.fasterxml.jackson.core.JsonGenerator; +import java.io.OutputStream; + interface IPartitionKeyComponent { int CompareTo(IPartitionKeyComponent other); diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java index e4fca693c693e..18d02d76c1f9c 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.JsonGenerator; + import java.io.IOException; import java.io.OutputStream; -import com.fasterxml.jackson.core.JsonGenerator; -import com.azure.data.cosmos.internal.Utils; - class InfinityPartitionKeyComponent implements IPartitionKeyComponent { @Override public int CompareTo(IPartitionKeyComponent other) { diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java index 555623858136f..cc21423e379fb 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.JsonGenerator; + import java.io.IOException; import java.io.OutputStream; -import com.fasterxml.jackson.core.JsonGenerator; -import com.azure.data.cosmos.internal.Utils; - class MaxNumberPartitionKeyComponent implements IPartitionKeyComponent { public static final MaxNumberPartitionKeyComponent VALUE = new MaxNumberPartitionKeyComponent(); diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java index 22520651b6048..f825135217885 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.JsonGenerator; + import java.io.IOException; import java.io.OutputStream; -import com.fasterxml.jackson.core.JsonGenerator; -import com.azure.data.cosmos.internal.Utils; - class MaxStringPartitionKeyComponent implements IPartitionKeyComponent { public static final MaxStringPartitionKeyComponent VALUE = new MaxStringPartitionKeyComponent(); diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java index a87d99fb8ca5b..56c6063dfe240 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.JsonGenerator; + import java.io.IOException; import java.io.OutputStream; -import com.fasterxml.jackson.core.JsonGenerator; -import com.azure.data.cosmos.internal.Utils; - class MinNumberPartitionKeyComponent implements IPartitionKeyComponent { public static final MinNumberPartitionKeyComponent VALUE = new MinNumberPartitionKeyComponent(); diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java index e60c0c547df78..21ca27251866f 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.JsonGenerator; + import java.io.IOException; import java.io.OutputStream; -import com.fasterxml.jackson.core.JsonGenerator; -import com.azure.data.cosmos.internal.Utils; - class MinStringPartitionKeyComponent implements IPartitionKeyComponent { public static final MinStringPartitionKeyComponent VALUE = new MinStringPartitionKeyComponent(); diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java index 1b781c4694751..5f5a4b9848b86 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.JsonGenerator; + import java.io.IOException; import java.io.OutputStream; -import com.fasterxml.jackson.core.JsonGenerator; -import com.azure.data.cosmos.internal.Utils; - class NullPartitionKeyComponent implements IPartitionKeyComponent { public static final NullPartitionKeyComponent VALUE = new NullPartitionKeyComponent(); diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java index ef5b56b5a324d..4fa9d70aa7d1c 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.JsonGenerator; + import java.io.IOException; import java.io.OutputStream; -import com.fasterxml.jackson.core.JsonGenerator; -import com.azure.data.cosmos.internal.Utils; - /** * Used internally to represent a number component in the partition key of the Azure Cosmos DB database service. */ diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java index a91b468fcd68a..b5cddde833e2d 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java @@ -23,6 +23,10 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.Utils; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.ObjectCodec; @@ -35,10 +39,6 @@ import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import com.azure.data.cosmos.Undefined; -import com.azure.data.cosmos.internal.Utils; -import com.azure.data.cosmos.internal.RMResources; -import com.azure.data.cosmos.internal.Strings; import java.io.IOException; import java.util.ArrayList; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java index 1c765f7bde130..2a80fe6ad3399 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos.internal.routing; -import java.util.Comparator; - +import com.azure.data.cosmos.JsonSerializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -import com.azure.data.cosmos.JsonSerializable; + +import java.util.Comparator; @JsonIgnoreProperties({ "empty", "singleValue", "hashMap" }) public final class Range> extends JsonSerializable { diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java index 104bb9ce2d421..66b79466f46f3 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java @@ -23,13 +23,13 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.JsonGenerator; + import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; -import com.fasterxml.jackson.core.JsonGenerator; -import com.azure.data.cosmos.internal.Utils; - class StringPartitionKeyComponent implements IPartitionKeyComponent { public static final int MAX_STRING_CHARS = 100; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java index 59dc6e13655a0..f67302bf73fb2 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.internal.Utils; +import com.fasterxml.jackson.core.JsonGenerator; + import java.io.IOException; import java.io.OutputStream; -import com.fasterxml.jackson.core.JsonGenerator; -import com.azure.data.cosmos.internal.Utils; - class UndefinedPartitionKeyComponent implements IPartitionKeyComponent { public static final UndefinedPartitionKeyComponent VALUE = new UndefinedPartitionKeyComponent(); diff --git a/commons/src/test/java/com/azure/data/cosmos/ConflictTests.java b/commons/src/test/java/com/azure/data/cosmos/ConflictTests.java index fc079c6ffb075..8ec191b8c82d9 100644 --- a/commons/src/test/java/com/azure/data/cosmos/ConflictTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/ConflictTests.java @@ -23,8 +23,6 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.Conflict; -import com.azure.data.cosmos.Document; import org.apache.commons.io.IOUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; diff --git a/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java b/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java index 7b6c1f033422d..055c0e8c8cf40 100644 --- a/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java @@ -23,8 +23,6 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; import com.google.common.collect.ImmutableMap; import org.testng.annotations.Test; diff --git a/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java b/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java index daa8b7dc333c0..d2a84034f3066 100644 --- a/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java @@ -23,9 +23,6 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.PartitionKeyDefinitionVersion; import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; diff --git a/commons/src/test/java/com/azure/data/cosmos/DocumentTests.java b/commons/src/test/java/com/azure/data/cosmos/DocumentTests.java index 7dfaa1bff5a74..656c8e93d542e 100644 --- a/commons/src/test/java/com/azure/data/cosmos/DocumentTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/DocumentTests.java @@ -23,15 +23,13 @@ package com.azure.data.cosmos; -import static org.assertj.core.api.Assertions.assertThat; - - -import com.azure.data.cosmos.Document; import org.testng.annotations.Test; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import static org.assertj.core.api.Assertions.assertThat; + public class DocumentTests { @Test(groups = { "unit" }) diff --git a/commons/src/test/java/com/azure/data/cosmos/IncludedPathTest.java b/commons/src/test/java/com/azure/data/cosmos/IncludedPathTest.java index cdbaa7b56c924..70ab7d2fe9bed 100644 --- a/commons/src/test/java/com/azure/data/cosmos/IncludedPathTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/IncludedPathTest.java @@ -22,14 +22,11 @@ */ package com.azure.data.cosmos; -import static org.assertj.core.api.Assertions.assertThat; +import org.testng.annotations.Test; import java.util.Collection; -import com.azure.data.cosmos.DataType; -import com.azure.data.cosmos.IncludedPath; -import com.azure.data.cosmos.Index; -import org.testng.annotations.Test; +import static org.assertj.core.api.Assertions.assertThat; public class IncludedPathTest { @@ -39,13 +36,13 @@ public void deserialize() { " 'path': '\\/*'," + " 'indexes': [" + " {" + - " 'kind': 'RANGE'," + - " 'dataType': 'STRING'," + + " 'kind': 'Range'," + + " 'dataType': 'String'," + " 'precision': -1" + " }," + " {" + - " 'kind': 'RANGE'," + - " 'dataType': 'NUMBER'," + + " 'kind': 'Range'," + + " 'dataType': 'Number'," + " 'precision': -1" + " }" + " ]" + diff --git a/commons/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java b/commons/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java index d1a04d6e3a819..cd91eec212194 100644 --- a/commons/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java @@ -1,16 +1,14 @@ package com.azure.data.cosmos; -import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.fail; - -import java.io.Serializable; - -import com.azure.data.cosmos.Document; -import org.testng.annotations.Test; - import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; +import org.testng.annotations.Test; + +import java.io.Serializable; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.Assert.fail; public class JsonSerializableTests { diff --git a/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java b/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java index 8688f825115c3..0c1fbaca22b49 100644 --- a/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java @@ -22,13 +22,10 @@ */ package com.azure.data.cosmos; -import static org.assertj.core.api.Assertions.assertThat; - -import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.Permission; -import com.azure.data.cosmos.PermissionMode; import org.testng.annotations.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class PermissionTest { @Test(groups = {"unit"}) diff --git a/commons/src/test/java/com/azure/data/cosmos/ResourceIdTests.java b/commons/src/test/java/com/azure/data/cosmos/ResourceIdTests.java index 43b227fdfc00f..c196baf42c6fd 100644 --- a/commons/src/test/java/com/azure/data/cosmos/ResourceIdTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/ResourceIdTests.java @@ -23,16 +23,15 @@ package com.azure.data.cosmos; -import static org.assertj.core.api.Assertions.assertThat; +import com.azure.data.cosmos.internal.ResourceId; +import org.apache.commons.lang3.tuple.Pair; +import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; import java.util.Random; -import org.apache.commons.lang3.tuple.Pair; -import org.testng.annotations.Test; - -import com.azure.data.cosmos.internal.ResourceId; +import static org.assertj.core.api.Assertions.assertThat; public class ResourceIdTests { diff --git a/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java b/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java index f9dcb97d995e0..fb3e24bf486bd 100644 --- a/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java @@ -22,17 +22,7 @@ */ package com.azure.data.cosmos.directconnectivity; -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.UnsupportedEncodingException; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - -import org.testng.annotations.Test; - import com.azure.data.cosmos.internal.HttpConstants; - import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.HttpHeaders; @@ -41,6 +31,14 @@ import io.netty.handler.codec.http.HttpVersion; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import org.testng.annotations.Test; + +import java.io.UnsupportedEncodingException; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; public class HttpUtilsTest { diff --git a/commons/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseTest.java b/commons/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseTest.java index 262bdb2fdd0ac..e6208e4ecb067 100644 --- a/commons/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseTest.java @@ -23,15 +23,15 @@ package com.azure.data.cosmos.directconnectivity; -import static org.assertj.core.api.Assertions.assertThat; +import org.apache.commons.io.IOUtils; +import org.testng.annotations.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.HashMap; -import org.apache.commons.io.IOUtils; -import org.testng.annotations.Test; +import static org.assertj.core.api.Assertions.assertThat; public class StoreResponseTest { @Test(groups = { "unit" }) diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java b/commons/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java similarity index 97% rename from gateway/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java rename to commons/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java index 0e935f5ee40bc..d69fdaa70bf69 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos.internal; -import static org.assertj.core.api.Assertions.assertThat; - import com.azure.data.cosmos.directconnectivity.Protocol; import org.testng.annotations.Test; +import static org.assertj.core.api.Assertions.assertThat; + public class ConfigsTests { @Test(groups = { "unit" }) @@ -45,7 +45,7 @@ public void maxHttpBodyLength() { @Test(groups = { "unit" }) public void getProtocol() { Configs config = new Configs(); - assertThat(config.getProtocol()).isEqualTo(Protocol.valueOf(System.getProperty("COSMOS.PROTOCOL", "HTTPS"))); + assertThat(config.getProtocol()).isEqualTo(Protocol.valueOf(System.getProperty("cosmos.directModeProtocol", "TCP"))); } @Test(groups = { "unit" }) diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java b/commons/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java index fd3ed3c53e836..2538b0faf95dd 100644 --- a/commons/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.internal; import org.testng.annotations.Test; + import static org.assertj.core.api.Assertions.assertThat; public class PathsHelperTest { diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java b/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java index 7a0decd919a4f..da6e0a904a988 100644 --- a/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java @@ -23,19 +23,17 @@ package com.azure.data.cosmos.internal; -import static org.assertj.core.api.Assertions.assertThat; - -import java.nio.charset.StandardCharsets; -import java.util.UUID; - +import com.azure.data.cosmos.Document; import org.apache.commons.collections4.map.HashedMap; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import rx.Observable; -import com.azure.data.cosmos.Document; +import java.nio.charset.StandardCharsets; +import java.util.UUID; -import rx.Observable; +import static org.assertj.core.api.Assertions.assertThat; public class RxDocumentServiceRequestTest { diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java b/commons/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java index 39a4000fd2984..8cc1477868426 100644 --- a/commons/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java @@ -23,13 +23,13 @@ package com.azure.data.cosmos.internal; -import java.time.format.DateTimeFormatter; -import java.util.Locale; - import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import java.time.format.DateTimeFormatter; +import java.util.Locale; + public class TimeTokenTest { private Locale defaultLocale; diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java b/commons/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java index ec8a23046128b..fb8eccd8aed03 100644 --- a/commons/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java @@ -2,6 +2,7 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; + import static org.assertj.core.api.Assertions.assertThat; public class StringPartitionKeyComponentTest { diff --git a/direct-impl/pom.xml b/direct-impl/pom.xml index e925fe6321287..44c305467bf2d 100644 --- a/direct-impl/pom.xml +++ b/direct-impl/pom.xml @@ -36,7 +36,8 @@ SOFTWARE. unit 3.0.0-a1-SNAPSHOT 27.0.1-jre - + 4.0.5 + @@ -53,8 +54,7 @@ SOFTWARE. org.apache.maven.plugins maven-surefire-plugin - - + @@ -313,6 +313,11 @@ SOFTWARE. guava ${guava.version} + + io.dropwizard.metrics + metrics-core + ${metrics.version} + diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java index 550f744adf51c..b167739a0db6f 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java @@ -27,23 +27,23 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.BadRequestException; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.NotFoundException; import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.ResourceId; import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.internal.BadRequestException; -import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; -import com.azure.data.cosmos.internal.InvalidPartitionException; -import com.azure.data.cosmos.internal.NotFoundException; -import com.azure.data.cosmos.internal.RMResources; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.Strings; -import com.azure.data.cosmos.internal.caches.RxCollectionCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Single; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java index 3e097852f291f..58db1cd1d31ec 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java @@ -23,18 +23,18 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.InternalServerErrorException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.ResourceId; import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.Utils; -import com.azure.data.cosmos.internal.AuthorizationTokenType; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Single; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java index ab3ebb10261e5..3f1b798379ec2 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java @@ -23,28 +23,27 @@ package com.azure.data.cosmos.directconnectivity; -import java.util.HashMap; -import java.util.List; - import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.ISessionToken; import com.azure.data.cosmos.internal.NotFoundException; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; - -import static com.azure.data.cosmos.internal.Utils.ValueHolder; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Single; +import java.util.HashMap; +import java.util.List; + +import static com.azure.data.cosmos.internal.Utils.ValueHolder; + /* ConsistencyLevel Replication Mode Desired ReadMode ------------------- -------------------- --------------------------------------------------------------------------- diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java index 6c19be06c1eee..b6a8dcc28640c 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java @@ -28,12 +28,12 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.Integers; -import com.azure.data.cosmos.internal.RequestChargeTracker; -import com.azure.data.cosmos.internal.SessionTokenHelper; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.Integers; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.SessionTokenHelper; import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.internal.Utils; import org.apache.commons.collections4.ComparatorUtils; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java index bae340f944431..3adaa06d98cc7 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java @@ -27,22 +27,22 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.Paths; import com.azure.data.cosmos.internal.PathsHelper; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.UserAgentContainer; -import com.azure.data.cosmos.internal.Utils; -import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.internal.AuthorizationTokenType; -import com.azure.data.cosmos.internal.Exceptions; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.caches.AsyncCache; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import io.netty.buffer.ByteBuf; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java index a7a8b4d569b35..5feac5c55db40 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java @@ -23,15 +23,6 @@ package com.azure.data.cosmos.directconnectivity; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; @@ -39,21 +30,28 @@ import com.azure.data.cosmos.ReplicationPolicy; import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.GlobalEndpointManager; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.Utils; -import com.azure.data.cosmos.internal.GlobalEndpointManager; - import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; +import org.apache.commons.lang3.StringUtils; import rx.Observable; import rx.Single; import rx.functions.Action1; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + /** * This class will read the service configuration from the gateway. * diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java index 530d6c6986b90..3a5f71c480067 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java @@ -23,23 +23,21 @@ package com.azure.data.cosmos.directconnectivity; -import java.time.Duration; - import com.azure.data.cosmos.CosmosClientException; -import org.apache.commons.lang3.time.StopWatch; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.Quadruple; import com.azure.data.cosmos.internal.IRetryPolicy; import com.azure.data.cosmos.internal.InvalidPartitionException; import com.azure.data.cosmos.internal.PartitionIsMigratingException; import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.Quadruple; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; - +import org.apache.commons.lang3.time.StopWatch; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import rx.Single; +import java.time.Duration; + public class GoneAndRetryWithRetryPolicy implements IRetryPolicy { private final static Logger logger = LoggerFactory.getLogger(GoneAndRetryWithRetryPolicy.class); diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java index 4667c0c7be9ba..b39a1cc753b77 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java @@ -25,27 +25,27 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.HttpClientFactory; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Integers; import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.InvalidPartitionException; import com.azure.data.cosmos.internal.Lists; import com.azure.data.cosmos.internal.Longs; import com.azure.data.cosmos.internal.MutableVolatile; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.PathsHelper; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RuntimeConstants; -import com.azure.data.cosmos.internal.UserAgentContainer; -import com.azure.data.cosmos.internal.BadRequestException; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.HttpClientFactory; -import com.azure.data.cosmos.internal.InvalidPartitionException; import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.PartitionIsMigratingException; import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.PathsHelper; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RuntimeConstants; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.Utils; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java index 5654cde3382e7..ecd2d097856d4 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java @@ -26,14 +26,14 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.InternalServerErrorException; import com.azure.data.cosmos.internal.JavaStreamUtils; import com.azure.data.cosmos.internal.MutableVolatile; import com.azure.data.cosmos.internal.Quadruple; -import com.azure.data.cosmos.internal.RequestChargeTracker; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java index 6ddc736bcc0f7..c60645dce0707 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java @@ -23,28 +23,26 @@ package com.azure.data.cosmos.directconnectivity; -import java.time.Duration; - import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.ReplicatedResourceClientUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.BackoffRetryUtility; +import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.Quadruple; +import com.azure.data.cosmos.internal.ReplicatedResourceClientUtils; import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.BackoffRetryUtility; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import rx.Single; import rx.functions.Func1; import rx.functions.Func2; +import java.time.Duration; + /** * ReplicatedResourceClient uses the ConsistencyReader to make requests to * backend diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java index 095073d14acea..6ddc0bfcf83f9 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java @@ -25,8 +25,8 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Strings; @@ -40,7 +40,7 @@ public static ConsistencyLevel GetConsistencyLevelToUse(GatewayServiceConfigurat String requestConsistencyLevelHeaderValue = request.getHeaders().get(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL); if (!Strings.isNullOrEmpty(requestConsistencyLevelHeaderValue)) { - ConsistencyLevel requestConsistencyLevel = EnumUtils.getEnum(ConsistencyLevel.class, requestConsistencyLevelHeaderValue); + ConsistencyLevel requestConsistencyLevel = EnumUtils.getEnum(ConsistencyLevel.class, Strings.fromCamelCaseToUpperCase(requestConsistencyLevelHeaderValue)); if (requestConsistencyLevel == null) { throw new BadRequestException( String.format( diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java index b00e20b28e1df..7c8500acb5a7a 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java @@ -24,66 +24,67 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableMap; -import com.azure.data.cosmos.internal.UserAgentContainer; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdClientChannelInitializer; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdEndpoint; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdMetrics; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdObjectMapper; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestArgs; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestManager; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestRecord; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdServiceEndpoint; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelOption; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.logging.LogLevel; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; import io.netty.handler.ssl.SslContext; -import io.netty.util.concurrent.DefaultThreadFactory; -import io.netty.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Single; +import rx.SingleEmitter; import java.io.IOException; import java.net.URI; import java.time.Duration; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; -import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdReporter.reportIssueUnless; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; -final public class RntbdTransportClient extends TransportClient implements AutoCloseable { +@JsonSerialize(using = RntbdTransportClient.JsonSerializer.class) +public final class RntbdTransportClient extends TransportClient implements AutoCloseable { // region Fields - final private static String className = RntbdTransportClient.class.getName(); - final private static AtomicLong counter = new AtomicLong(0L); - final private static Logger logger = LoggerFactory.getLogger(className); + private static final AtomicLong instanceCount = new AtomicLong(); + private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClient.class); + private static final String namePrefix = RntbdTransportClient.class.getSimpleName() + '-'; - final private AtomicBoolean closed = new AtomicBoolean(false); - final private EndpointFactory endpointFactory; - final private String name; + private final AtomicBoolean closed = new AtomicBoolean(); + private final RntbdEndpoint.Provider endpointProvider; + private final RntbdMetrics metrics; + private final String name; // endregion // region Constructors - RntbdTransportClient(EndpointFactory endpointFactory) { - this.name = className + '-' + counter.incrementAndGet(); - this.endpointFactory = endpointFactory; + RntbdTransportClient(final RntbdEndpoint.Provider endpointProvider) { + this.name = RntbdTransportClient.namePrefix + RntbdTransportClient.instanceCount.incrementAndGet(); + this.endpointProvider = endpointProvider; + this.metrics = new RntbdMetrics(this.name); } - RntbdTransportClient(Options options, SslContext sslContext, UserAgentContainer userAgent) { - this(new EndpointFactory(options, sslContext, userAgent)); + RntbdTransportClient(final Options options, final SslContext sslContext) { + this(new RntbdServiceEndpoint.Provider(options, sslContext)); } - RntbdTransportClient(Configs configs, int requestTimeoutInSeconds, UserAgentContainer userAgent) { - this(new Options(Duration.ofSeconds((long)requestTimeoutInSeconds)), configs.getSslContext(), userAgent); + RntbdTransportClient(final Configs configs, final int requestTimeoutInSeconds, final UserAgentContainer userAgent) { + this(new Options.Builder(requestTimeoutInSeconds).userAgent(userAgent).build(), configs.getSslContext()); } // endregion @@ -93,447 +94,293 @@ final public class RntbdTransportClient extends TransportClient implements AutoC @Override public void close() { - if (this.closed.compareAndSet(false, true)) { - - this.endpointFactory.close().addListener(future -> { - - if (future.isSuccess()) { - - // TODO: DANOBLE: Deal with fact that all channels are closed, but each of their sockets are open - // Links: - // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 - // Notes: - // Observation: Closing/shutting down a channel does not cause its underlying socket to be closed - // Option: Pool SocketChannel instances and manage the SocketChannel used by each NioSocketChannel - // Option: Inherit from NioSocketChannel to ensure the behavior we'd like (close means close) - // Option: Recommend that customers increase their system's file descriptor count (e.g., on macOS) - - logger.info("{} closed", this); - return; - } - - logger.error("{} close failed: {}", this, future.cause()); - }); + logger.debug("\n [{}] CLOSE", this); - } else { - logger.debug("{} already closed", this); + if (this.closed.compareAndSet(false, true)) { + this.endpointProvider.close(); + this.metrics.close(); + return; } + + logger.debug("\n [{}]\n already closed", this); } @Override public Single invokeStoreAsync( - URI physicalAddress, ResourceOperation unused, RxDocumentServiceRequest request + final URI physicalAddress, final ResourceOperation unused, final RxDocumentServiceRequest request ) { - Objects.requireNonNull(physicalAddress, "physicalAddress"); - Objects.requireNonNull(request, "request"); + checkNotNull(physicalAddress, "physicalAddress"); + checkNotNull(request, "request"); this.throwIfClosed(); - final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, physicalAddress.getPath()); - final Endpoint endpoint = this.endpointFactory.getEndpoint(physicalAddress); + final RntbdRequestArgs requestArgs = new RntbdRequestArgs(request, physicalAddress); - final CompletableFuture responseFuture = endpoint.write(requestArgs); + if (logger.isDebugEnabled()) { + requestArgs.traceOperation(logger, null, "invokeStoreAsync"); + logger.debug("\n [{}]\n {}\n INVOKE_STORE_ASYNC", this, requestArgs); + } - return Single.fromEmitter(emitter -> responseFuture.whenComplete((response, error) -> { + final RntbdEndpoint endpoint = this.endpointProvider.get(physicalAddress); + this.metrics.incrementRequestCount(); - requestArgs.traceOperation(logger, null, "emitSingle", response, error); + final RntbdRequestRecord requestRecord = endpoint.request(requestArgs); - if (error == null) { - if (logger.isDebugEnabled()) { - logger.debug("{} [physicalAddress: {}, activityId: {}] Request succeeded with response status: {}", - endpoint, physicalAddress, request.getActivityId(), response.getStatus() - ); - } - emitter.onSuccess(response); + return Single.fromEmitter((SingleEmitter emitter) -> { + + requestRecord.whenComplete((response, error) -> { - } else { - if (logger.isErrorEnabled()) { - logger.error("{} [physicalAddress: {}, activityId: {}] Request failed: {}", - endpoint, physicalAddress, request.getActivityId(), error.getMessage() - ); + requestArgs.traceOperation(logger, null, "emitSingle", response, error); + this.metrics.incrementResponseCount(); + + if (error == null) { + emitter.onSuccess(response); + } else { + reportIssueUnless(error instanceof CosmosClientException, logger, requestRecord, "", error); + this.metrics.incrementErrorResponseCount(); + emitter.onError(error); } - emitter.onError(error); - } - requestArgs.traceOperation(logger, null, "completeEmitSingle"); - })); + requestArgs.traceOperation(logger, null, "emitSingleComplete"); + }); + }); } @Override public String toString() { - return '[' + name + ", endpointCount: " + this.endpointFactory.endpoints.mappingCount() + ']'; + return RntbdObjectMapper.toJson(this); } private void throwIfClosed() { - if (this.closed.get()) { - throw new IllegalStateException(String.format("%s is closed", this)); - } + checkState(!this.closed.get(), "%s is closed", this); } // endregion // region Types - interface Endpoint { - - Future close(); - - CompletableFuture write(RntbdRequestArgs requestArgs); - } - - private static class DefaultEndpoint implements Endpoint { - - final private ChannelFuture channelFuture; - final private RntbdRequestManager requestManager; - - DefaultEndpoint(EndpointFactory factory, URI physicalAddress) { - - final RntbdClientChannelInitializer clientChannelInitializer = factory.createClientChannelInitializer(); - this.requestManager = clientChannelInitializer.getRequestManager(); - final int connectionTimeout = factory.getConnectionTimeout(); - - final Bootstrap bootstrap = new Bootstrap() - .channel(NioSocketChannel.class) - .group(factory.eventLoopGroup) - .handler(clientChannelInitializer) - .option(ChannelOption.AUTO_READ, true) - .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout) - .option(ChannelOption.SO_KEEPALIVE, true); + static final class JsonSerializer extends StdSerializer { - this.channelFuture = bootstrap.connect(physicalAddress.getHost(), physicalAddress.getPort()); + public JsonSerializer() { + this(null); } - public Future close() { - return this.channelFuture.channel().close(); + public JsonSerializer(Class type) { + super(type); } @Override - public String toString() { - return this.channelFuture.channel().toString(); - } - - public CompletableFuture write(RntbdRequestArgs requestArgs) { - - Objects.requireNonNull(requestArgs, "requestArgs"); - - final CompletableFuture responseFuture = this.requestManager.createStoreResponseFuture(requestArgs); - - this.channelFuture.addListener((ChannelFuture future) -> { - - if (future.isSuccess()) { - requestArgs.traceOperation(logger, null, "doWrite"); - logger.debug("{} connected", future.channel()); - doWrite(future.channel(), requestArgs); - return; - } - - UUID activityId = requestArgs.getActivityId(); + public void serialize(RntbdTransportClient value, JsonGenerator generator, SerializerProvider provider) throws IOException { - if (future.isCancelled()) { + generator.writeStartObject(); - this.requestManager.cancelStoreResponseFuture(activityId); + generator.writeArrayFieldStart(value.name); - logger.debug("{}{} request cancelled: ", future.channel(), requestArgs, future.cause()); - - } else { - - final Channel channel = future.channel(); - Throwable cause = future.cause(); - - logger.error("{}{} request failed: ", channel, requestArgs, cause); - - GoneException goneException = new GoneException( - String.format("failed to establish connection to %s: %s", - channel.remoteAddress(), cause.getMessage() - ), - cause instanceof Exception ? (Exception)cause : new IOException(cause.getMessage(), cause), - ImmutableMap.of(HttpHeaders.ACTIVITY_ID, activityId.toString()), - requestArgs.getReplicaPath() - ); - - logger.debug("{}{} {} mapped to GoneException: ", - channel, requestArgs, cause.getClass(), goneException - ); - - this.requestManager.completeStoreResponseFutureExceptionally(activityId, goneException); + value.endpointProvider.list().forEach(endpoint -> { + try { + generator.writeObject(endpoint); + } catch (IOException error) { + logger.error("failed to serialize {} due to ", endpoint.getName(), error); } - }); - return responseFuture; - } + generator.writeEndArray(); - private static void doWrite(Channel channel, RntbdRequestArgs requestArgs) { + generator.writeObjectField("config", value.endpointProvider.config()); + generator.writeObjectField("metrics", value.metrics); + generator.writeEndObject(); + } + } - channel.write(requestArgs).addListener((ChannelFuture future) -> { + public static final class Options { - requestArgs.traceOperation(logger, null, "writeComplete", future.channel()); + // region Fields - if (future.isSuccess()) { + private final String certificateHostNameOverride; + private final int maxChannelsPerEndpoint; + private final int maxRequestsPerChannel; + private final Duration connectionTimeout; + private final int partitionCount; + private final Duration receiveHangDetectionTime; + private final Duration requestTimeout; + private final Duration sendHangDetectionTime; + private final UserAgentContainer userAgent; - logger.debug("{} request sent: {}", future.channel(), requestArgs); + // endregion - } else if (future.isCancelled()) { + // region Constructors - logger.debug("{}{} request cancelled: {}", - future.channel(), requestArgs, future.cause().getMessage() - ); + private Options(Builder builder) { - } else { - Throwable cause = future.cause(); - logger.error("{}{} request failed due to {}: {}", - future.channel(), requestArgs, cause.getClass(), cause.getMessage() - ); - } - }); + this.certificateHostNameOverride = builder.certificateHostNameOverride; + this.maxChannelsPerEndpoint = builder.maxChannelsPerEndpoint; + this.maxRequestsPerChannel = builder.maxRequestsPerChannel; + this.connectionTimeout = builder.connectionTimeout == null ? builder.requestTimeout : builder.connectionTimeout; + this.partitionCount = builder.partitionCount; + this.requestTimeout = builder.requestTimeout; + this.receiveHangDetectionTime = builder.receiveHangDetectionTime; + this.sendHangDetectionTime = builder.sendHangDetectionTime; + this.userAgent = builder.userAgent; } - } - - static class EndpointFactory { - final private ConcurrentHashMap endpoints = new ConcurrentHashMap<>(); - final private NioEventLoopGroup eventLoopGroup; - final private Options options; - final private SslContext sslContext; - final private UserAgentContainer userAgent; - - EndpointFactory(Options options, SslContext sslContext, UserAgentContainer userAgent) { - - Objects.requireNonNull(options, "options"); - Objects.requireNonNull(sslContext, "sslContext"); - Objects.requireNonNull(userAgent, "userAgent"); + // endregion - final DefaultThreadFactory threadFactory = new DefaultThreadFactory("CosmosEventLoop", true); - final int threadCount = Runtime.getRuntime().availableProcessors(); + // region Accessors - this.eventLoopGroup = new NioEventLoopGroup(threadCount, threadFactory); - this.options = options; - this.sslContext = sslContext; - this.userAgent = userAgent; + public String getCertificateHostNameOverride() { + return this.certificateHostNameOverride; } - int getConnectionTimeout() { - return (int)this.options.getOpenTimeout().toMillis(); + public int getMaxChannelsPerEndpoint() { + return this.maxChannelsPerEndpoint; } - Options getOptions() { - return this.options; + public int getMaxRequestsPerChannel() { + return this.maxRequestsPerChannel; } - UserAgentContainer getUserAgent() { - return this.userAgent; + public Duration getConnectionTimeout() { + return this.connectionTimeout; } - Future close() { - return this.eventLoopGroup.shutdownGracefully(); + public int getPartitionCount() { + return this.partitionCount; } - RntbdClientChannelInitializer createClientChannelInitializer() { - - final LogLevel logLevel; - - if (RntbdTransportClient.logger.isTraceEnabled()) { - logLevel = LogLevel.TRACE; - } else if (RntbdTransportClient.logger.isDebugEnabled()) { - logLevel = LogLevel.DEBUG; - } else { - logLevel = null; - } - - return new RntbdClientChannelInitializer(this.userAgent, this.sslContext, logLevel, this.options); + public Duration getReceiveHangDetectionTime() { + return this.receiveHangDetectionTime; } - Endpoint createEndpoint(URI physicalAddress) { - return new DefaultEndpoint(this, physicalAddress); + public Duration getRequestTimeout() { + return this.requestTimeout; } - void deleteEndpoint(URI physicalAddress) { - - // TODO: DANOBLE: Utilize this method of tearing down unhealthy endpoints - // Links: - // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/331552 - // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/331593 - - final String authority = physicalAddress.getAuthority(); - final Endpoint endpoint = this.endpoints.remove(authority); - - if (endpoint == null) { - throw new IllegalArgumentException(String.format("physicalAddress: %s", physicalAddress)); - } - - endpoint.close().addListener(future -> { - - if (future.isSuccess()) { - logger.info("{} closed channel of communication with {}", endpoint, authority); - return; - } - - logger.error("{} failed to close channel of communication with {}: {}", endpoint, authority, future.cause()); - }); + public Duration getSendHangDetectionTime() { + return this.sendHangDetectionTime; } - Endpoint getEndpoint(URI physicalAddress) { - return this.endpoints.computeIfAbsent( - physicalAddress.getAuthority(), authority -> this.createEndpoint(physicalAddress) - ); + public UserAgentContainer getUserAgent() { + return this.userAgent; } - } - - final public static class Options { - - // region Fields - - private String certificateHostNameOverride; - private int maxChannels; - private int maxRequestsPerChannel; - private Duration openTimeout = Duration.ZERO; - private int partitionCount; - private Duration receiveHangDetectionTime; - private Duration requestTimeout; - private Duration sendHangDetectionTime; - private Duration timerPoolResolution = Duration.ZERO; - private UserAgentContainer userAgent = null; // endregion - // region Constructors - - public Options(int requestTimeoutInSeconds) { - this(Duration.ofSeconds((long)requestTimeoutInSeconds)); - } - - public Options(Duration requestTimeout) { - - Objects.requireNonNull(requestTimeout); - - if (requestTimeout.compareTo(Duration.ZERO) <= 0) { - throw new IllegalArgumentException("requestTimeout"); - } + // region Methods - this.maxChannels = 0xFFFF; - this.maxRequestsPerChannel = 30; - this.partitionCount = 1; - this.receiveHangDetectionTime = Duration.ofSeconds(65L); - this.requestTimeout = requestTimeout; - this.sendHangDetectionTime = Duration.ofSeconds(10L); + @Override + public String toString() { + return RntbdObjectMapper.toJson(this); } // endregion - // region Property accessors + // region Types - public String getCertificateHostNameOverride() { - return certificateHostNameOverride; - } + public static class Builder { - public void setCertificateHostNameOverride(String value) { - this.certificateHostNameOverride = value; - } + // region Fields - public int getMaxChannels() { - return this.maxChannels; - } + private static final UserAgentContainer DEFAULT_USER_AGENT_CONTAINER = new UserAgentContainer(); + private static final Duration SIXTY_FIVE_SECONDS = Duration.ofSeconds(65L); + private static final Duration TEN_SECONDS = Duration.ofSeconds(10L); - public void setMaxChannels(int value) { - this.maxChannels = value; - } + // Required parameters - public int getMaxRequestsPerChannel() { - return this.maxRequestsPerChannel; - } + private String certificateHostNameOverride = null; - public void setMaxRequestsPerChannel(int maxRequestsPerChannel) { - this.maxRequestsPerChannel = maxRequestsPerChannel; - } + // Optional parameters - public Duration getOpenTimeout() { - return this.openTimeout.isNegative() || this.openTimeout.isZero() ? this.requestTimeout : this.openTimeout; - } + private int maxChannelsPerEndpoint = 10; + private int maxRequestsPerChannel = 30; + private Duration connectionTimeout = null; + private int partitionCount = 1; + private Duration receiveHangDetectionTime = SIXTY_FIVE_SECONDS; + private Duration requestTimeout; + private Duration sendHangDetectionTime = TEN_SECONDS; + private UserAgentContainer userAgent = DEFAULT_USER_AGENT_CONTAINER; - public void setOpenTimeout(Duration value) { - this.openTimeout = value; - } - - public int getPartitionCount() { - return this.partitionCount; - } - - public void setPartitionCount(int value) { - this.partitionCount = value; - } - - public Duration getReceiveHangDetectionTime() { - return this.receiveHangDetectionTime; - } + // endregion - public void setReceiveHangDetectionTime(Duration value) { - this.receiveHangDetectionTime = value; - } + // region Constructors - public Duration getRequestTimeout() { - return this.requestTimeout; - } + public Builder(Duration requestTimeout) { + this.requestTimeout(requestTimeout); + } - public Duration getSendHangDetectionTime() { - return this.sendHangDetectionTime; - } + public Builder(int requestTimeoutInSeconds) { + this(Duration.ofSeconds(requestTimeoutInSeconds)); + } - public void setSendHangDetectionTime(Duration value) { - this.sendHangDetectionTime = value; - } + // endregion - public Duration getTimerPoolResolution() { - return calculateTimerPoolResolutionSeconds(this.timerPoolResolution, this.requestTimeout, this.openTimeout); - } + // region Methods - public void setTimerPoolResolution(Duration value) { - this.timerPoolResolution = value; - } + public Options build() { + return new Options(this); + } - public UserAgentContainer getUserAgent() { + public Builder certificateHostNameOverride(final String value) { + this.certificateHostNameOverride = value; + return this; + } - if (this.userAgent != null) { - return this.userAgent; + public Builder connectionTimeout(final Duration value) { + checkArgument(value == null || value.compareTo(Duration.ZERO) > 0, "value: %s", value); + this.connectionTimeout = value; + return this; } - this.userAgent = new UserAgentContainer(); - return this.userAgent; - } + public Builder maxRequestsPerChannel(final int value) { + checkArgument(value > 0, "value: %s", value); + this.maxRequestsPerChannel = value; + return this; + } - public void setUserAgent(UserAgentContainer value) { - this.userAgent = value; - } + public Builder maxChannelsPerEndpoint(final int value) { + checkArgument(value > 0, "value: %s", value); + this.maxChannelsPerEndpoint = value; + return this; + } - // endregion + public Builder partitionCount(final int value) { + checkArgument(value > 0, "value: %s", value); + this.partitionCount = value; + return this; + } - // region Methods + public Builder receiveHangDetectionTime(final Duration value) { - private static Duration calculateTimerPoolResolutionSeconds( + checkNotNull(value, "value: null"); + checkArgument(value.compareTo(Duration.ZERO) > 0, "value: %s", value); - Duration timerPoolResolution, - Duration requestTimeout, - Duration openTimeout) { + this.receiveHangDetectionTime = value; + return this; + } - Objects.requireNonNull(timerPoolResolution, "timerPoolResolution"); - Objects.requireNonNull(requestTimeout, "requestTimeout"); - Objects.requireNonNull(openTimeout, "openTimeout"); + public Builder requestTimeout(final Duration value) { - if (timerPoolResolution.compareTo(Duration.ZERO) <= 0 && requestTimeout.compareTo(Duration.ZERO) <= 0 && - openTimeout.compareTo(Duration.ZERO) <= 0) { + checkNotNull(value, "value: null"); + checkArgument(value.compareTo(Duration.ZERO) > 0, "value: %s", value); - throw new IllegalStateException("RntbdTransportClient.Options"); + this.requestTimeout = value; + return this; } - if (timerPoolResolution.compareTo(Duration.ZERO) > 0 && timerPoolResolution.compareTo(openTimeout) < 0 && - timerPoolResolution.compareTo(requestTimeout) < 0) { + public Builder sendHangDetectionTime(final Duration value) { + + checkNotNull(value, "value: null"); + checkArgument(value.compareTo(Duration.ZERO) > 0, "value: %s", value); - return timerPoolResolution; + this.sendHangDetectionTime = value; + return this; } - if (openTimeout.compareTo(Duration.ZERO) > 0 && requestTimeout.compareTo(Duration.ZERO) > 0) { - return openTimeout.compareTo(requestTimeout) < 0 ? openTimeout : requestTimeout; + public Builder userAgent(final UserAgentContainer value) { + checkNotNull(value, "value: null"); + this.userAgent = value; + return this; } - return openTimeout.compareTo(Duration.ZERO) > 0 ? openTimeout : requestTimeout; + // endregion } // endregion diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java index 28761ba122af9..34c25b37f8bad 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java @@ -25,8 +25,8 @@ import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; @@ -51,7 +51,7 @@ public Observable processMessage(RxDocumentServiceReq if (!Strings.isNullOrEmpty(requestConsistencyLevelHeaderValue)) { ConsistencyLevel requestConsistencyLevel; - if ((requestConsistencyLevel = EnumUtils.getEnum(ConsistencyLevel.class, requestConsistencyLevelHeaderValue)) == null) { + if ((requestConsistencyLevel = EnumUtils.getEnum(ConsistencyLevel.class, Strings.fromCamelCaseToUpperCase(requestConsistencyLevelHeaderValue))) == null) { return Observable.error(new BadRequestException( String.format( RMResources.InvalidHeaderValue, diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java index d2d3b0f26f073..31760f1dbfd67 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java @@ -25,21 +25,21 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.internal.InternalServerErrorException; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.SessionContainer; -import com.azure.data.cosmos.internal.SessionTokenHelper; import com.azure.data.cosmos.internal.BackoffRetryUtility; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.Exceptions; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.IRetryPolicy; +import com.azure.data.cosmos.internal.ISessionToken; +import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.SessionContainer; +import com.azure.data.cosmos.internal.SessionTokenHelper; import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.internal.Utils; import org.apache.commons.lang3.math.NumberUtils; @@ -176,7 +176,7 @@ private void updateResponseHeader(RxDocumentServiceRequest request, Map headers; - final private HttpResponseStatus status; - - public TransportException(HttpResponseStatus status, ObjectNode details, Map headers) { - - super("TODO: DANOBLE: format message string based on headers, and status information"); - this.error = BridgeInternal.createError(details); - this.headers = headers; - this.status = status; - } - - public Error getError() { - return error; - } - - public Map getHeaders() { - return headers; - } - - public HttpResponseStatus getStatus() { - return status; +// TODO: DANOBLE: Use a TransportException derivative wherever CorruptFrameException is thrown in RntbdTransportClient +// * Continue to throw IllegalArgumentException, IllegalStateException, and NullPointerException. +// * Continue to complete all pending requests with a GoneException. +// Customers should then expect to see these causes for GoneException errors originating in RntbdTransportClient: +// - TransportException +// - ReadTimeoutException +// - WriteTimeoutException +// These causes for GoneException errors will be logged as issues because they indicate a problem in the +// RntbdTransportClient code: +// - IllegalArgumentException +// - IllegalStateException +// - NullPointerException +// Any other exceptions caught by the RntbdTransportClient code will also be logged as issues because they +// indicate something unexpected happened. +// NOTES: +// We throw a derivative in one place: RntbdContextException in RntbdContext.decode. This is a special case +// that is handled by RntbdRequestManager.userEventTriggered. + +public class TransportException extends RuntimeException { + public TransportException(String message, Throwable cause) { + super(message, cause, /* enableSuppression */ true, /* writableStackTrace */ false); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelHandler.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelHandler.java new file mode 100644 index 0000000000000..198c8600feeb4 --- /dev/null +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelHandler.java @@ -0,0 +1,139 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.azure.data.cosmos.directconnectivity.rntbd; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.EventLoop; +import io.netty.channel.pool.ChannelPool; +import io.netty.channel.pool.ChannelPoolHandler; +import io.netty.handler.logging.LoggingHandler; +import io.netty.handler.ssl.SslHandler; +import io.netty.handler.timeout.ReadTimeoutHandler; +import io.netty.handler.timeout.WriteTimeoutHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.SSLEngine; +import java.util.concurrent.TimeUnit; + +import static com.google.common.base.Preconditions.checkNotNull; + +public class RntbdClientChannelHandler extends ChannelInitializer implements ChannelPoolHandler { + + private static Logger logger = LoggerFactory.getLogger(RntbdClientChannelHandler.class); + private final RntbdEndpoint.Config config; + + RntbdClientChannelHandler(final RntbdEndpoint.Config config) { + checkNotNull(config, "config"); + this.config = config; + } + + /** + * Called by {@link ChannelPool#acquire} after a {@link Channel} is acquired + *

+ * This method is called within the {@link EventLoop} of the {@link Channel}. + * + * @param channel a channel that was just acquired + */ + @Override + public void channelAcquired(final Channel channel) { + logger.trace("{} CHANNEL ACQUIRED", channel); + } + + /** + * Called by {@link ChannelPool#release} after a {@link Channel} is created + *

+ * This method is called within the {@link EventLoop} of the {@link Channel}. + * + * @param channel a channel that was just created + */ + @Override + public void channelCreated(final Channel channel) { + logger.trace("{} CHANNEL CREATED", channel); + this.initChannel(channel); + } + + /** + * Called by {@link ChannelPool#release} after a {@link Channel} is released + *

+ * This method is called within the {@link EventLoop} of the {@link Channel}. + * + * @param channel a channel that was just released + */ + @Override + public void channelReleased(final Channel channel) { + logger.trace("{} CHANNEL RELEASED", channel); + } + + /** + * Called by @{ChannelPipeline} initializer after the current channel is registered to an event loop. + *

+ * This method constructs this pipeline: + *

{@code
+     * ChannelPipeline {
+     *     (ReadTimeoutHandler#0 = io.netty.handler.timeout.ReadTimeoutHandler),
+     *     (SslHandler#0 = io.netty.handler.ssl.SslHandler),
+     *     (RntbdContextNegotiator#0 = com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdContextNegotiator),
+     *     (RntbdResponseDecoder#0 = com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdResponseDecoder),
+     *     (RntbdRequestEncoder#0 = com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdRequestEncoder),
+     *     (WriteTimeoutHandler#0 = io.netty.handler.timeout.WriteTimeoutHandler),
+     *     (RntbdRequestManager#0 = com.microsoft.azure.cosmosdb.internal.directconnectivity.rntbd.RntbdRequestManager),
+     * }
+     * }
+ * + * @param channel a channel that was just registered with an event loop + */ + @Override + protected void initChannel(final Channel channel) { + + checkNotNull(channel); + + final RntbdRequestManager requestManager = new RntbdRequestManager(this.config.getMaxRequestsPerChannel()); + final long readerIdleTime = this.config.getReceiveHangDetectionTime(); + final long writerIdleTime = this.config.getSendHangDetectionTime(); + final ChannelPipeline pipeline = channel.pipeline(); + + pipeline.addFirst( + new RntbdContextNegotiator(requestManager, this.config.getUserAgent()), + new RntbdResponseDecoder(), + new RntbdRequestEncoder(), + new WriteTimeoutHandler(writerIdleTime, TimeUnit.NANOSECONDS), + requestManager + ); + + if (this.config.getWireLogLevel() != null) { + pipeline.addFirst(new LoggingHandler(this.config.getWireLogLevel())); + } + + final SSLEngine sslEngine = this.config.getSslContext().newEngine(channel.alloc()); + + pipeline.addFirst( + new ReadTimeoutHandler(readerIdleTime, TimeUnit.NANOSECONDS), + new SslHandler(sslEngine) + ); + } +} diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelInitializer.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelInitializer.java deleted file mode 100644 index 01c1df430c9da..0000000000000 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelInitializer.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - * - */ - -package com.azure.data.cosmos.directconnectivity.rntbd; - -import com.azure.data.cosmos.internal.UserAgentContainer; -import com.azure.data.cosmos.directconnectivity.RntbdTransportClient.Options; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelPipeline; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.logging.LogLevel; -import io.netty.handler.logging.LoggingHandler; -import io.netty.handler.ssl.SslContext; -import io.netty.handler.ssl.SslHandler; - -import javax.net.ssl.SSLEngine; -import java.util.Objects; - -final public class RntbdClientChannelInitializer extends ChannelInitializer { - - private final LogLevel logLevel; - private final Options options; - private final RntbdRequestManager requestManager; - private final SslContext sslContext; - private final UserAgentContainer userAgent; - - public RntbdClientChannelInitializer( - UserAgentContainer userAgent, - SslContext sslContext, - LogLevel logLevel, - Options options - ) { - - Objects.requireNonNull(sslContext, "sslContext"); - Objects.requireNonNull(userAgent, "userAgent"); - Objects.requireNonNull(options, "options"); - - this.requestManager = new RntbdRequestManager(); - this.sslContext = sslContext; - this.userAgent = userAgent; - this.logLevel = logLevel; - this.options = options; - } - - public RntbdRequestManager getRequestManager() { - return this.requestManager; - } - - @Override - protected void initChannel(NioSocketChannel channel) { - - final ChannelPipeline pipeline = channel.pipeline(); - - pipeline.addFirst( - new RntbdContextNegotiator(this.requestManager, this.userAgent), - new RntbdResponseDecoder(), - new RntbdRequestEncoder(), - this.requestManager - ); - - if (this.logLevel != null) { - pipeline.addFirst(new LoggingHandler(this.logLevel)); - } - - final int readerIdleTime = (int)this.options.getReceiveHangDetectionTime().toNanos(); - final int writerIdleTime = (int)this.options.getSendHangDetectionTime().toNanos(); - final SSLEngine sslEngine = this.sslContext.newEngine(channel.alloc()); - - pipeline.addFirst( - // TODO: DANOBLE: Utilize READ/WriteTimeoutHandler for receive/send hang detection - // Links: - // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/331552 - // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/331593 - // Notes: - // First (naive?) attempt caused performance degradation - // new WriteTimeoutHandler(writerIdleTime), - // new ReadTimeoutHandler(readerIdleTime), - new SslHandler(sslEngine) - ); - } -} diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelPool.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelPool.java new file mode 100644 index 0000000000000..021c3e5a409f3 --- /dev/null +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelPool.java @@ -0,0 +1,266 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.azure.data.cosmos.directconnectivity.rntbd; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.pool.ChannelHealthChecker; +import io.netty.channel.pool.FixedChannelPool; +import io.netty.util.concurrent.Future; +import io.netty.util.concurrent.Promise; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.SocketAddress; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdReporter.reportIssue; +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdReporter.reportIssueUnless; +import static com.google.common.base.Preconditions.checkState; + +@JsonSerialize(using = RntbdClientChannelPool.JsonSerializer.class) +public final class RntbdClientChannelPool extends FixedChannelPool { + + // region Fields + + private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelPool.class); + private static final AtomicReference pendingAcquireCount = new AtomicReference<>(); + + private final AtomicInteger availableChannelCount; + private final AtomicBoolean closed; + private final int maxChannels; + private final int maxRequestsPerChannel; + + // endregion + + // region Methods + + /** + * Initializes a newly created {@link RntbdClientChannelPool} object + * + * @param bootstrap the {@link Bootstrap} that is used for connections + * @param config the {@link RntbdEndpoint.Config} that is used for the channel pool instance created + */ + RntbdClientChannelPool(final Bootstrap bootstrap, final RntbdEndpoint.Config config) { + + super(bootstrap, new RntbdClientChannelHandler(config), ChannelHealthChecker.ACTIVE, null, + -1L, config.getMaxChannelsPerEndpoint(), Integer.MAX_VALUE, true + ); + + this.maxRequestsPerChannel = config.getMaxRequestsPerChannel(); + this.maxChannels = config.getMaxChannelsPerEndpoint(); + this.availableChannelCount = new AtomicInteger(); + this.closed = new AtomicBoolean(); + } + + @Override + public Future acquire(Promise promise) { + this.throwIfClosed(); + return super.acquire(promise); + } + + @Override + public Future release(Channel channel, Promise promise) { + this.throwIfClosed(); + return super.release(channel, promise); + } + + @Override + public void close() { + if (this.closed.compareAndSet(false, true)) { + this.availableChannelCount.set(0); + super.close(); + } + } + + public int availableChannelCount() { + return this.availableChannelCount.get(); + } + + public int maxChannels() { + return this.maxChannels; + } + + public int maxRequestsPerChannel() { + return this.maxRequestsPerChannel; + } + + public int pendingAcquisitionCount() { + + Field field = pendingAcquireCount.get(); + + if (field == null) { + synchronized (pendingAcquireCount) { + field = pendingAcquireCount.get(); + if (field == null) { + field = FieldUtils.getDeclaredField(FixedChannelPool.class, "pendingAcquireCount", true); + pendingAcquireCount.set(field); + } + } + } + + try { + return (int)FieldUtils.readField(field, this); + } catch (IllegalAccessException error) { + reportIssue(logger, this, "could not access field due to ", error); + } + + return -1; + } + + /** + * Poll a {@link Channel} out of internal storage to reuse it + *

+ * Maintainers: Implementations of this method must be thread-safe and this type's base class, {@link FixedChannelPool}, + * ensures thread safety. It does this by calling this method serially on a single-threaded EventExecutor. As a + * result this method need not (and should not) be synchronized. + * + * @return a value of {@code null}, if no {@link Channel} is ready to be reused + * + * @see #acquire(Promise) + */ + @Override + protected Channel pollChannel() { + + final Channel first = super.pollChannel(); + + if (first == null) { + return null; + } + + if (this.closed.get()) { + return first; // because we're being called following a call to close (from super.close) + } + + if (this.isInactiveOrServiceableChannel(first)) { + return this.decrementAvailableChannelCountAndAccept(first); + } + + super.offerChannel(first); // because we need a non-null sentinel to stop the search for a channel + + for (Channel next = super.pollChannel(); next != first; super.offerChannel(next), next = super.pollChannel()) { + if (this.isInactiveOrServiceableChannel(next)) { + return this.decrementAvailableChannelCountAndAccept(next); + } + } + + super.offerChannel(first); // because we choose not to check any channel more than once in a single call + return null; + } + + /** + * Offer a {@link Channel} back to the internal storage + *

+ * Maintainers: Implementations of this method must be thread-safe. + * + * @param channel the {@link Channel} to return to internal storage + * @return {@code true}, if the {@link Channel} could be added to internal storage; otherwise {@code false} + */ + @Override + protected boolean offerChannel(final Channel channel) { + if (super.offerChannel(channel)) { + this.availableChannelCount.incrementAndGet(); + return true; + } + return false; + } + + public SocketAddress remoteAddress() { + return this.bootstrap().config().remoteAddress(); + } + + @Override + public String toString() { + return "RntbdClientChannelPool(" + RntbdObjectMapper.toJson(this) + ")"; + } + + // endregion + + // region Privates + + private Channel decrementAvailableChannelCountAndAccept(final Channel first) { + this.availableChannelCount.decrementAndGet(); + return first; + } + + private boolean isInactiveOrServiceableChannel(final Channel channel) { + + if (!channel.isActive()) { + return true; + } + + final RntbdRequestManager requestManager = channel.pipeline().get(RntbdRequestManager.class); + + if (requestManager == null) { + reportIssueUnless(!channel.isActive(), logger, this, "{} active with no request manager", channel); + return true; // inactive + } + + return requestManager.isServiceable(this.maxRequestsPerChannel); + } + + private void throwIfClosed() { + checkState(!this.closed.get(), "%s is closed", this); + } + + // endregion + + // region Types + + static final class JsonSerializer extends StdSerializer { + + public JsonSerializer() { + this(null); + } + + public JsonSerializer(Class type) { + super(type); + } + + @Override + public void serialize(RntbdClientChannelPool value, JsonGenerator generator, SerializerProvider provider) throws IOException { + generator.writeStartObject(); + generator.writeStringField("remoteAddress", value.remoteAddress().toString()); + generator.writeNumberField("maxChannels", value.maxChannels()); + generator.writeNumberField("maxRequestsPerChannel", value.maxRequestsPerChannel()); + generator.writeObjectFieldStart("state"); + generator.writeBooleanField("isClosed", value.closed.get()); + generator.writeNumberField("acquiredChannelCount", value.acquiredChannelCount()); + generator.writeNumberField("availableChannelCount", value.availableChannelCount()); + generator.writeNumberField("pendingAcquisitionCount", value.pendingAcquisitionCount()); + generator.writeEndObject(); + generator.writeEndObject(); + } + } +} diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdConstants.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdConstants.java index ecec351e39d14..14258b00e5d8e 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdConstants.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdConstants.java @@ -50,12 +50,12 @@ public enum RntbdConsistencyLevel { private final byte id; - RntbdConsistencyLevel(byte id) { + RntbdConsistencyLevel(final byte id) { this.id = id; } public byte id() { - return id; + return this.id; } } @@ -68,15 +68,16 @@ public enum RntbdContentSerializationFormat { private final byte id; - RntbdContentSerializationFormat(byte id) { + RntbdContentSerializationFormat(final byte id) { this.id = id; } public byte id() { - return id; + return this.id; } } + @SuppressWarnings("UnstableApiUsage") enum RntbdContextHeader implements RntbdHeader { ProtocolVersion((short)0x0000, RntbdTokenType.ULong, false), @@ -90,7 +91,7 @@ enum RntbdContextHeader implements RntbdHeader { public static final ImmutableSet set = Sets.immutableEnumSet(EnumSet.allOf(RntbdContextHeader.class)); static { - Collector> collector = ImmutableMap.toImmutableMap(RntbdContextHeader::id, h -> h); + final Collector> collector = ImmutableMap.toImmutableMap(RntbdContextHeader::id, h -> h); map = set.stream().collect(collector); } @@ -98,20 +99,20 @@ enum RntbdContextHeader implements RntbdHeader { private final boolean isRequired; private final RntbdTokenType type; - RntbdContextHeader(short id, RntbdTokenType type, boolean isRequired) { + RntbdContextHeader(final short id, final RntbdTokenType type, final boolean isRequired) { this.id = id; this.type = type; this.isRequired = isRequired; } - public short id() { - return this.id; - } - public boolean isRequired() { return this.isRequired; } + public short id() { + return this.id; + } + public RntbdTokenType type() { return this.type; } @@ -127,7 +128,7 @@ enum RntbdContextRequestHeader implements RntbdHeader { public static final ImmutableSet set = Sets.immutableEnumSet(EnumSet.allOf(RntbdContextRequestHeader.class)); static { - Collector> collector = ImmutableMap.toImmutableMap(h -> h.id(), h -> h); + final Collector> collector = ImmutableMap.toImmutableMap(h -> h.id(), h -> h); map = set.stream().collect(collector); } @@ -135,20 +136,20 @@ enum RntbdContextRequestHeader implements RntbdHeader { private final boolean isRequired; private final RntbdTokenType type; - RntbdContextRequestHeader(short id, RntbdTokenType type, boolean isRequired) { + RntbdContextRequestHeader(final short id, final RntbdTokenType type, final boolean isRequired) { this.id = id; this.type = type; this.isRequired = isRequired; } - public short id() { - return id; - } - public boolean isRequired() { return this.isRequired; } + public short id() { + return this.id; + } + public RntbdTokenType type() { return this.type; } @@ -163,12 +164,12 @@ public enum RntbdEnumerationDirection { private final byte id; - RntbdEnumerationDirection(byte id) { + RntbdEnumerationDirection(final byte id) { this.id = id; } public byte id() { - return id; + return this.id; } } @@ -179,12 +180,12 @@ public enum RntbdFanoutOperationState { private final byte id; - RntbdFanoutOperationState(byte id) { + RntbdFanoutOperationState(final byte id) { this.id = id; } public byte id() { - return id; + return this.id; } } @@ -197,11 +198,11 @@ enum RntbdIndexingDirective { private final byte id; - RntbdIndexingDirective(byte id) { + RntbdIndexingDirective(final byte id) { this.id = id; } - public static RntbdIndexingDirective fromId(byte id) { + public static RntbdIndexingDirective fromId(final byte id) { switch (id) { case (byte)0x00: return Default; @@ -216,7 +217,7 @@ public static RntbdIndexingDirective fromId(byte id) { } public byte id() { - return id; + return this.id; } } @@ -229,12 +230,12 @@ public enum RntbdMigrateCollectionDirective { private final byte id; - RntbdMigrateCollectionDirective(byte id) { + RntbdMigrateCollectionDirective(final byte id) { this.id = id; } public byte id() { - return id; + return this.id; } } @@ -278,11 +279,11 @@ enum RntbdOperationType { private final short id; - RntbdOperationType(short id) { + RntbdOperationType(final short id) { this.id = id; } - public static RntbdOperationType fromId(short id) throws IllegalArgumentException { + public static RntbdOperationType fromId(final short id) throws IllegalArgumentException { switch (id) { case 0x0000: @@ -359,7 +360,7 @@ public static RntbdOperationType fromId(short id) throws IllegalArgumentExceptio } public short id() { - return id; + return this.id; } } @@ -371,12 +372,12 @@ public enum RntbdReadFeedKeyType { private final byte id; - RntbdReadFeedKeyType(byte id) { + RntbdReadFeedKeyType(final byte id) { this.id = id; } public byte id() { - return id; + return this.id; } } @@ -389,12 +390,12 @@ public enum RntbdRemoteStorageType { private final byte id; - RntbdRemoteStorageType(byte id) { + RntbdRemoteStorageType(final byte id) { this.id = id; } public byte id() { - return id; + return this.id; } } @@ -510,7 +511,7 @@ public enum RntbdRequestHeader implements RntbdHeader { public static final ImmutableSet set = Sets.immutableEnumSet(EnumSet.allOf(RntbdRequestHeader.class)); static { - Collector> collector = ImmutableMap.toImmutableMap(RntbdRequestHeader::id, h -> h); + final Collector> collector = ImmutableMap.toImmutableMap(RntbdRequestHeader::id, h -> h); map = set.stream().collect(collector); } @@ -518,20 +519,20 @@ public enum RntbdRequestHeader implements RntbdHeader { private final boolean isRequired; private final RntbdTokenType type; - RntbdRequestHeader(short id, RntbdTokenType type, boolean isRequired) { + RntbdRequestHeader(final short id, final RntbdTokenType type, final boolean isRequired) { this.id = id; this.type = type; this.isRequired = isRequired; } - public short id() { - return this.id; - } - public boolean isRequired() { return this.isRequired; } + public short id() { + return this.id; + } + public RntbdTokenType type() { return this.type; } @@ -572,11 +573,11 @@ enum RntbdResourceType { private final short id; - RntbdResourceType(short id) { + RntbdResourceType(final short id) { this.id = id; } - public static RntbdResourceType fromId(short id) throws IllegalArgumentException { + public static RntbdResourceType fromId(final short id) throws IllegalArgumentException { switch (id) { case 0x0000: return RntbdResourceType.Connection; @@ -642,7 +643,7 @@ public static RntbdResourceType fromId(short id) throws IllegalArgumentException } public short id() { - return id; + return this.id; } } @@ -710,7 +711,7 @@ public enum RntbdResponseHeader implements RntbdHeader { public static final ImmutableSet set = Sets.immutableEnumSet(EnumSet.allOf(RntbdResponseHeader.class)); static { - Collector> collector = ImmutableMap.toImmutableMap(RntbdResponseHeader::id, header -> header); + final Collector> collector = ImmutableMap.toImmutableMap(RntbdResponseHeader::id, header -> header); map = set.stream().collect(collector); } @@ -718,20 +719,20 @@ public enum RntbdResponseHeader implements RntbdHeader { private final boolean isRequired; private final RntbdTokenType type; - RntbdResponseHeader(short id, RntbdTokenType type, boolean isRequired) { + RntbdResponseHeader(final short id, final RntbdTokenType type, final boolean isRequired) { this.id = id; this.type = type; this.isRequired = isRequired; } - public short id() { - return this.id; - } - public boolean isRequired() { return this.isRequired; } + public short id() { + return this.id; + } + public RntbdTokenType type() { return this.type; } @@ -739,10 +740,10 @@ public RntbdTokenType type() { interface RntbdHeader { - short id(); - boolean isRequired(); + short id(); + String name(); RntbdTokenType type(); diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContext.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContext.java index 3c51ce1bddd8f..a826b3d29fad3 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContext.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContext.java @@ -24,14 +24,11 @@ package com.azure.data.cosmos.directconnectivity.rntbd; +import com.azure.data.cosmos.directconnectivity.ServerProperties; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.azure.data.cosmos.directconnectivity.ServerProperties; -import com.azure.data.cosmos.directconnectivity.TransportException; import io.netty.buffer.ByteBuf; -import io.netty.handler.codec.CorruptedFrameException; import io.netty.handler.codec.http.HttpResponseStatus; import java.util.Collections; @@ -40,19 +37,63 @@ import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.CurrentProtocolVersion; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdContextHeader; +import static com.google.common.base.Preconditions.checkState; -final public class RntbdContext { - - final private RntbdResponseStatus frame; - final private Headers headers; +public final class RntbdContext { - private RntbdContext(RntbdResponseStatus frame, Headers headers) { + private final RntbdResponseStatus frame; + private final Headers headers; + private ServerProperties serverProperties; + private RntbdContext(final RntbdResponseStatus frame, final Headers headers) { this.frame = frame; this.headers = headers; } - static RntbdContext decode(ByteBuf in) throws TransportException { + @JsonProperty + public UUID getActivityId() { + return this.frame.getActivityId(); + } + + @JsonProperty + public String getClientVersion() { + return this.headers.clientVersion.getValue(String.class); + } + + @JsonProperty + public long getIdleTimeoutInSeconds() { + return this.headers.idleTimeoutInSeconds.getValue(Long.class); + } + + @JsonProperty + public int getProtocolVersion() { + return this.headers.protocolVersion.getValue(Long.class).intValue(); + } + + @JsonProperty + public ServerProperties getServerProperties() { + return this.serverProperties == null ? (this.serverProperties = new ServerProperties( + this.headers.serverAgent.getValue(String.class), + this.headers.serverVersion.getValue(String.class)) + ) : this.serverProperties; + } + + @JsonIgnore + public String getServerVersion() { + return this.headers.serverVersion.getValue(String.class); + } + + @JsonProperty + public int getStatusCode() { + return this.frame.getStatusCode(); + } + + @JsonProperty + public long getUnauthenticatedTimeoutInSeconds() { + return this.headers.unauthenticatedTimeoutInSeconds.getValue(Long.class); + } + + public static RntbdContext decode(final ByteBuf in) { in.markReaderIndex(); @@ -71,7 +112,7 @@ static RntbdContext decode(ByteBuf in) throws TransportException { if (statusCode < 200 || statusCode >= 400) { - final ObjectNode details = (ObjectNode)RntbdObjectMapper.readTree(in.readSlice(in.readIntLE())); + final ObjectNode details = RntbdObjectMapper.readTree(in.readSlice(in.readIntLE())); final HashMap map = new HashMap<>(4); if (headers.clientVersion.isPresent()) { @@ -90,13 +131,24 @@ static RntbdContext decode(ByteBuf in) throws TransportException { map.put("serverVersion", headers.serverVersion.getValue()); } - throw new TransportException(frame.getStatus(), details, Collections.unmodifiableMap(map)); + throw new RntbdContextException(frame.getStatus(), details, Collections.unmodifiableMap(map)); } return new RntbdContext(frame, headers); } - public static RntbdContext from(RntbdContextRequest request, ServerProperties properties, HttpResponseStatus status) { + public void encode(final ByteBuf out) { + + final int start = out.writerIndex(); + + this.frame.encode(out); + this.headers.encode(out); + + final int length = out.writerIndex() - start; + checkState(length == this.frame.getLength()); + } + + public static RntbdContext from(final RntbdContextRequest request, final ServerProperties properties, final HttpResponseStatus status) { // NOTE TO CODE REVIEWERS // ---------------------- @@ -120,73 +172,12 @@ public static RntbdContext from(RntbdContextRequest request, ServerProperties pr return new RntbdContext(frame, headers); } - @JsonProperty - UUID getActivityId() { - return this.frame.getActivityId(); - } - - @JsonProperty - String getClientVersion() { - return this.headers.clientVersion.getValue(String.class); - } - - @JsonProperty - long getIdleTimeoutInSeconds() { - return this.headers.idleTimeoutInSeconds.getValue(Long.class); - } - - @JsonProperty - int getProtocolVersion() { - return this.headers.protocolVersion.getValue(Long.class).intValue(); - } - - @JsonProperty - ServerProperties getServerProperties() { - return new ServerProperties( - this.headers.serverAgent.getValue(String.class), - this.headers.serverVersion.getValue(String.class) - ); - } - - String getServerVersion() { - return this.headers.serverVersion.getValue(String.class); - } - - @JsonProperty - int getStatusCode() { - return this.frame.getStatusCode(); - } - - @JsonProperty - long getUnauthenticatedTimeoutInSeconds() { - return this.headers.unauthenticatedTimeoutInSeconds.getValue(Long.class); - } - - public void encode(ByteBuf out) { - - int start = out.writerIndex(); - - this.frame.encode(out); - this.headers.encode(out); - - int length = out.writerIndex() - start; - - if (length != this.frame.getLength()) { - throw new IllegalStateException(); - } - } - @Override public String toString() { - ObjectWriter writer = RntbdObjectMapper.writer(); - try { - return writer.writeValueAsString(this); - } catch (JsonProcessingException error) { - throw new CorruptedFrameException(error); - } + return RntbdObjectMapper.toJson(this); } - final private static class Headers extends RntbdTokenStream { + private static final class Headers extends RntbdTokenStream { RntbdToken clientVersion; RntbdToken idleTimeoutInSeconds; @@ -207,8 +198,8 @@ final private static class Headers extends RntbdTokenStream this.unauthenticatedTimeoutInSeconds = this.get(RntbdContextHeader.UnauthenticatedTimeoutInSeconds); } - static Headers decode(ByteBuf in) { - Headers headers = new Headers(); + static Headers decode(final ByteBuf in) { + final Headers headers = new Headers(); Headers.decode(in, headers); return headers; } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextDecoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextDecoder.java index 52c5c48e6f5a4..46d9f49e85405 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextDecoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextDecoder.java @@ -34,29 +34,36 @@ class RntbdContextDecoder extends ByteToMessageDecoder { - final private static Logger logger = LoggerFactory.getLogger("RntbdContextDecoder"); + private static final Logger logger = LoggerFactory.getLogger(RntbdContextDecoder.class); /** * Deserialize from an input {@link ByteBuf} to an {@link RntbdContext} instance *

- * This method fulfills the promise of an {@link RntbdContext} instance. It does not pass the instance down the - * pipeline. + * This method decodes an {@link RntbdContext} or {@link RntbdContextException} instance and fires a user event. * - * @param context the {@link ChannelHandlerContext} to which this {@link ByteToMessageDecoder} belongs + * @param context the {@link ChannelHandlerContext} to which this {@link RntbdContextDecoder} belongs * @param in the {@link ByteBuf} from which to readTree data * @param out the {@link List} to which decoded messages should be added - * @throws Exception thrown if an error occurs */ @Override - protected void decode(ChannelHandlerContext context, ByteBuf in, List out) throws Exception { + protected void decode(final ChannelHandlerContext context, final ByteBuf in, final List out) { if (RntbdFramer.canDecodeHead(in)) { - RntbdContext rntbdContext = RntbdContext.decode(in); - context.fireUserEventTriggered(rntbdContext); - in.discardReadBytes(); + Object result; - logger.debug("{} DECODE COMPLETE: {}", context.channel(), rntbdContext); + try { + final RntbdContext rntbdContext = RntbdContext.decode(in); + context.fireUserEventTriggered(rntbdContext); + result = rntbdContext; + } catch (RntbdContextException error) { + context.fireUserEventTriggered(error); + result = error; + } finally { + in.discardReadBytes(); + } + + logger.debug("{} DECODE COMPLETE: {}", context.channel(), result); } } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java new file mode 100644 index 0000000000000..cfa1fa43c8a2a --- /dev/null +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java @@ -0,0 +1,61 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.azure.data.cosmos.directconnectivity.rntbd; + +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.directconnectivity.TransportException; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.netty.handler.codec.http.HttpResponseStatus; + +import java.util.Map; + +public final class RntbdContextException extends TransportException { + + final private Error error; + final private Map responseHeaders; + final private HttpResponseStatus status; + + RntbdContextException(HttpResponseStatus status, ObjectNode details, Map responseHeaders) { + + super(status + ": " + details, null); + + this.error = BridgeInternal.createError(details); + this.responseHeaders = responseHeaders; + this.status = status; + } + + public Error getError() { + return error; + } + + public Map getResponseHeaders() { + return responseHeaders; + } + + public HttpResponseStatus getStatus() { + return status; + } +} \ No newline at end of file diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextNegotiator.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextNegotiator.java index f1e4ae6fc33cf..2cf24b7678c77 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextNegotiator.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextNegotiator.java @@ -25,6 +25,7 @@ package com.azure.data.cosmos.directconnectivity.rntbd; import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.Utils; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; @@ -35,11 +36,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Objects; -import java.util.UUID; import java.util.concurrent.CompletableFuture; -final public class RntbdContextNegotiator extends CombinedChannelDuplexHandler { +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +public final class RntbdContextNegotiator extends CombinedChannelDuplexHandler { private static final Logger logger = LoggerFactory.getLogger(RntbdContextNegotiator.class); private final RntbdRequestManager manager; @@ -47,12 +49,12 @@ final public class RntbdContextNegotiator extends CombinedChannelDuplexHandler contextRequestFuture = this.manager.getRntbdContextRequestFuture(); super.write(context, request, channel.newPromise().addListener((ChannelFutureListener)future -> { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequest.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequest.java index 160a4c7f71ca9..26b2eb117596d 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequest.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequest.java @@ -24,58 +24,66 @@ package com.azure.data.cosmos.directconnectivity.rntbd; +import com.azure.data.cosmos.internal.UserAgentContainer; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectWriter; -import com.azure.data.cosmos.internal.UserAgentContainer; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.CorruptedFrameException; import java.nio.charset.StandardCharsets; import java.util.UUID; -import static com.azure.data.cosmos.internal.HttpConstants.Versions; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.CurrentProtocolVersion; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdContextRequestHeader; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResourceType; +import static com.azure.data.cosmos.internal.HttpConstants.Versions; -final public class RntbdContextRequest { +public final class RntbdContextRequest { @JsonProperty - final private UUID activityId; + private final UUID activityId; @JsonProperty - final private Headers headers; + private final Headers headers; - RntbdContextRequest(UUID activityId, UserAgentContainer userAgent) { + RntbdContextRequest(final UUID activityId, final UserAgentContainer userAgent) { this(activityId, new Headers(userAgent)); } - private RntbdContextRequest(UUID activityId, Headers headers) { + private RntbdContextRequest(final UUID activityId, final Headers headers) { this.activityId = activityId; this.headers = headers; } - public static RntbdContextRequest decode(ByteBuf in) { + public UUID getActivityId() { + return this.activityId; + } + + public String getClientVersion() { + return this.headers.clientVersion.getValue(String.class); + } + + public static RntbdContextRequest decode(final ByteBuf in) { - int resourceOperationTypeCode = in.getInt(in.readerIndex() + Integer.BYTES); + final int resourceOperationTypeCode = in.getInt(in.readerIndex() + Integer.BYTES); if (resourceOperationTypeCode != 0) { - String reason = String.format("resourceOperationCode=0x%08X", resourceOperationTypeCode); + final String reason = String.format("resourceOperationCode=0x%08X", resourceOperationTypeCode); throw new IllegalStateException(reason); } - int start = in.readerIndex(); - int expectedLength = in.readIntLE(); + final int start = in.readerIndex(); + final int expectedLength = in.readIntLE(); - RntbdRequestFrame header = RntbdRequestFrame.decode(in); - Headers headers = Headers.decode(in.readSlice(expectedLength - (in.readerIndex() - start))); + final RntbdRequestFrame header = RntbdRequestFrame.decode(in); + final Headers headers = Headers.decode(in.readSlice(expectedLength - (in.readerIndex() - start))); - int observedLength = in.readerIndex() - start; + final int observedLength = in.readerIndex() - start; if (observedLength != expectedLength) { - String reason = String.format("expectedLength=%d, observeredLength=%d", expectedLength, observedLength); + final String reason = String.format("expectedLength=%d, observeredLength=%d", expectedLength, observedLength); throw new IllegalStateException(reason); } @@ -83,46 +91,38 @@ public static RntbdContextRequest decode(ByteBuf in) { return new RntbdContextRequest(header.getActivityId(), headers); } - public UUID getActivityId() { - return activityId; - } - - public String getClientVersion() { - return this.headers.clientVersion.getValue(String.class); - } - - public void encode(ByteBuf out) { + public void encode(final ByteBuf out) { - int expectedLength = RntbdRequestFrame.LENGTH + headers.computeLength(); - int start = out.writerIndex(); + final int expectedLength = RntbdRequestFrame.LENGTH + this.headers.computeLength(); + final int start = out.writerIndex(); out.writeIntLE(expectedLength); - RntbdRequestFrame header = new RntbdRequestFrame(this.getActivityId(), RntbdOperationType.Connection, RntbdResourceType.Connection); + final RntbdRequestFrame header = new RntbdRequestFrame(this.getActivityId(), RntbdOperationType.Connection, RntbdResourceType.Connection); header.encode(out); this.headers.encode(out); - int observedLength = out.writerIndex() - start; + final int observedLength = out.writerIndex() - start; if (observedLength != expectedLength) { - String reason = String.format("expectedLength=%d, observeredLength=%d", expectedLength, observedLength); + final String reason = String.format("expectedLength=%d, observeredLength=%d", expectedLength, observedLength); throw new IllegalStateException(reason); } } @Override public String toString() { - ObjectWriter writer = RntbdObjectMapper.writer(); + final ObjectWriter writer = RntbdObjectMapper.writer(); try { return writer.writeValueAsString(this); - } catch (JsonProcessingException error) { + } catch (final JsonProcessingException error) { throw new CorruptedFrameException(error); } } - final private static class Headers extends RntbdTokenStream { + private static final class Headers extends RntbdTokenStream { - private final static byte[] ClientVersion = Versions.CURRENT_VERSION.getBytes(StandardCharsets.UTF_8); + private static final byte[] ClientVersion = Versions.CURRENT_VERSION.getBytes(StandardCharsets.UTF_8); @JsonProperty RntbdToken clientVersion; @@ -133,7 +133,7 @@ final private static class Headers extends RntbdTokenStream out) throws IllegalStateException { + protected void decode(final ChannelHandlerContext context, final ByteBuf in, final List out) throws IllegalStateException { - RntbdContextRequest request; + final RntbdContextRequest request; in.markReaderIndex(); try { request = RntbdContextRequest.decode(in); - } catch (IllegalStateException error) { + } catch (final IllegalStateException error) { in.resetReaderIndex(); throw error; } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestEncoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestEncoder.java index 9920e172a64dd..1df05d5031b4a 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestEncoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestEncoder.java @@ -32,7 +32,7 @@ final class RntbdContextRequestEncoder extends MessageToByteEncoder { - final private static Logger Logger = LoggerFactory.getLogger(RntbdContextRequestEncoder.class); + private static final Logger Logger = LoggerFactory.getLogger(RntbdContextRequestEncoder.class); /** * Returns {@code true} if the given message is an @{link RntbdContextRequest} instance @@ -41,10 +41,9 @@ final class RntbdContextRequestEncoder extends MessageToByteEncoder { * * @param message the message to encode * @return @{code true}, if the given message is an an @{link RntbdContextRequest} instance; otherwise @{false} - * @throws Exception thrown if an error occurs */ @Override - public boolean acceptOutboundMessage(Object message) throws Exception { + public boolean acceptOutboundMessage(final Object message) { return message instanceof RntbdContextRequest; } @@ -59,14 +58,14 @@ public boolean acceptOutboundMessage(Object message) throws Exception { * @throws IllegalStateException is thrown if an error occurs */ @Override - protected void encode(ChannelHandlerContext context, Object message, ByteBuf out) throws IllegalStateException { + protected void encode(final ChannelHandlerContext context, final Object message, final ByteBuf out) throws IllegalStateException { - RntbdContextRequest request = (RntbdContextRequest)message; + final RntbdContextRequest request = (RntbdContextRequest)message; out.markWriterIndex(); try { request.encode(out); - } catch (IllegalStateException error) { + } catch (final IllegalStateException error) { out.resetWriterIndex(); throw error; } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdEndpoint.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdEndpoint.java new file mode 100644 index 0000000000000..ed5e4f89fcb7a --- /dev/null +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdEndpoint.java @@ -0,0 +1,119 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.azure.data.cosmos.directconnectivity.rntbd; + +import com.azure.data.cosmos.internal.UserAgentContainer; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.ssl.SslContext; + +import java.net.URI; +import java.util.stream.Stream; + +import static com.azure.data.cosmos.directconnectivity.RntbdTransportClient.Options; +import static com.google.common.base.Preconditions.checkNotNull; + +public interface RntbdEndpoint extends AutoCloseable { + + String getName(); + + @Override + void close() throws RuntimeException; + + RntbdRequestRecord request(RntbdRequestArgs requestArgs); + + interface Provider extends AutoCloseable { + + @Override + void close() throws RuntimeException; + + Config config(); + + int count(); + + RntbdEndpoint get(URI physicalAddress); + + Stream list(); + } + + final class Config { + + private final Options options; + private final SslContext sslContext; + private final LogLevel wireLogLevel; + + public Config(final Options options, final SslContext sslContext, final LogLevel wireLogLevel) { + + checkNotNull(options, "options"); + checkNotNull(sslContext, "sslContext"); + + this.options = options; + this.sslContext = sslContext; + this.wireLogLevel = wireLogLevel; + } + + public int getConnectionTimeout() { + final long value = this.options.getConnectionTimeout().toMillis(); + assert value <= Integer.MAX_VALUE; + return (int)value; + } + + public int getMaxChannelsPerEndpoint() { + return this.options.getMaxChannelsPerEndpoint(); + } + + public int getMaxRequestsPerChannel() { + return this.options.getMaxRequestsPerChannel(); + } + + public long getReceiveHangDetectionTime() { + return this.options.getReceiveHangDetectionTime().toNanos(); + } + + public long getRequestTimeout() { + return this.options.getRequestTimeout().toNanos(); + } + + public long getSendHangDetectionTime() { + return this.options.getSendHangDetectionTime().toNanos(); + } + + public SslContext getSslContext() { + return this.sslContext; + } + + public UserAgentContainer getUserAgent() { + return this.options.getUserAgent(); + } + + public LogLevel getWireLogLevel() { + return this.wireLogLevel; + } + + @Override + public String toString() { + return RntbdObjectMapper.toJson(this); + } + } +} diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdFramer.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdFramer.java index bdaad39d0f65f..271fadcb9912f 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdFramer.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdFramer.java @@ -27,70 +27,70 @@ import io.netty.buffer.ByteBuf; import io.netty.handler.codec.CorruptedFrameException; -import java.util.Objects; +import static com.google.common.base.Preconditions.checkNotNull; final class RntbdFramer { private RntbdFramer() { } - static boolean canDecodePayload(ByteBuf in) { - return canDecodePayload(in, in.readerIndex()); - } - - static boolean canDecodePayload(ByteBuf in, int start) { - - Objects.requireNonNull(in); - - int readerIndex = in.readerIndex(); - - if (start < readerIndex) { - throw new IllegalArgumentException("start < in.readerIndex()"); - } + static boolean canDecodeHead(final ByteBuf in) throws CorruptedFrameException { - int offset = start - readerIndex; + checkNotNull(in, "in"); - if (in.readableBytes() - offset < Integer.BYTES) { + if (in.readableBytes() < RntbdResponseStatus.LENGTH) { return false; } - long length = in.getUnsignedIntLE(start); + final int start = in.readerIndex(); + final long length = in.getUnsignedIntLE(start); if (length > Integer.MAX_VALUE) { - String reason = String.format("Payload frame length exceeds Integer.MAX_VALUE, %d: %d", + final String reason = String.format("Head frame length exceeds Integer.MAX_VALUE, %d: %d", Integer.MAX_VALUE, length ); throw new CorruptedFrameException(reason); } - return offset + Integer.BYTES + length <= in.readableBytes(); + if (length < Integer.BYTES) { + final String reason = String.format("Head frame length is less than size of length field, %d: %d", + Integer.BYTES, length + ); + throw new CorruptedFrameException(reason); + } + + return length <= in.readableBytes(); } - static boolean canDecodeHead(ByteBuf in) throws CorruptedFrameException { + static boolean canDecodePayload(final ByteBuf in, final int start) { - Objects.requireNonNull(in); + checkNotNull(in, "in"); - if (in.readableBytes() < RntbdResponseStatus.LENGTH) { + final int readerIndex = in.readerIndex(); + + if (start < readerIndex) { + throw new IllegalArgumentException("start < in.readerIndex()"); + } + + final int offset = start - readerIndex; + + if (in.readableBytes() - offset < Integer.BYTES) { return false; } - int start = in.readerIndex(); - long length = in.getUnsignedIntLE(start); + final long length = in.getUnsignedIntLE(start); if (length > Integer.MAX_VALUE) { - String reason = String.format("Head frame length exceeds Integer.MAX_VALUE, %d: %d", + final String reason = String.format("Payload frame length exceeds Integer.MAX_VALUE, %d: %d", Integer.MAX_VALUE, length ); throw new CorruptedFrameException(reason); } - if (length < Integer.BYTES) { - String reason = String.format("Head frame length is less than size of length field, %d: %d", - Integer.BYTES, length - ); - throw new CorruptedFrameException(reason); - } + return offset + Integer.BYTES + length <= in.readableBytes(); + } - return length <= in.readableBytes(); + static boolean canDecodePayload(final ByteBuf in) { + return canDecodePayload(in, in.readerIndex()); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdMetrics.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdMetrics.java new file mode 100644 index 0000000000000..a5a04a23ad00a --- /dev/null +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdMetrics.java @@ -0,0 +1,159 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.azure.data.cosmos.directconnectivity.rntbd; + +import com.codahale.metrics.Gauge; +import com.codahale.metrics.Meter; +import com.codahale.metrics.MetricFilter; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.RatioGauge; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.google.common.base.Stopwatch; + +import java.time.Duration; + +@JsonPropertyOrder({ + "lifetime", "requests", "responses", "errorResponses", "responseRate", "completionRate", "throughput" +}) +public final class RntbdMetrics implements AutoCloseable { + + // region Fields + + private static final MetricRegistry registry = new MetricRegistry(); + + private final Gauge completionRate; + private final Meter errorResponses; + private final Stopwatch lifetime; + private final String prefix; + private final Meter requests; + private final Gauge responseRate; + private final Meter responses; + + // endregion + + // region Constructors + + public RntbdMetrics(final String name) { + + this.lifetime = Stopwatch.createStarted(); + this.prefix = name + '.'; + + this.requests = registry.register(this.prefix + "requests", new Meter()); + this.responses = registry.register(this.prefix + "responses", new Meter()); + this.errorResponses = registry.register(this.prefix + "errorResponses", new Meter()); + this.responseRate = registry.register(this.prefix + "responseRate", new ResponseRate(this)); + this.completionRate = registry.register(this.prefix + "completionRate", new CompletionRate(this)); + } + + // endregion + + // region Accessors + + public double getCompletionRate() { + return this.completionRate.getValue(); + } + + public long getErrorResponses() { + return this.errorResponses.getCount(); + } + + public double getLifetime() { + final Duration elapsed = this.lifetime.elapsed(); + return elapsed.getSeconds() + (1E-9D * elapsed.getNano()); + } + + public long getRequests() { + return this.requests.getCount(); + } + + public double getResponseRate() { + return this.responseRate.getValue(); + } + + public long getResponses() { + return this.responses.getCount(); + } + + public double getThroughput() { + return this.responses.getMeanRate(); + } + + // endregion + + // region Methods + + @Override + public void close() { + registry.removeMatching(MetricFilter.startsWith(this.prefix)); + } + + public final void incrementErrorResponseCount() { + this.errorResponses.mark(); + } + + public final void incrementRequestCount() { + this.requests.mark(); + } + + public final void incrementResponseCount() { + this.responses.mark(); + } + + @Override + public String toString() { + return RntbdObjectMapper.toJson(this); + } + + // endregion + + private static final class CompletionRate extends RatioGauge { + + private final RntbdMetrics metrics; + + private CompletionRate(RntbdMetrics metrics) { + this.metrics = metrics; + } + + @Override + protected Ratio getRatio() { + return Ratio.of(this.metrics.responses.getCount() - this.metrics.errorResponses.getCount(), + this.metrics.requests.getCount()); + } + } + + private static final class ResponseRate extends RatioGauge { + + private final RntbdMetrics metrics; + + private ResponseRate(RntbdMetrics metrics) { + this.metrics = metrics; + } + + @Override + protected Ratio getRatio() { + return Ratio.of(this.metrics.responses.getCount(), this.metrics.requests.getCount()); + } + } +} diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdObjectMapper.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdObjectMapper.java index 6c6b8c280083b..62fcba8dec08f 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdObjectMapper.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdObjectMapper.java @@ -24,60 +24,83 @@ package com.azure.data.cosmos.directconnectivity.rntbd; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.node.JsonNodeType; +import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.ser.PropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.handler.codec.CorruptedFrameException; +import io.netty.handler.codec.EncoderException; import java.io.IOException; import java.io.InputStream; -import java.util.Objects; -class RntbdObjectMapper { +import static com.google.common.base.Preconditions.checkNotNull; - private static final SimpleFilterProvider propertyFilterProvider = new SimpleFilterProvider(); - private static final ObjectMapper objectMapper = new ObjectMapper().setFilterProvider(propertyFilterProvider); - private static volatile ObjectWriter objectWriter = null; +public final class RntbdObjectMapper { + + private static final SimpleFilterProvider filterProvider; + private static final ObjectMapper objectMapper; + private static final ObjectWriter objectWriter; + + static { + objectMapper = new ObjectMapper().setFilterProvider(filterProvider = new SimpleFilterProvider()); + objectWriter = objectMapper.writer(); + } private RntbdObjectMapper() { } - static JsonNode readTree(ByteBuf in) { + static ObjectNode readTree(final RntbdResponse response) { + checkNotNull(response, "response"); + return readTree(response.getContent()); + } - Objects.requireNonNull(in, "in"); - InputStream istream = new ByteBufInputStream(in); + static ObjectNode readTree(final ByteBuf in) { - try { - return objectMapper.readTree(istream); - } catch (IOException error) { + checkNotNull(in, "in"); + final JsonNode node; + + try (final InputStream istream = new ByteBufInputStream(in)) { + node = objectMapper.readTree(istream); + } catch (final IOException error) { throw new CorruptedFrameException(error); } + + if (node.isObject()) { + return (ObjectNode)node; + } + + final String cause = String.format("Expected %s, not %s", JsonNodeType.OBJECT, node.getNodeType()); + throw new CorruptedFrameException(cause); } - static void registerPropertyFilter(Class type, Class filter) { + static void registerPropertyFilter(final Class type, final Class filter) { - Objects.requireNonNull(type, "type"); - Objects.requireNonNull(filter, "filter"); + checkNotNull(type, "type"); + checkNotNull(filter, "filter"); try { - propertyFilterProvider.addFilter(type.getSimpleName(), filter.newInstance()); - } catch (ReflectiveOperationException error) { + filterProvider.addFilter(type.getSimpleName(), filter.newInstance()); + } catch (final ReflectiveOperationException error) { throw new IllegalStateException(error); } } - static ObjectWriter writer() { - if (objectWriter == null) { - synchronized (objectMapper) { - if (objectWriter == null) { - objectWriter = objectMapper.writer(); - } - } + public static String toJson(Object value) { + try { + return objectWriter.writeValueAsString(value); + } catch (final JsonProcessingException error) { + throw new EncoderException(error); } + } + + public static ObjectWriter writer() { return objectWriter; } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdReporter.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdReporter.java new file mode 100644 index 0000000000000..d6f01112287f5 --- /dev/null +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdReporter.java @@ -0,0 +1,85 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.azure.data.cosmos.directconnectivity.rntbd; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.slf4j.Logger; +import org.slf4j.helpers.FormattingTuple; +import org.slf4j.helpers.MessageFormatter; + +import java.io.File; +import java.net.URL; + +public final class RntbdReporter { + + private static final String codeSource; + + static { + String value; + try { + URL url = RntbdReporter.class.getProtectionDomain().getCodeSource().getLocation(); + File file = new File(url.toURI()); + value = file.getName(); + } catch (Throwable error) { + value = "azure-cosmosdb-direct"; + } + codeSource = value; + } + + private RntbdReporter() { + } + + public static void reportIssue(Logger logger, Object subject, String format, Object... arguments) { + if (logger.isErrorEnabled()) { + doReportIssue(logger, subject, format, arguments); + } + } + + public static void reportIssueUnless( + boolean predicate, Logger logger, Object subject, String format, Object... arguments + ) { + if (!predicate && logger.isErrorEnabled()) { + doReportIssue(logger, subject, format, arguments); + } + } + + private static void doReportIssue(Logger logger, Object subject, String format, Object[] arguments) { + + FormattingTuple formattingTuple = MessageFormatter.arrayFormat(format, arguments); + StackTraceElement[] stackTraceElements = new Exception().getStackTrace(); + Throwable throwable = formattingTuple.getThrowable(); + + if (throwable == null) { + logger.error("Report this {} issue to ensure it is addressed:\n[{}]\n[{}]\n[{}]", + codeSource, subject, stackTraceElements[2], formattingTuple.getMessage() + ); + } else { + logger.error("Report this {} issue to ensure it is addressed:\n[{}]\n[{}]\n[{}{}{}]", + codeSource, subject, stackTraceElements[2], formattingTuple.getMessage(), + throwable, ExceptionUtils.getStackTrace(throwable) + ); + } + } +} diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequest.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequest.java index 5925eb6081ca9..3658385650684 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequest.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequest.java @@ -25,81 +25,80 @@ package com.azure.data.cosmos.directconnectivity.rntbd; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.fasterxml.jackson.annotation.JsonIgnore; import io.netty.buffer.ByteBuf; -import java.util.Objects; import java.util.UUID; -final public class RntbdRequest { +import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdRequestHeader; +import static com.google.common.base.Preconditions.checkNotNull; - final private static byte[] EmptyByteArray = {}; +public final class RntbdRequest { - final private RntbdRequestFrame frame; - final private RntbdRequestHeaders headers; - final private byte[] payload; + private static final byte[] EmptyByteArray = {}; - private RntbdRequest(RntbdRequestFrame frame, RntbdRequestHeaders headers, byte[] payload) { + private final RntbdRequestFrame frame; + private final RntbdRequestHeaders headers; + private final byte[] payload; - Objects.requireNonNull(frame, "frame"); - Objects.requireNonNull(headers, "headers"); + private RntbdRequest(final RntbdRequestFrame frame, final RntbdRequestHeaders headers, final byte[] payload) { + + checkNotNull(frame, "frame"); + checkNotNull(headers, "headers"); this.frame = frame; this.headers = headers; this.payload = payload == null ? EmptyByteArray : payload; } - static RntbdRequest decode(ByteBuf in) { + public UUID getActivityId() { + return this.frame.getActivityId(); + } + + @JsonIgnore + @SuppressWarnings("unchecked") + public T getHeader(final RntbdRequestHeader header) { + return (T)this.headers.get(header).getValue(); + } + + public Long getTransportRequestId() { + return this.getHeader(RntbdRequestHeader.TransportRequestID); + } + + public static RntbdRequest decode(final ByteBuf in) { - int resourceOperationCode = in.getInt(in.readerIndex() + Integer.BYTES); + final int resourceOperationCode = in.getInt(in.readerIndex() + Integer.BYTES); if (resourceOperationCode == 0) { - String reason = String.format("resourceOperationCode=0x%08X", resourceOperationCode); + final String reason = String.format("resourceOperationCode=0x%08X", resourceOperationCode); throw new IllegalStateException(reason); } - int start = in.readerIndex(); - int expectedLength = in.readIntLE(); + final int start = in.readerIndex(); + final int expectedLength = in.readIntLE(); - RntbdRequestFrame header = RntbdRequestFrame.decode(in); - RntbdRequestHeaders metadata = RntbdRequestHeaders.decode(in); - ByteBuf payloadBuf = in.readSlice(expectedLength - (in.readerIndex() - start)); + final RntbdRequestFrame header = RntbdRequestFrame.decode(in); + final RntbdRequestHeaders metadata = RntbdRequestHeaders.decode(in); + final ByteBuf payloadBuf = in.readSlice(expectedLength - (in.readerIndex() - start)); - int observedLength = in.readerIndex() - start; + final int observedLength = in.readerIndex() - start; if (observedLength != expectedLength) { - String reason = String.format("expectedLength=%d, observedLength=%d", expectedLength, observedLength); + final String reason = String.format("expectedLength=%d, observedLength=%d", expectedLength, observedLength); throw new IllegalStateException(reason); } - byte[] payload = new byte[payloadBuf.readableBytes()]; + final byte[] payload = new byte[payloadBuf.readableBytes()]; payloadBuf.readBytes(payload); in.discardReadBytes(); return new RntbdRequest(header, metadata, payload); } - public static RntbdRequest from(RntbdRequestArgs args) { + void encode(final ByteBuf out) { - RxDocumentServiceRequest serviceRequest = args.getServiceRequest(); - - final RntbdRequestFrame frame = new RntbdRequestFrame( - serviceRequest.getActivityId(), - serviceRequest.getOperationType(), - serviceRequest.getResourceType()); - - final RntbdRequestHeaders headers = new RntbdRequestHeaders(args, frame); - - return new RntbdRequest(frame, headers, serviceRequest.getContent()); - } - - public UUID getActivityId() { - return this.frame.getActivityId(); - } - - void encode(ByteBuf out) { - - int expectedLength = RntbdRequestFrame.LENGTH + headers.computeLength(); - int start = out.readerIndex(); + final int expectedLength = RntbdRequestFrame.LENGTH + this.headers.computeLength(); + final int start = out.readerIndex(); out.writeIntLE(expectedLength); this.frame.encode(out); @@ -112,4 +111,18 @@ void encode(ByteBuf out) { out.writeBytes(this.payload); } } + + public static RntbdRequest from(final RntbdRequestArgs args) { + + final RxDocumentServiceRequest serviceRequest = args.getServiceRequest(); + + final RntbdRequestFrame frame = new RntbdRequestFrame( + args.getActivityId(), + serviceRequest.getOperationType(), + serviceRequest.getResourceType()); + + final RntbdRequestHeaders headers = new RntbdRequestHeaders(args, frame); + + return new RntbdRequest(frame, headers, serviceRequest.getContent()); + } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestArgs.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestArgs.java index b59fc12d74099..b04cdce7f3ee2 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestArgs.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestArgs.java @@ -24,34 +24,53 @@ package com.azure.data.cosmos.directconnectivity.rntbd; -import com.google.common.base.Stopwatch; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import com.google.common.base.Stopwatch; import io.netty.channel.ChannelHandlerContext; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import java.math.BigDecimal; +import java.net.URI; import java.time.Duration; -import java.util.Objects; import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import java.util.stream.Stream; -final public class RntbdRequestArgs { +import static com.google.common.base.Preconditions.checkNotNull; + +@JsonPropertyOrder({ + "transportRequestId", "origin", "replicaPath", "activityId", "operationType", "resourceType", "birthTime", + "lifetime" +}) +public final class RntbdRequestArgs { + + private static final AtomicLong instanceCount = new AtomicLong(); + private static final String simpleClassName = RntbdRequestArgs.class.getSimpleName(); private final UUID activityId; private final long birthTime; private final Stopwatch lifetime; + private final String origin; + private final URI physicalAddress; private final String replicaPath; private final RxDocumentServiceRequest serviceRequest; + private final long transportRequestId; - - public RntbdRequestArgs(RxDocumentServiceRequest serviceRequest, String replicaPath) { + public RntbdRequestArgs(final RxDocumentServiceRequest serviceRequest, final URI physicalAddress) { this.activityId = UUID.fromString(serviceRequest.getActivityId()); this.birthTime = System.nanoTime(); this.lifetime = Stopwatch.createStarted(); - this.replicaPath = StringUtils.stripEnd(replicaPath, "/"); + this.origin = physicalAddress.getScheme() + "://" + physicalAddress.getAuthority(); + this.physicalAddress = physicalAddress; + this.replicaPath = StringUtils.stripEnd(physicalAddress.getPath(), "/"); this.serviceRequest = serviceRequest; + this.transportRequestId = instanceCount.incrementAndGet(); } public UUID getActivityId() { @@ -62,33 +81,45 @@ public long getBirthTime() { return this.birthTime; } + @JsonSerialize(using = ToStringSerializer.class) public Duration getLifetime() { return this.lifetime.elapsed(); } + public String getOrigin() { + return this.origin; + } + + @JsonIgnore + public URI getPhysicalAddress() { + return this.physicalAddress; + } + public String getReplicaPath() { return this.replicaPath; } - RxDocumentServiceRequest getServiceRequest() { + @JsonIgnore + public RxDocumentServiceRequest getServiceRequest() { return this.serviceRequest; } + public long getTransportRequestId() { + return this.transportRequestId; + } + @Override public String toString() { - return "[activityId: " + this.serviceRequest.getActivityId() + ", operationType: " - + this.serviceRequest.getOperationType() + ", resourceType: " - + this.serviceRequest.getResourceType() + ", replicaPath: " - + this.replicaPath + "]"; + return simpleClassName + '(' + RntbdObjectMapper.toJson(this) + ')'; } - public void traceOperation(Logger logger, ChannelHandlerContext context, String operationName, Object... args) { + public void traceOperation(final Logger logger, final ChannelHandlerContext context, final String operationName, final Object... args) { - Objects.requireNonNull(logger); + checkNotNull(logger, "logger"); if (logger.isTraceEnabled()) { final BigDecimal lifetime = BigDecimal.valueOf(this.lifetime.elapsed().toNanos(), 6); - logger.info("{},{},\"{}({})\",\"{}\",\"{}\"", this.birthTime, lifetime, operationName, + logger.trace("{},{},\"{}({})\",\"{}\",\"{}\"", this.birthTime, lifetime, operationName, Stream.of(args).map(arg -> arg == null ? "null" : arg.toString()).collect(Collectors.joining(",") ), diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestDecoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestDecoder.java index 150f619fc07fe..92fb9b4adc455 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestDecoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestDecoder.java @@ -30,7 +30,7 @@ import java.util.List; -final public class RntbdRequestDecoder extends ByteToMessageDecoder { +public final class RntbdRequestDecoder extends ByteToMessageDecoder { /** * Prepare for decoding an @{link RntbdRequest} or fire a channel readTree event to pass the input message along * @@ -39,12 +39,12 @@ final public class RntbdRequestDecoder extends ByteToMessageDecoder { * @throws Exception thrown if an error occurs */ @Override - public void channelRead(ChannelHandlerContext context, Object message) throws Exception { + public void channelRead(final ChannelHandlerContext context, final Object message) throws Exception { if (message instanceof ByteBuf) { - ByteBuf in = (ByteBuf)message; - int resourceOperationType = in.getInt(in.readerIndex() + Integer.BYTES); + final ByteBuf in = (ByteBuf)message; + final int resourceOperationType = in.getInt(in.readerIndex() + Integer.BYTES); if (resourceOperationType != 0) { super.channelRead(context, message); @@ -67,14 +67,14 @@ public void channelRead(ChannelHandlerContext context, Object message) throws Ex * @throws IllegalStateException thrown if an error occurs */ @Override - protected void decode(ChannelHandlerContext context, ByteBuf in, List out) throws IllegalStateException { + protected void decode(final ChannelHandlerContext context, final ByteBuf in, final List out) throws IllegalStateException { - RntbdRequest request; + final RntbdRequest request; in.markReaderIndex(); try { request = RntbdRequest.decode(in); - } catch (IllegalStateException error) { + } catch (final IllegalStateException error) { in.resetReaderIndex(); throw error; } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestEncoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestEncoder.java index 68a6802896b3f..4dc7ef56fe654 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestEncoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestEncoder.java @@ -31,7 +31,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -final public class RntbdRequestEncoder extends MessageToByteEncoder { +public final class RntbdRequestEncoder extends MessageToByteEncoder { private static final Logger logger = LoggerFactory.getLogger(RntbdRequestEncoder.class); @@ -44,7 +44,7 @@ final public class RntbdRequestEncoder extends MessageToByteEncoder { * @return {@code true}, if the given message is an an {@link RntbdRequest} instance; otherwise @{false} */ @Override - public boolean acceptOutboundMessage(Object message) { + public boolean acceptOutboundMessage(final Object message) { return message instanceof RntbdRequestArgs; } @@ -58,20 +58,20 @@ public boolean acceptOutboundMessage(Object message) { * @param out the {@link ByteBuf} into which the encoded message will be written */ @Override - protected void encode(ChannelHandlerContext context, Object message, ByteBuf out) throws Exception { + protected void encode(final ChannelHandlerContext context, final Object message, final ByteBuf out) throws Exception { - RntbdRequest request = RntbdRequest.from((RntbdRequestArgs)message); - int start = out.writerIndex(); + final RntbdRequest request = RntbdRequest.from((RntbdRequestArgs)message); + final int start = out.writerIndex(); try { request.encode(out); - } catch (Throwable error) { + } catch (final Throwable error) { out.writerIndex(start); throw error; } if (logger.isDebugEnabled()) { - int length = out.writerIndex() - start; + final int length = out.writerIndex() - start; logger.debug("{}: ENCODE COMPLETE: length={}, request={}", context.channel(), length, request); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFrame.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFrame.java index 6ba43e32ad178..815d8d846bb33 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFrame.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFrame.java @@ -38,22 +38,22 @@ final class RntbdRequestFrame { // region Fields - final static int LENGTH = Integer.BYTES // messageLength + static final int LENGTH = Integer.BYTES // messageLength + Short.BYTES // resourceType + Short.BYTES // operationType + 2 * Long.BYTES; // activityId - final private UUID activityId; - final private RntbdOperationType operationType; - final private RntbdResourceType resourceType; + private final UUID activityId; + private final RntbdOperationType operationType; + private final RntbdResourceType resourceType; // region Constructors - RntbdRequestFrame(String activityId, OperationType operationType, ResourceType resourceType) { - this(UUID.fromString(activityId), map(operationType), map(resourceType)); + RntbdRequestFrame(final UUID activityId, final OperationType operationType, final ResourceType resourceType) { + this(activityId, map(operationType), map(resourceType)); } - RntbdRequestFrame(UUID activityId, RntbdOperationType operationType, RntbdResourceType resourceType) { + RntbdRequestFrame(final UUID activityId, final RntbdOperationType operationType, final RntbdResourceType resourceType) { this.activityId = activityId; this.operationType = operationType; this.resourceType = resourceType; @@ -63,16 +63,34 @@ final class RntbdRequestFrame { // region Methods - static RntbdRequestFrame decode(ByteBuf in) { + UUID getActivityId() { + return this.activityId; + } + + RntbdOperationType getOperationType() { + return this.operationType; + } + + RntbdResourceType getResourceType() { + return this.resourceType; + } + + static RntbdRequestFrame decode(final ByteBuf in) { - RntbdResourceType resourceType = RntbdResourceType.fromId(in.readShortLE()); - RntbdOperationType operationType = RntbdOperationType.fromId(in.readShortLE()); - UUID activityId = RntbdUUID.decode(in); + final RntbdResourceType resourceType = RntbdResourceType.fromId(in.readShortLE()); + final RntbdOperationType operationType = RntbdOperationType.fromId(in.readShortLE()); + final UUID activityId = RntbdUUID.decode(in); return new RntbdRequestFrame(activityId, operationType, resourceType); } - private static RntbdResourceType map(ResourceType resourceType) { + void encode(final ByteBuf out) { + out.writeShortLE(this.resourceType.id()); + out.writeShortLE(this.operationType.id()); + RntbdUUID.encode(this.activityId, out); + } + + private static RntbdResourceType map(final ResourceType resourceType) { switch (resourceType) { case Attachment: @@ -132,12 +150,12 @@ private static RntbdResourceType map(ResourceType resourceType) { case RidRange: return RntbdResourceType.RidRange; default: - String reason = String.format(Locale.ROOT, "Unrecognized resource type: %s", resourceType); + final String reason = String.format(Locale.ROOT, "Unrecognized resource type: %s", resourceType); throw new UnsupportedOperationException(reason); } } - private static RntbdOperationType map(OperationType operationType) { + private static RntbdOperationType map(final OperationType operationType) { switch (operationType) { case Crash: @@ -207,28 +225,10 @@ private static RntbdOperationType map(OperationType operationType) { case AddComputeGatewayRequestCharges: return RntbdOperationType.AddComputeGatewayRequestCharges; default: - String reason = String.format(Locale.ROOT, "Unrecognized operation type: %s", operationType); + final String reason = String.format(Locale.ROOT, "Unrecognized operation type: %s", operationType); throw new UnsupportedOperationException(reason); } } - UUID getActivityId() { - return activityId; - } - - RntbdOperationType getOperationType() { - return operationType; - } - - RntbdResourceType getResourceType() { - return resourceType; - } - - void encode(ByteBuf out) { - out.writeShortLE(this.resourceType.id()); - out.writeShortLE(this.operationType.id()); - RntbdUUID.encode(this.activityId, out); - } - // endregion } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFramer.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFramer.java index 472e0fb2b4a2d..344d077381f45 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFramer.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFramer.java @@ -28,7 +28,7 @@ import java.nio.ByteOrder; -final public class RntbdRequestFramer extends LengthFieldBasedFrameDecoder { +public final class RntbdRequestFramer extends LengthFieldBasedFrameDecoder { public RntbdRequestFramer() { super(ByteOrder.LITTLE_ENDIAN, Integer.MAX_VALUE, 0, Integer.BYTES, -Integer.BYTES, 0, true); diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestHeaders.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestHeaders.java index 6a86d7c348b7d..9d27a78f1aa82 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestHeaders.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestHeaders.java @@ -25,7 +25,6 @@ package com.azure.data.cosmos.directconnectivity.rntbd; -import com.fasterxml.jackson.annotation.JsonFilter; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.IndexingDirective; import com.azure.data.cosmos.internal.ContentSerializationFormat; @@ -33,24 +32,21 @@ import com.azure.data.cosmos.internal.FanoutOperationState; import com.azure.data.cosmos.internal.MigrateCollectionDirective; import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.ReadFeedKeyType; import com.azure.data.cosmos.internal.RemoteStorageType; import com.azure.data.cosmos.internal.ResourceId; -import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.fasterxml.jackson.annotation.JsonFilter; import io.netty.buffer.ByteBuf; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.validator.routines.DoubleValidator; -import org.apache.commons.validator.routines.LongValidator; import java.util.Base64; import java.util.Locale; import java.util.Map; -import java.util.Objects; import java.util.function.Supplier; -import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; import static com.azure.data.cosmos.directconnectivity.WFConstants.BackendHeaders; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdConsistencyLevel; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdContentSerializationFormat; @@ -62,6 +58,8 @@ import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdReadFeedKeyType; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdRemoteStorageType; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdRequestHeader; +import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; +import static com.google.common.base.Preconditions.checkNotNull; @JsonFilter("RntbdToken") final class RntbdRequestHeaders extends RntbdTokenStream { @@ -69,25 +67,24 @@ final class RntbdRequestHeaders extends RntbdTokenStream { // region Fields private static final String UrlTrim = "/+"; - private static final DoubleValidator doubleValidator = DoubleValidator.getInstance(); - private static final LongValidator longValidator = LongValidator.getInstance(); // endregion // region Constructors - RntbdRequestHeaders(RntbdRequestArgs args, RntbdRequestFrame frame) { + RntbdRequestHeaders(final RntbdRequestArgs args, final RntbdRequestFrame frame) { this(); - Objects.requireNonNull(args, "args"); - Objects.requireNonNull(frame, "frame"); + checkNotNull(args, "args"); + checkNotNull(frame, "frame"); - RxDocumentServiceRequest request = args.getServiceRequest(); - byte[] content = request.getContent(); + final RxDocumentServiceRequest request = args.getServiceRequest(); + final byte[] content = request.getContent(); this.getPayloadPresent().setValue(content != null && content.length > 0); this.getReplicaPath().setValue(args.getReplicaPath()); + this.getTransportRequestID().setValue(args.getTransportRequestId()); final Map headers = request.getHeaders(); @@ -174,7 +171,7 @@ final class RntbdRequestHeaders extends RntbdTokenStream { this.fillTokenFromHeader(headers, this::getTransportRequestID, HttpHeaders.TRANSPORT_REQUEST_ID); // Will be null in case of direct, which is fine - BE will use the value slice the connection context this. - // When this is used in GATEWAY, the header value will be populated with the proxied HTTP request's header, + // When this is used in Gateway, the header value will be populated with the proxied HTTP request's header, // and BE will respect the per-request value. this.fillTokenFromHeader(headers, this::getClientVersion, HttpHeaders.VERSION); @@ -188,8 +185,8 @@ private RntbdRequestHeaders() { // region Methods - static RntbdRequestHeaders decode(ByteBuf in) { - RntbdRequestHeaders metadata = new RntbdRequestHeaders(); + static RntbdRequestHeaders decode(final ByteBuf in) { + final RntbdRequestHeaders metadata = new RntbdRequestHeaders(); return RntbdRequestHeaders.decode(in, metadata); } @@ -581,67 +578,67 @@ private RntbdToken getUserName() { return this.get(RntbdRequestHeader.UserName); } - private void addAimHeader(Map headers) { + private void addAimHeader(final Map headers) { - String value = headers.get(HttpHeaders.A_IM); + final String value = headers.get(HttpHeaders.A_IM); if (StringUtils.isNotEmpty(value)) { this.getAIM().setValue(value); } } - private void addAllowScanOnQuery(Map headers) { - String value = headers.get(HttpHeaders.ENABLE_SCAN_IN_QUERY); + private void addAllowScanOnQuery(final Map headers) { + final String value = headers.get(HttpHeaders.ENABLE_SCAN_IN_QUERY); if (StringUtils.isNotEmpty(value)) { this.getEnableScanInQuery().setValue(Boolean.parseBoolean(value)); } } - private void addBinaryIdIfPresent(Map headers) { - String value = headers.get(BackendHeaders.BINARY_ID); + private void addBinaryIdIfPresent(final Map headers) { + final String value = headers.get(BackendHeaders.BINARY_ID); if (StringUtils.isNotEmpty(value)) { this.getBinaryId().setValue(Base64.getDecoder().decode(value)); } } - private void addCanCharge(Map headers) { - String value = headers.get(HttpHeaders.CAN_CHARGE); + private void addCanCharge(final Map headers) { + final String value = headers.get(HttpHeaders.CAN_CHARGE); if (StringUtils.isNotEmpty(value)) { this.getCanCharge().setValue(Boolean.parseBoolean(value)); } } - private void addCanOfferReplaceComplete(Map headers) { - String value = headers.get(HttpHeaders.CAN_OFFER_REPLACE_COMPLETE); + private void addCanOfferReplaceComplete(final Map headers) { + final String value = headers.get(HttpHeaders.CAN_OFFER_REPLACE_COMPLETE); if (StringUtils.isNotEmpty(value)) { this.getCanOfferReplaceComplete().setValue(Boolean.parseBoolean(value)); } } - private void addCanThrottle(Map headers) { - String value = headers.get(HttpHeaders.CAN_THROTTLE); + private void addCanThrottle(final Map headers) { + final String value = headers.get(HttpHeaders.CAN_THROTTLE); if (StringUtils.isNotEmpty(value)) { this.getCanThrottle().setValue(Boolean.parseBoolean(value)); } } - private void addCollectionRemoteStorageSecurityIdentifier(Map headers) { - String value = headers.get(HttpHeaders.COLLECTION_REMOTE_STORAGE_SECURITY_IDENTIFIER); + private void addCollectionRemoteStorageSecurityIdentifier(final Map headers) { + final String value = headers.get(HttpHeaders.COLLECTION_REMOTE_STORAGE_SECURITY_IDENTIFIER); if (StringUtils.isNotEmpty(value)) { this.getCollectionRemoteStorageSecurityIdentifier().setValue(value); } } - private void addConsistencyLevelHeader(Map headers) { + private void addConsistencyLevelHeader(final Map headers) { - String value = headers.get(HttpHeaders.CONSISTENCY_LEVEL); + final String value = headers.get(HttpHeaders.CONSISTENCY_LEVEL); if (StringUtils.isNotEmpty(value)) { - ConsistencyLevel level = EnumUtils.getEnumIgnoreCase(ConsistencyLevel.class, value); + final ConsistencyLevel level = EnumUtils.getEnumIgnoreCase(ConsistencyLevel.class, value); if (level == null) { - String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, + final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, HttpHeaders.CONSISTENCY_LEVEL, value); throw new IllegalStateException(reason); @@ -670,16 +667,16 @@ private void addConsistencyLevelHeader(Map headers) { } } - private void addContentSerializationFormat(Map headers) { + private void addContentSerializationFormat(final Map headers) { - String value = headers.get(HttpHeaders.CONTENT_SERIALIZATION_FORMAT); + final String value = headers.get(HttpHeaders.CONTENT_SERIALIZATION_FORMAT); if (StringUtils.isNotEmpty(value)) { - ContentSerializationFormat format = EnumUtils.getEnumIgnoreCase(ContentSerializationFormat.class, value); + final ContentSerializationFormat format = EnumUtils.getEnumIgnoreCase(ContentSerializationFormat.class, value); if (format == null) { - String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, + final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, HttpHeaders.CONTENT_SERIALIZATION_FORMAT, value); throw new IllegalStateException(reason); @@ -698,14 +695,14 @@ private void addContentSerializationFormat(Map headers) { } } - private void addContinuationToken(RxDocumentServiceRequest request) { - String value = request.getContinuation(); + private void addContinuationToken(final RxDocumentServiceRequest request) { + final String value = request.getContinuation(); if (StringUtils.isNotEmpty(value)) { this.getContinuationToken().setValue(value); } } - private void addDateHeader(Map headers) { + private void addDateHeader(final Map headers) { // Since the HTTP date header is overridden by some proxies/http client libraries, we support an additional date // header and prefer that to the (regular) date header @@ -721,51 +718,51 @@ private void addDateHeader(Map headers) { } } - private void addDisableRUPerMinuteUsage(Map headers) { - String value = headers.get(HttpHeaders.DISABLE_RU_PER_MINUTE_USAGE); + private void addDisableRUPerMinuteUsage(final Map headers) { + final String value = headers.get(HttpHeaders.DISABLE_RU_PER_MINUTE_USAGE); if (StringUtils.isNotEmpty(value)) { this.getDisableRUPerMinuteUsage().setValue(Boolean.parseBoolean(value)); } } - private void addEmitVerboseTracesInQuery(Map headers) { - String value = headers.get(HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY); + private void addEmitVerboseTracesInQuery(final Map headers) { + final String value = headers.get(HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY); if (StringUtils.isNotEmpty(value)) { this.getEmitVerboseTracesInQuery().setValue(Boolean.parseBoolean(value)); } } - private void addEnableLogging(Map headers) { - String value = headers.get(HttpHeaders.ENABLE_LOGGING); + private void addEnableLogging(final Map headers) { + final String value = headers.get(HttpHeaders.ENABLE_LOGGING); if (StringUtils.isNotEmpty(value)) { this.getEnableLogging().setValue(Boolean.parseBoolean(value)); } } - private void addEnableLowPrecisionOrderBy(Map headers) { - String value = headers.get(HttpHeaders.ENABLE_LOW_PRECISION_ORDER_BY); + private void addEnableLowPrecisionOrderBy(final Map headers) { + final String value = headers.get(HttpHeaders.ENABLE_LOW_PRECISION_ORDER_BY); if (StringUtils.isNotEmpty(value)) { this.getEnableLowPrecisionOrderBy().setValue(Boolean.parseBoolean(value)); } } - private void addEntityId(Map headers) { - String value = headers.get(BackendHeaders.ENTITY_ID); + private void addEntityId(final Map headers) { + final String value = headers.get(BackendHeaders.ENTITY_ID); if (StringUtils.isNotEmpty(value)) { this.getEntityId().setValue(value); } } - private void addEnumerationDirection(Map headers) { + private void addEnumerationDirection(final Map headers) { - String value = headers.get(HttpHeaders.ENUMERATION_DIRECTION); + final String value = headers.get(HttpHeaders.ENUMERATION_DIRECTION); if (StringUtils.isNotEmpty(value)) { - EnumerationDirection direction = EnumUtils.getEnumIgnoreCase(EnumerationDirection.class, value); + final EnumerationDirection direction = EnumUtils.getEnumIgnoreCase(EnumerationDirection.class, value); if (direction == null) { - String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, + final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, HttpHeaders.ENUMERATION_DIRECTION, value); throw new IllegalStateException(reason); @@ -784,23 +781,23 @@ private void addEnumerationDirection(Map headers) { } } - private void addExcludeSystemProperties(Map headers) { - String value = headers.get(BackendHeaders.EXCLUDE_SYSTEM_PROPERTIES); + private void addExcludeSystemProperties(final Map headers) { + final String value = headers.get(BackendHeaders.EXCLUDE_SYSTEM_PROPERTIES); if (StringUtils.isNotEmpty(value)) { this.getExcludeSystemProperties().setValue(Boolean.parseBoolean(value)); } } - private void addFanoutOperationStateHeader(Map headers) { + private void addFanoutOperationStateHeader(final Map headers) { - String value = headers.get(BackendHeaders.FANOUT_OPERATION_STATE); + final String value = headers.get(BackendHeaders.FANOUT_OPERATION_STATE); if (StringUtils.isNotEmpty(value)) { - FanoutOperationState format = EnumUtils.getEnumIgnoreCase(FanoutOperationState.class, value); + final FanoutOperationState format = EnumUtils.getEnumIgnoreCase(FanoutOperationState.class, value); if (format == null) { - String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, + final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, BackendHeaders.FANOUT_OPERATION_STATE, value); throw new IllegalStateException(reason); @@ -819,23 +816,23 @@ private void addFanoutOperationStateHeader(Map headers) { } } - private void addIfModifiedSinceHeader(Map headers) { - String value = headers.get(HttpHeaders.IF_MODIFIED_SINCE); + private void addIfModifiedSinceHeader(final Map headers) { + final String value = headers.get(HttpHeaders.IF_MODIFIED_SINCE); if (StringUtils.isNotEmpty(value)) { this.getIfModifiedSince().setValue(value); } } - private void addIndexingDirectiveHeader(Map headers) { + private void addIndexingDirectiveHeader(final Map headers) { - String value = headers.get(HttpHeaders.INDEXING_DIRECTIVE); + final String value = headers.get(HttpHeaders.INDEXING_DIRECTIVE); if (StringUtils.isNotEmpty(value)) { - IndexingDirective directive = EnumUtils.getEnumIgnoreCase(IndexingDirective.class, value); + final IndexingDirective directive = EnumUtils.getEnumIgnoreCase(IndexingDirective.class, value); if (directive == null) { - String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, + final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, HttpHeaders.INDEXING_DIRECTIVE, value); throw new IllegalStateException(reason); @@ -857,35 +854,35 @@ private void addIndexingDirectiveHeader(Map headers) { } } - private void addIsAutoScaleRequest(Map headers) { - String value = headers.get(HttpHeaders.IS_AUTO_SCALE_REQUEST); + private void addIsAutoScaleRequest(final Map headers) { + final String value = headers.get(HttpHeaders.IS_AUTO_SCALE_REQUEST); if (StringUtils.isNotEmpty(value)) { this.getIsAutoScaleRequest().setValue(Boolean.parseBoolean(value)); } } - private void addIsFanout(Map headers) { - String value = headers.get(BackendHeaders.IS_FANOUT_REQUEST); + private void addIsFanout(final Map headers) { + final String value = headers.get(BackendHeaders.IS_FANOUT_REQUEST); if (StringUtils.isNotEmpty(value)) { this.getIsFanout().setValue(Boolean.parseBoolean(value)); } } - private void addIsReadOnlyScript(Map headers) { - String value = headers.get(HttpHeaders.IS_READ_ONLY_SCRIPT); + private void addIsReadOnlyScript(final Map headers) { + final String value = headers.get(HttpHeaders.IS_READ_ONLY_SCRIPT); if (StringUtils.isNotEmpty(value)) { this.getIsReadOnlyScript().setValue(Boolean.parseBoolean(value)); } } - private void addIsUserRequest(Map headers) { - String value = headers.get(BackendHeaders.IS_USER_REQUEST); + private void addIsUserRequest(final Map headers) { + final String value = headers.get(BackendHeaders.IS_USER_REQUEST); if (StringUtils.isNotEmpty(value)) { this.getIsUserRequest().setValue(Boolean.parseBoolean(value)); } } - private void addMatchHeader(Map headers, RntbdOperationType operationType) { + private void addMatchHeader(final Map headers, final RntbdOperationType operationType) { String match = null; @@ -904,16 +901,16 @@ private void addMatchHeader(Map headers, RntbdOperationType oper } } - private void addMigrateCollectionDirectiveHeader(Map headers) { + private void addMigrateCollectionDirectiveHeader(final Map headers) { - String value = headers.get(HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE); + final String value = headers.get(HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE); if (StringUtils.isNotEmpty(value)) { - MigrateCollectionDirective directive = EnumUtils.getEnumIgnoreCase(MigrateCollectionDirective.class, value); + final MigrateCollectionDirective directive = EnumUtils.getEnumIgnoreCase(MigrateCollectionDirective.class, value); if (directive == null) { - String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, + final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE, value); throw new IllegalStateException(reason); @@ -933,77 +930,68 @@ private void addMigrateCollectionDirectiveHeader(Map headers) { } } - private void addPageSize(Map headers) { + private void addPageSize(final Map headers) { - String value = headers.get(HttpHeaders.PAGE_SIZE); + final String value = headers.get(HttpHeaders.PAGE_SIZE); if (StringUtils.isNotEmpty(value)) { - - final Long pageSize = longValidator.validate(value, Locale.ROOT); - - if (pageSize == null || !longValidator.isInRange(pageSize, -1, 0xFFFFFFFFL)) { - String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, - HttpHeaders.PAGE_SIZE, - value); - throw new IllegalStateException(reason); - } - - this.getPageSize().setValue((int)(pageSize < 0 ? 0xFFFFFFFFL : pageSize)); + final long aLong = parseLong(HttpHeaders.PAGE_SIZE, value, -1, 0xFFFFFFFFL); + this.getPageSize().setValue((int)(aLong < 0 ? 0xFFFFFFFFL : aLong)); } } - private void addPopulateCollectionThroughputInfo(Map headers) { - String value = headers.get(HttpHeaders.POPULATE_COLLECTION_THROUGHPUT_INFO); + private void addPopulateCollectionThroughputInfo(final Map headers) { + final String value = headers.get(HttpHeaders.POPULATE_COLLECTION_THROUGHPUT_INFO); if (StringUtils.isNotEmpty(value)) { this.getPopulateCollectionThroughputInfo().setValue(Boolean.parseBoolean(value)); } } - private void addPopulatePartitionStatistics(Map headers) { - String value = headers.get(HttpHeaders.POPULATE_PARTITION_STATISTICS); + private void addPopulatePartitionStatistics(final Map headers) { + final String value = headers.get(HttpHeaders.POPULATE_PARTITION_STATISTICS); if (StringUtils.isNotEmpty(value)) { this.getPopulatePartitionStatistics().setValue(Boolean.parseBoolean(value)); } } - private void addPopulateQueryMetrics(Map headers) { - String value = headers.get(HttpHeaders.POPULATE_QUERY_METRICS); + private void addPopulateQueryMetrics(final Map headers) { + final String value = headers.get(HttpHeaders.POPULATE_QUERY_METRICS); if (StringUtils.isNotEmpty(value)) { this.getPopulateQueryMetrics().setValue(Boolean.parseBoolean(value)); } } - private void addPopulateQuotaInfo(Map headers) { - String value = headers.get(HttpHeaders.POPULATE_QUOTA_INFO); + private void addPopulateQuotaInfo(final Map headers) { + final String value = headers.get(HttpHeaders.POPULATE_QUOTA_INFO); if (StringUtils.isNotEmpty(value)) { this.getPopulateQuotaInfo().setValue(Boolean.parseBoolean(value)); } } - private void addProfileRequest(Map headers) { - String value = headers.get(HttpHeaders.PROFILE_REQUEST); + private void addProfileRequest(final Map headers) { + final String value = headers.get(HttpHeaders.PROFILE_REQUEST); if (StringUtils.isNotEmpty(value)) { this.getProfileRequest().setValue(Boolean.parseBoolean(value)); } } - private void addQueryForceScan(Map headers) { - String value = headers.get(HttpHeaders.FORCE_QUERY_SCAN); + private void addQueryForceScan(final Map headers) { + final String value = headers.get(HttpHeaders.FORCE_QUERY_SCAN); if (StringUtils.isNotEmpty(value)) { this.getForceQueryScan().setValue(Boolean.parseBoolean(value)); } } - private void addRemoteStorageType(Map headers) { + private void addRemoteStorageType(final Map headers) { - String value = headers.get(BackendHeaders.REMOTE_STORAGE_TYPE); + final String value = headers.get(BackendHeaders.REMOTE_STORAGE_TYPE); if (StringUtils.isNotEmpty(value)) { - RemoteStorageType type = EnumUtils.getEnumIgnoreCase(RemoteStorageType.class, value); + final RemoteStorageType type = EnumUtils.getEnumIgnoreCase(RemoteStorageType.class, value); if (type == null) { - String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, + final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, BackendHeaders.REMOTE_STORAGE_TYPE, value); throw new IllegalStateException(reason); @@ -1022,9 +1010,9 @@ private void addRemoteStorageType(Map headers) { } } - private void addResourceIdOrPathHeaders(RxDocumentServiceRequest request) { + private void addResourceIdOrPathHeaders(final RxDocumentServiceRequest request) { - String value = request.getResourceId(); + final String value = request.getResourceId(); if (StringUtils.isNotEmpty(value)) { // Name-based can also have ResourceId because gateway might have generated it @@ -1036,8 +1024,8 @@ private void addResourceIdOrPathHeaders(RxDocumentServiceRequest request) { // Assumption: format is like "dbs/dbName/colls/collName/docs/docName" or "/dbs/dbName/colls/collName", // not "apps/appName/partitions/partitionKey/replicas/replicaId/dbs/dbName" - String address = request.getResourceAddress(); - String[] fragments = address.split(UrlTrim); + final String address = request.getResourceAddress(); + final String[] fragments = address.split(UrlTrim); int count = fragments.length; int index = 0; @@ -1052,7 +1040,7 @@ private void addResourceIdOrPathHeaders(RxDocumentServiceRequest request) { this.getDatabaseName().setValue(fragments[index + 1]); break; default: - String reason = String.format(Locale.ROOT, RMResources.InvalidResourceAddress, + final String reason = String.format(Locale.ROOT, RMResources.InvalidResourceAddress, value, address); throw new IllegalStateException(reason); } @@ -1111,41 +1099,33 @@ private void addResourceIdOrPathHeaders(RxDocumentServiceRequest request) { } } - private void addResponseContinuationTokenLimitInKb(Map headers) { + private void addResponseContinuationTokenLimitInKb(final Map headers) { - String value = headers.get(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB); + final String value = headers.get(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB); if (StringUtils.isNotEmpty(value)) { - - Long tokenLimit = longValidator.validate(value, Locale.ROOT); - - if (tokenLimit == null || !longValidator.isInRange(tokenLimit, 0, 0xFFFFFFFFL)) { - String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, - HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, - value); - throw new IllegalStateException(reason); - } - this.getResponseContinuationTokenLimitInKb().setValue((int)(tokenLimit < 0 ? 0xFFFFFFFFL : tokenLimit)); + final long aLong = parseLong(HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, value, 0, 0xFFFFFFFFL); + this.getResponseContinuationTokenLimitInKb().setValue((int)(aLong < 0 ? 0xFFFFFFFFL : aLong)); } } - private void addShareThroughput(Map headers) { - String value = headers.get(BackendHeaders.SHARE_THROUGHPUT); + private void addShareThroughput(final Map headers) { + final String value = headers.get(BackendHeaders.SHARE_THROUGHPUT); if (StringUtils.isNotEmpty(value)) { this.getShareThroughput().setValue(Boolean.parseBoolean(value)); } } - private void addStartAndEndKeys(Map headers) { + private void addStartAndEndKeys(final Map headers) { String value = headers.get(HttpHeaders.READ_FEED_KEY_TYPE); if (StringUtils.isNotEmpty(value)) { - ReadFeedKeyType type = EnumUtils.getEnumIgnoreCase(ReadFeedKeyType.class, value); + final ReadFeedKeyType type = EnumUtils.getEnumIgnoreCase(ReadFeedKeyType.class, value); if (type == null) { - String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, + final String reason = String.format(Locale.ROOT, RMResources.InvalidRequestHeaderValue, HttpHeaders.READ_FEED_KEY_TYPE, value); throw new IllegalStateException(reason); @@ -1163,7 +1143,7 @@ private void addStartAndEndKeys(Map headers) { } } - Base64.Decoder decoder = Base64.getDecoder(); + final Base64.Decoder decoder = Base64.getDecoder(); value = headers.get(HttpHeaders.START_ID); @@ -1190,29 +1170,29 @@ private void addStartAndEndKeys(Map headers) { } } - private void addSupportSpatialLegacyCoordinates(Map headers) { - String value = headers.get(HttpHeaders.SUPPORT_SPATIAL_LEGACY_COORDINATES); + private void addSupportSpatialLegacyCoordinates(final Map headers) { + final String value = headers.get(HttpHeaders.SUPPORT_SPATIAL_LEGACY_COORDINATES); if (StringUtils.isNotEmpty(value)) { this.getSupportSpatialLegacyCoordinates().setValue(Boolean.parseBoolean(value)); } } - private void addUsePolygonsSmallerThanAHemisphere(Map headers) { - String value = headers.get(HttpHeaders.USE_POLYGONS_SMALLER_THAN_AHEMISPHERE); + private void addUsePolygonsSmallerThanAHemisphere(final Map headers) { + final String value = headers.get(HttpHeaders.USE_POLYGONS_SMALLER_THAN_AHEMISPHERE); if (StringUtils.isNotEmpty(value)) { this.getUsePolygonsSmallerThanAHemisphere().setValue(Boolean.parseBoolean(value)); } } - private void fillTokenFromHeader(Map headers, Supplier supplier, String name) { + private void fillTokenFromHeader(final Map headers, final Supplier supplier, final String name) { - String value = headers.get(name); + final String value = headers.get(name); if (StringUtils.isNotEmpty(value)) { - RntbdToken token = supplier.get(); + final RntbdToken token = supplier.get(); - switch (token.getType()) { + switch (token.getTokenType()) { case SmallString: case String: @@ -1228,60 +1208,66 @@ private void fillTokenFromHeader(Map headers, Supplier contextFuture = new CompletableFuture<>(); - final private CompletableFuture contextRequestFuture = new CompletableFuture<>(); - final private ConcurrentHashMap pendingRequests = new ConcurrentHashMap<>(); + private static final Logger logger = LoggerFactory.getLogger(RntbdRequestManager.class); - private volatile ChannelHandlerContext context; - private volatile PendingRequest currentRequest; - private volatile CoalescingBufferQueue pendingWrites; + private final CompletableFuture contextFuture = new CompletableFuture<>(); + private final CompletableFuture contextRequestFuture = new CompletableFuture<>(); + private final ConcurrentHashMap pendingRequests; + private final int pendingRequestLimit; - // endregion + private boolean closingExceptionally = false; + private CoalescingBufferQueue pendingWrites; - // region Request management methods + // endregion - /** - * Cancels the {@link CompletableFuture} for the request message identified by @{code activityId} - * - * @param activityId identifies an RNTBD request message - */ - public void cancelStoreResponseFuture(UUID activityId) { - Objects.requireNonNull(activityId, "activityId"); - this.removePendingRequest(activityId).getResponseFuture().cancel(true); + public RntbdRequestManager(int capacity) { + checkArgument(capacity > 0, "capacity: %s", capacity); + this.pendingRequests = new ConcurrentHashMap<>(capacity); + this.pendingRequestLimit = capacity; } + // region ChannelHandler methods + /** - * Fails a {@link CompletableFuture} for the request message identified by {@code activityId} + * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. * - * @param activityId identifies an RNTBD request message - * @param cause specifies the cause of the failure + * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ - public void completeStoreResponseFutureExceptionally(UUID activityId, Throwable cause) { - Objects.requireNonNull(activityId, "activityId"); - Objects.requireNonNull(cause, "cause"); - this.removePendingRequest(activityId).getResponseFuture().completeExceptionally(cause); + @Override + public void handlerAdded(final ChannelHandlerContext context) { + this.traceOperation(context, "handlerAdded"); } /** - * Creates a {@link CompletableFuture} of a {@link StoreResponse} for the message identified by {@code activityId} + * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events + * anymore. * - * @param requestArgs identifies a request message - * @return a {@link CompletableFuture} of a {@link StoreResponse} + * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ - public CompletableFuture createStoreResponseFuture(RntbdRequestArgs requestArgs) { - - Objects.requireNonNull(requestArgs, "requestArgs"); - - this.currentRequest = this.pendingRequests.compute(requestArgs.getActivityId(), (activityId, pendingRequest) -> { - - if (pendingRequest == null) { - pendingRequest = new PendingRequest(requestArgs); - logger.trace("{} created new pending request", pendingRequest); - } else { - logger.trace("{} renewed existing pending request", pendingRequest); - } - - return pendingRequest; - - }); - - this.traceOperation(logger, this.context, "createStoreResponseFuture"); - return this.currentRequest.getResponseFuture(); - } - - void traceOperation(Logger logger, ChannelHandlerContext context, String operationName, Object... args) { - - if (logger.isTraceEnabled()) { - - final long birthTime; - final BigDecimal lifetime; - - if (this.currentRequest == null) { - birthTime = System.nanoTime(); - lifetime = BigDecimal.ZERO; - } else { - birthTime = this.currentRequest.getBirthTime(); - lifetime = BigDecimal.valueOf(this.currentRequest.getLifetime().toNanos(), 6); - } - - logger.info("{},{},\"{}({})\",\"{}\",\"{}\"", birthTime, lifetime, operationName, Stream.of(args).map(arg -> - arg == null ? "null" : arg.toString()).collect(Collectors.joining(",") - ), this.currentRequest, context - ); - } + @Override + public void handlerRemoved(final ChannelHandlerContext context) { + this.traceOperation(context, "handlerRemoved"); } // endregion @@ -184,74 +138,51 @@ void traceOperation(Logger logger, ChannelHandlerContext context, String operati * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override - public void channelActive(ChannelHandlerContext context) throws Exception { - this.traceOperation(logger, this.context, "channelActive"); + public void channelActive(final ChannelHandlerContext context) { + this.traceOperation(context, "channelActive"); context.fireChannelActive(); } /** * Completes all pending requests exceptionally when a channel reaches the end of its lifetime + *

+ * This method will only be called after the channel is closed. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override - public void channelInactive(ChannelHandlerContext context) throws Exception { - - this.traceOperation(logger, this.context, "channelInactive"); - Channel channel = context.channel(); - - try { - - this.contextRequestFuture.getNow(null); - this.contextFuture.getNow(null); - - logger.debug("{} INACTIVE: RNTBD negotiation request status:\nrequest: {}\nresponse: {}", - channel, this.contextRequestFuture, this.contextFuture - ); - - } catch (CancellationException error) { - logger.debug("{} INACTIVE: RNTBD negotiation request cancelled:", channel, error); - - } catch (Exception error) { - logger.error("{} INACTIVE: RNTBD negotiation request failed:", channel, error); - } - - if (!this.pendingWrites.isEmpty()) { - this.pendingWrites.releaseAndFailAll(context, new ChannelException("Closed with pending writes")); - } - - if (!this.pendingRequests.isEmpty()) { - - String reason = String.format("%s Closed with pending requests", channel); - ChannelException cause = new ChannelException(reason); - - for (PendingRequest pendingRequest : this.pendingRequests.values()) { - pendingRequest.getResponseFuture().completeExceptionally(cause); - } - - this.pendingRequests.clear(); - } - + public void channelInactive(final ChannelHandlerContext context) { + this.traceOperation(context, "channelInactive"); context.fireChannelInactive(); } @Override - public void channelRead(ChannelHandlerContext context, Object message) throws Exception { + public void channelRead(final ChannelHandlerContext context, final Object message) { - this.traceOperation(logger, context, "channelRead"); + this.traceOperation(context, "channelRead"); if (message instanceof RntbdResponse) { + try { this.messageReceived(context, (RntbdResponse)message); + } catch (Throwable throwable) { + reportIssue(logger, context, "{} ", message, throwable); + this.exceptionCaught(context, throwable); } finally { ReferenceCountUtil.release(message); } - this.traceOperation(logger, context, "messageReceived"); - return; - } - String reason = String.format("Expected message of type %s, not %s", RntbdResponse.class, message.getClass()); - throw new IllegalStateException(reason); + } else { + + final IllegalStateException error = new IllegalStateException( + Strings.lenientFormat("expected message of %s, not %s: %s", + RntbdResponse.class, message.getClass(), message + ) + ); + + reportIssue(logger, context, "", error); + this.exceptionCaught(context, error); + } } /** @@ -264,14 +195,14 @@ public void channelRead(ChannelHandlerContext context, Object message) throws Ex * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override - public void channelReadComplete(ChannelHandlerContext context) throws Exception { - this.traceOperation(logger, context, "channelReadComplete"); + public void channelReadComplete(final ChannelHandlerContext context) { + this.traceOperation(context, "channelReadComplete"); context.fireChannelReadComplete(); } /** * Constructs a {@link CoalescingBufferQueue} for buffering encoded requests until we have an {@link RntbdRequest} - * + *

* This method then calls {@link ChannelHandlerContext#fireChannelRegistered()} to forward to the next * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. *

@@ -280,16 +211,13 @@ public void channelReadComplete(ChannelHandlerContext context) throws Exception * @param context the {@link ChannelHandlerContext} for which the bind operation is made */ @Override - public void channelRegistered(ChannelHandlerContext context) throws Exception { - - this.traceOperation(logger, context, "channelRegistered"); + public void channelRegistered(final ChannelHandlerContext context) { - if (!(this.context == null && this.pendingWrites == null)) { - throw new IllegalStateException(); - }; + this.traceOperation(context, "channelRegistered"); + checkState(this.pendingWrites == null, "pendingWrites: %s", this.pendingWrites); this.pendingWrites = new CoalescingBufferQueue(context.channel()); - this.context = context; + context.fireChannelRegistered(); } @@ -299,16 +227,14 @@ public void channelRegistered(ChannelHandlerContext context) throws Exception { * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override - public void channelUnregistered(ChannelHandlerContext context) throws Exception { - - this.traceOperation(logger, context, "channelUnregistered"); + public void channelUnregistered(final ChannelHandlerContext context) { - if (this.context == null || this.pendingWrites == null || !this.pendingWrites.isEmpty()) { - throw new IllegalStateException(); - }; + this.traceOperation(context, "channelUnregistered"); + checkState(this.pendingWrites != null, "pendingWrites: null"); + this.completeAllPendingRequestsExceptionally(context, ClosedWithPendingRequestsException.INSTANCE); this.pendingWrites = null; - this.context = null; + context.fireChannelUnregistered(); } @@ -319,8 +245,8 @@ public void channelUnregistered(ChannelHandlerContext context) throws Exception * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs */ @Override - public void channelWritabilityChanged(ChannelHandlerContext context) throws Exception { - this.traceOperation(logger, context, "channelWritabilityChanged"); + public void channelWritabilityChanged(final ChannelHandlerContext context) { + this.traceOperation(context, "channelWritabilityChanged"); context.fireChannelWritabilityChanged(); } @@ -332,60 +258,60 @@ public void channelWritabilityChanged(ChannelHandlerContext context) throws Exce */ @Override @SuppressWarnings("deprecation") - public void exceptionCaught(ChannelHandlerContext context, Throwable cause) throws Exception { + public void exceptionCaught(final ChannelHandlerContext context, final Throwable cause) { // TODO: DANOBLE: replace RntbdRequestManager.exceptionCaught with read/write listeners // Notes: - // ChannelInboundHandler.exceptionCaught is deprecated and--today, prior to deprecation--only catches read-- - // i.e., inbound--exceptions. - // Replacements: - // * read listener: unclear as there is no obvious replacement - // * write listener: implemented by RntbdTransportClient.DefaultEndpoint.doWrite + // ChannelInboundHandler.exceptionCaught is deprecated and--today, prior to deprecation--only catches read-- + // i.e., inbound--exceptions. + // Replacements: + // * read listener: unclear as there is no obvious replacement + // * write listener: implemented by RntbdTransportClient.DefaultEndpoint.doWrite // Links: // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/373213 - logger.error("{} closing exceptionally: {}", context.channel(), cause.getMessage()); - traceOperation(logger, context, "exceptionCaught", cause); - context.close(); - } + this.traceOperation(context, "exceptionCaught", cause); - /** - * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. - * - * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs - */ - @Override - public void handlerAdded(ChannelHandlerContext context) throws Exception { - this.traceOperation(logger, context, "handlerAdded"); - } + if (!this.closingExceptionally) { - /** - * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events - * anymore. - * - * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs - */ - @Override - public void handlerRemoved(ChannelHandlerContext context) throws Exception { - this.traceOperation(logger, context, "handlerRemoved"); + reportIssueUnless(cause != ClosedWithPendingRequestsException.INSTANCE, logger, context, + "expected an exception other than ", ClosedWithPendingRequestsException.INSTANCE); + + this.completeAllPendingRequestsExceptionally(context, cause); + context.pipeline().flush().close(); + } } /** - * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelInitializer} pipeline + * Processes inbound events triggered by channel handlers in the {@link RntbdClientChannelHandler} pipeline *

- * ALL but inbound request management events are ignored. + * All but inbound request management events are ignored. * * @param context {@link ChannelHandlerContext} to which this {@link RntbdRequestManager} belongs * @param event An object representing a user event */ @Override - public void userEventTriggered(ChannelHandlerContext context, Object event) throws Exception { - this.traceOperation(logger, context, "userEventTriggered", event); - if (event instanceof RntbdContext) { - this.completeRntbdContextFuture(context, (RntbdContext)event); - return; + public void userEventTriggered(final ChannelHandlerContext context, final Object event) { + + this.traceOperation(context, "userEventTriggered", event); + + try { + if (event instanceof RntbdContext) { + this.contextFuture.complete((RntbdContext)event); + this.removeContextNegotiatorAndFlushPendingWrites(context); + return; + } + if (event instanceof RntbdContextException) { + this.contextFuture.completeExceptionally((RntbdContextException)event); + context.pipeline().flush().close(); + return; + } + context.fireUserEventTriggered(event); + + } catch (Throwable error) { + reportIssue(logger, context, "{}: ", event, error); + this.exceptionCaught(context, error); } - context.fireUserEventTriggered(event); } // endregion @@ -398,66 +324,76 @@ public void userEventTriggered(ChannelHandlerContext context, Object event) thro * @param context the {@link ChannelHandlerContext} for which the bind operation is made * @param localAddress the {@link SocketAddress} to which it should bound * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error occurs */ @Override - public void bind(ChannelHandlerContext context, SocketAddress localAddress, ChannelPromise promise) throws Exception { - this.traceOperation(logger, context, "bind"); + public void bind(final ChannelHandlerContext context, final SocketAddress localAddress, final ChannelPromise promise) { + this.traceOperation(context, "bind", localAddress); context.bind(localAddress, promise); } /** - * Called once a connect operation is made. + * Called once a close operation is made. * - * @param context the {@link ChannelHandlerContext} for which the connect operation is made - * @param remoteAddress the {@link SocketAddress} to which it should connect - * @param localAddress the {@link SocketAddress} which is used as source on connect - * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error occurs + * @param context the {@link ChannelHandlerContext} for which the close operation is made + * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override - public void connect(ChannelHandlerContext context, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception { - this.traceOperation(logger, context, "connect"); - context.connect(remoteAddress, localAddress, promise); + public void close(final ChannelHandlerContext context, final ChannelPromise promise) { + + this.traceOperation(context, "close"); + + this.completeAllPendingRequestsExceptionally(context, ClosedWithPendingRequestsException.INSTANCE); + final SslHandler sslHandler = context.pipeline().get(SslHandler.class); + + if (sslHandler != null) { + // Netty 4.1.36.Final: SslHandler.closeOutbound must be called before closing the pipeline + // This ensures that all SSL engine and ByteBuf resources are released + // This is something that does not occur in the call to ChannelPipeline.close that follows + sslHandler.closeOutbound(); + } + + context.close(promise); } /** - * Called once a disconnect operation is made. + * Called once a connect operation is made. * - * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made - * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error occurs + * @param context the {@link ChannelHandlerContext} for which the connect operation is made + * @param remoteAddress the {@link SocketAddress} to which it should connect + * @param localAddress the {@link SocketAddress} which is used as source on connect + * @param promise the {@link ChannelPromise} to notify once the operation completes */ @Override - public void disconnect(ChannelHandlerContext context, ChannelPromise promise) throws Exception { - this.traceOperation(logger, context, "disconnect"); - context.disconnect(promise); + public void connect( + final ChannelHandlerContext context, final SocketAddress remoteAddress, final SocketAddress localAddress, + final ChannelPromise promise + ) { + this.traceOperation(context, "connect", remoteAddress, localAddress); + context.connect(remoteAddress, localAddress, promise); } /** - * Called once a close operation is made. + * Called once a deregister operation is made from the current registered {@link EventLoop}. * * @param context the {@link ChannelHandlerContext} for which the close operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error occurs */ @Override - public void close(ChannelHandlerContext context, ChannelPromise promise) throws Exception { - this.traceOperation(logger, context, "close"); - context.close(promise); + public void deregister(final ChannelHandlerContext context, final ChannelPromise promise) { + this.traceOperation(context, "deregister"); + context.deregister(promise); } /** - * Called once a deregister operation is made from the current registered {@link EventLoop}. + * Called once a disconnect operation is made. * - * @param context the {@link ChannelHandlerContext} for which the close operation is made + * @param context the {@link ChannelHandlerContext} for which the disconnect operation is made * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error occurs */ @Override - public void deregister(ChannelHandlerContext context, ChannelPromise promise) throws Exception { - this.traceOperation(logger, context, "deregister"); - context.deregister(promise); + public void disconnect(final ChannelHandlerContext context, final ChannelPromise promise) { + this.traceOperation(context, "disconnect"); + context.disconnect(promise); } /** @@ -466,11 +402,10 @@ public void deregister(ChannelHandlerContext context, ChannelPromise promise) th * The flush operation will try to flush out all previous written messages that are pending. * * @param context the {@link ChannelHandlerContext} for which the flush operation is made - * @throws Exception thrown if an error occurs */ @Override - public void flush(ChannelHandlerContext context) throws Exception { - this.traceOperation(logger, context, "flush"); + public void flush(final ChannelHandlerContext context) { + this.traceOperation(context, "flush"); context.flush(); } @@ -480,8 +415,8 @@ public void flush(ChannelHandlerContext context) throws Exception { * @param context the {@link ChannelHandlerContext} for which the read operation is made */ @Override - public void read(ChannelHandlerContext context) throws Exception { - this.traceOperation(logger, context, "read"); + public void read(final ChannelHandlerContext context) { + this.traceOperation(context, "read"); context.read(); } @@ -494,21 +429,29 @@ public void read(ChannelHandlerContext context) throws Exception { * @param context the {@link ChannelHandlerContext} for which the write operation is made * @param message the message to write * @param promise the {@link ChannelPromise} to notify once the operation completes - * @throws Exception thrown if an error occurs */ @Override - public void write(ChannelHandlerContext context, Object message, ChannelPromise promise) throws Exception { + public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) { - this.traceOperation(logger, context, "write", message); + // TODO: DANOBLE: Ensure that all write errors are reported with a root cause of type EncoderException - if (message instanceof RntbdRequestArgs) { - this.currentRequest = this.getPendingRequest((RntbdRequestArgs)message); - context.write(message, promise); - return; - } + this.traceOperation(context, "write", message); + + if (message instanceof RntbdRequestRecord) { + + context.write(this.addPendingRequestRecord(context, (RntbdRequestRecord)message), promise); + + } else { + + final IllegalStateException error = new IllegalStateException( + Strings.lenientFormat("expected message of %s, not %s: %s", + RntbdRequestRecord.class, message.getClass(), message + ) + ); - String reason = String.format("Expected message of type %s, not %s", RntbdRequestArgs.class, message.getClass()); - throw new IllegalStateException(reason); + reportIssue(logger, context, "", error); + this.exceptionCaught(context, error); + } } // endregion @@ -523,57 +466,144 @@ boolean hasRntbdContext() { return this.contextFuture.getNow(null) != null; } - void pendWrite(ByteBuf out, ChannelPromise promise) { + boolean isServiceable(final int demand) { + final int limit = this.hasRntbdContext() ? this.pendingRequestLimit : Math.min(this.pendingRequestLimit, demand); + return this.pendingRequests.size() < limit; + } - Objects.requireNonNull(out, "out"); + void pendWrite(final ByteBuf out, final ChannelPromise promise) { + this.pendingWrites.add(out, promise); + } - if (this.pendingWrites == null) { - throw new IllegalStateException("pendingWrites: null"); - } + private RntbdRequestArgs addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { - this.pendingWrites.add(out, promise); + return this.pendingRequests.compute(record.getTransportRequestId(), (id, current) -> { + + reportIssueUnless(current == null, logger, context, "id: {}, current: {}, request: {}", id, current, record); + + final Timeout pendingRequestTimeout = record.newTimeout(timeout -> { + + // We don't wish to complete on the timeout thread, but rather on a thread doled out by our executor + + EventExecutor executor = context.executor(); + + if (executor.inEventLoop()) { + record.expire(); + } else { + executor.next().execute(record::expire); + } + }); + + record.whenComplete((response, error) -> { + this.pendingRequests.remove(id); + pendingRequestTimeout.cancel(); + }); + + return record; + + }).getArgs(); } - private PendingRequest checkPendingRequest(UUID activityId, PendingRequest pendingRequest) { + private Optional getRntbdContext() { + return Optional.of(this.contextFuture.getNow(null)); + } - if (pendingRequest == null) { - throw new IllegalStateException(String.format("Pending request not found: %s", activityId)); + private void completeAllPendingRequestsExceptionally(final ChannelHandlerContext context, final Throwable throwable) { + + if (this.closingExceptionally) { + + reportIssueUnless(throwable == ClosedWithPendingRequestsException.INSTANCE, logger, context, + "throwable: ", throwable); + + reportIssueUnless(this.pendingRequests.isEmpty() && this.pendingWrites.isEmpty(), logger, context, + "pendingRequests: {}, pendingWrites: {}", this.pendingRequests.isEmpty(), + this.pendingWrites.isEmpty()); + + return; } - if (pendingRequest.getResponseFuture().isDone()) { - throw new IllegalStateException(String.format("Request is not pending: %s", activityId)); + this.closingExceptionally = true; + + if (!this.pendingWrites.isEmpty()) { + this.pendingWrites.releaseAndFailAll(context, ClosedWithPendingRequestsException.INSTANCE); } - return pendingRequest; - } + if (!this.pendingRequests.isEmpty()) { + + if (!this.contextRequestFuture.isDone()) { + this.contextRequestFuture.completeExceptionally(throwable); + } - private void completeRntbdContextFuture(ChannelHandlerContext context, RntbdContext value) { + if (!this.contextFuture.isDone()) { + this.contextFuture.completeExceptionally(throwable); + } - Objects.requireNonNull(context, "context"); - Objects.requireNonNull(value, "value"); + final int count = this.pendingRequests.size(); + Exception contextRequestException = null; + String phrase = null; + + if (this.contextRequestFuture.isCompletedExceptionally()) { + + try { + this.contextRequestFuture.get(); + } catch (final CancellationException error) { + phrase = "RNTBD context request write cancelled"; + contextRequestException = error; + } catch (final Exception error) { + phrase = "RNTBD context request write failed"; + contextRequestException = error; + } catch (final Throwable error) { + phrase = "RNTBD context request write failed"; + contextRequestException = new ChannelException(error); + } - if (this.contextFuture.isDone()) { - throw new IllegalStateException(String.format("rntbdContextFuture: %s", this.contextFuture)); - } + } else if (this.contextFuture.isCompletedExceptionally()) { + + try { + this.contextFuture.get(); + } catch (final CancellationException error) { + phrase = "RNTBD context request read cancelled"; + contextRequestException = error; + } catch (final Exception error) { + phrase = "RNTBD context request read failed"; + contextRequestException = error; + } catch (final Throwable error) { + phrase = "RNTBD context request read failed"; + contextRequestException = new ChannelException(error); + } - contextFuture.complete(value); + } else { - RntbdContextNegotiator negotiator = context.channel().pipeline().get(RntbdContextNegotiator.class); - negotiator.removeInboundHandler(); - negotiator.removeOutboundHandler(); + phrase = "closed exceptionally"; + } - if (!pendingWrites.isEmpty()) { - this.pendingWrites.writeAndRemoveAll(context); - } - } + final String message = Strings.lenientFormat("%s %s with %s pending requests", context, phrase, count); + final Exception cause; - private PendingRequest getPendingRequest(RntbdRequestArgs args) { - UUID activityId = args.getActivityId(); - return checkPendingRequest(activityId, this.pendingRequests.get(activityId)); - } + if (throwable == ClosedWithPendingRequestsException.INSTANCE) { - private Optional getRntbdContext() { - return Optional.of(this.contextFuture.getNow(null)); + cause = contextRequestException == null + ? ClosedWithPendingRequestsException.INSTANCE + : contextRequestException; + + } else { + + cause = throwable instanceof Exception + ? (Exception)throwable + : new ChannelException(throwable); + } + + for (RntbdRequestRecord record : this.pendingRequests.values()) { + + final Map requestHeaders = record.getArgs().getServiceRequest().getHeaders(); + final String requestUri = record.getArgs().getPhysicalAddress().toString(); + + final GoneException error = new GoneException(message, cause, (Map)null, requestUri); + BridgeInternal.setRequestHeaders(error, requestHeaders); + + record.completeExceptionally(error); + } + } } /** @@ -582,23 +612,29 @@ private Optional getRntbdContext() { * @param context {@link ChannelHandlerContext} encode to which this {@link RntbdRequestManager} belongs * @param response the message encode handle */ - private void messageReceived(ChannelHandlerContext context, RntbdResponse response) { + private void messageReceived(final ChannelHandlerContext context, final RntbdResponse response) { - final UUID activityId = response.getActivityId(); - final PendingRequest pendingRequest = this.pendingRequests.remove(activityId); + final Long transportRequestId = response.getTransportRequestId(); + + if (transportRequestId == null) { + reportIssue(logger, context, "{} ignored because there is no transport request identifier, response"); + return; + } + + final RntbdRequestRecord pendingRequest = this.pendingRequests.get(transportRequestId); if (pendingRequest == null) { - logger.warn("[activityId: {}] no request pending", activityId); + reportIssue(logger, context, "{} ignored because there is no matching pending request", response); return; } - final CompletableFuture future = pendingRequest.getResponseFuture(); final HttpResponseStatus status = response.getStatus(); + final UUID activityId = response.getActivityId(); if (HttpResponseStatus.OK.code() <= status.code() && status.code() < HttpResponseStatus.MULTIPLE_CHOICES.code()) { final StoreResponse storeResponse = response.toStoreResponse(this.contextFuture.getNow(null)); - future.complete(storeResponse); + pendingRequest.complete(storeResponse); } else { @@ -611,27 +647,11 @@ private void messageReceived(ChannelHandlerContext context, RntbdResponse respon final long lsn = response.getHeader(RntbdResponseHeader.LSN); final String partitionKeyRangeId = response.getHeader(RntbdResponseHeader.PartitionKeyRangeId); - // ..CREATE Error instance - - final ObjectMapper mapper = new ObjectMapper(); - final Error error; + // ..Create Error instance - if (response.hasPayload()) { - - try (Reader reader = response.getResponseStreamReader()) { - - error = BridgeInternal.createError((ObjectNode)mapper.readTree(reader)); - - } catch (IOException e) { - - String message = String.format("%s: %s", e.getClass(), e.getMessage()); - logger.error("{} %s", context.channel(), message); - throw new CorruptedFrameException(message); - } - - } else { - error = new Error(Integer.toString(status.code()), status.reasonPhrase(), status.codeClass().name()); - } + final Error error = response.hasPayload() ? + BridgeInternal.createError(RntbdObjectMapper.readTree(response)) : + new Error(Integer.toString(status.code()), status.reasonPhrase(), status.codeClass().name()); // ..Map RNTBD response headers to HTTP response headers @@ -639,7 +659,7 @@ private void messageReceived(ChannelHandlerContext context, RntbdResponse respon this.getRntbdContext().orElseThrow(IllegalStateException::new), activityId ); - // ..CREATE CosmosClientException based on status and sub-status codes + // ..Create CosmosClientException based on status and sub-status codes switch (status.code()) { @@ -657,7 +677,7 @@ private void messageReceived(ChannelHandlerContext context, RntbdResponse respon case StatusCodes.GONE: - int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); + final int subStatusCode = Math.toIntExact(response.getHeader(RntbdResponseHeader.SubStatus)); switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT: @@ -727,52 +747,48 @@ private void messageReceived(ChannelHandlerContext context, RntbdResponse respon break; } - logger.trace("{}[activityId: {}, statusCode: {}, subStatusCode: {}] {}", - context.channel(), cause.message(), cause.statusCode(), cause.subStatusCode(), - cause.getMessage() - ); + pendingRequest.completeExceptionally(cause); + } + } - future.completeExceptionally(cause); + private void removeContextNegotiatorAndFlushPendingWrites(final ChannelHandlerContext context) { + + final RntbdContextNegotiator negotiator = context.pipeline().get(RntbdContextNegotiator.class); + negotiator.removeInboundHandler(); + negotiator.removeOutboundHandler(); + + if (!this.pendingWrites.isEmpty()) { + this.pendingWrites.writeAndRemoveAll(context); } } - private PendingRequest removePendingRequest(UUID activityId) { - PendingRequest pendingRequest = this.pendingRequests.remove(activityId); - return checkPendingRequest(activityId, pendingRequest); + private void traceOperation(final ChannelHandlerContext context, final String operationName, final Object... args) { + logger.trace("{}\n{}\n{}", operationName, context, args); } // endregion // region Types - private static class PendingRequest { - - private final RntbdRequestArgs args; - private final CompletableFuture responseFuture = new CompletableFuture<>(); + private static class ClosedWithPendingRequestsException extends RuntimeException { - PendingRequest(RntbdRequestArgs args) { - this.args = args; - } - - RntbdRequestArgs getArgs() { - return this.args; - } + static ClosedWithPendingRequestsException INSTANCE = new ClosedWithPendingRequestsException(); - long getBirthTime() { - return this.args.getBirthTime(); - } - - Duration getLifetime() { - return this.args.getLifetime(); - } - - CompletableFuture getResponseFuture() { - return this.responseFuture; - } + // TODO: DANOBLE: Consider revising strategy for closing an RntbdTransportClient with pending requests + // One possibility: + // A channel associated with an RntbdTransportClient will not be closed immediately, if there are any pending + // requests on it. Instead it will be scheduled to close after the request timeout interval (default: 60s) has + // elapsed. + // Algorithm: + // When the RntbdTransportClient is closed, it closes each of its RntbdServiceEndpoint instances. In turn each + // RntbdServiceEndpoint closes its RntbdClientChannelPool. The RntbdClientChannelPool.close method should + // schedule closure of any channel with pending requests for later; when the request timeout interval has + // elapsed or--ideally--when all pending requests have completed. + // Links: + // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/388987 - @Override - public String toString() { - return this.args.toString(); + private ClosedWithPendingRequestsException() { + super(null, null, /* enableSuppression */ false, /* writableStackTrace */ false); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java new file mode 100644 index 0000000000000..c315a0092136a --- /dev/null +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java @@ -0,0 +1,94 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.azure.data.cosmos.directconnectivity.rntbd; + +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.directconnectivity.RequestTimeoutException; +import com.azure.data.cosmos.directconnectivity.StoreResponse; +import io.netty.util.Timeout; +import io.netty.util.TimerTask; + +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import static com.google.common.base.Preconditions.checkNotNull; + +public final class RntbdRequestRecord extends CompletableFuture { + + private static final String simpleClassName = RntbdRequestRecord.class.getSimpleName(); + + private final RntbdRequestArgs args; + private final RntbdRequestTimer timer; + + public RntbdRequestRecord(final RntbdRequestArgs args, final RntbdRequestTimer timer) { + + checkNotNull(args, "args"); + checkNotNull(timer, "timer"); + + this.args = args; + this.timer = timer; + } + + public UUID getActivityId() { + return this.args.getActivityId(); + } + + public RntbdRequestArgs getArgs() { + return this.args; + } + + public long getBirthTime() { + return this.args.getBirthTime(); + } + + public Duration getLifetime() { + return this.args.getLifetime(); + } + + public long getTransportRequestId() { + return this.args.getTransportRequestId(); + } + + public boolean expire() { + + final long timeoutInterval = this.timer.getRequestTimeout(TimeUnit.MILLISECONDS); + final String message = String.format("Request timeout interval (%,d ms) elapsed", timeoutInterval); + final RequestTimeoutException error = new RequestTimeoutException(message, this.args.getPhysicalAddress()); + + BridgeInternal.setRequestHeaders(error, this.args.getServiceRequest().getHeaders()); + + return this.completeExceptionally(error); + } + + public Timeout newTimeout(final TimerTask task) { + return this.timer.newTimeout(task); + } + + @Override + public String toString() { + return simpleClassName + '(' + RntbdObjectMapper.toJson(this.args) + ')'; + } +} diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestTimer.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestTimer.java new file mode 100644 index 0000000000000..707bb44c33f27 --- /dev/null +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestTimer.java @@ -0,0 +1,62 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.azure.data.cosmos.directconnectivity.rntbd; + +import io.netty.util.HashedWheelTimer; +import io.netty.util.Timeout; +import io.netty.util.Timer; +import io.netty.util.TimerTask; + +import java.util.concurrent.TimeUnit; + +public final class RntbdRequestTimer implements AutoCloseable { + + private static final long FIVE_MILLISECONDS = 5000000L; + private final long requestTimeout; + private final Timer timer; + + public RntbdRequestTimer(final long requestTimeout) { + + // Inspection of the HashWheelTimer code indicates that our choice of a 5 millisecond timer resolution ensures + // a request will timeout within 10 milliseconds of the specified requestTimeout interval. This is because + // cancellation of a timeout takes two timer resolution units to complete. + + this.timer = new HashedWheelTimer(FIVE_MILLISECONDS, TimeUnit.NANOSECONDS); + this.requestTimeout = requestTimeout; + } + + public long getRequestTimeout(TimeUnit unit) { + return unit.convert(requestTimeout, TimeUnit.NANOSECONDS); + } + + @Override + public void close() throws RuntimeException { + this.timer.stop(); + } + + public Timeout newTimeout(final TimerTask task) { + return this.timer.newTimeout(task, this.requestTimeout, TimeUnit.NANOSECONDS); + } +} diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponse.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponse.java index af46f086154a8..bfe7a0f9ed1ed 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponse.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponse.java @@ -24,68 +24,65 @@ package com.azure.data.cosmos.directconnectivity.rntbd; +import com.azure.data.cosmos.directconnectivity.StoreResponse; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.StdSerializer; -import com.azure.data.cosmos.directconnectivity.StoreResponse; import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.EmptyByteBuf; -import io.netty.handler.codec.CorruptedFrameException; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.util.ReferenceCounted; import io.netty.util.ResourceLeakDetector; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Map; -import java.util.Objects; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; import static java.lang.Math.min; @JsonPropertyOrder({ "frame", "headers", "content" }) -final public class RntbdResponse implements ReferenceCounted { +public final class RntbdResponse implements ReferenceCounted { // region Fields - @JsonSerialize(using = PayloadSerializer.class) + private static final String simpleClassName = RntbdResponse.class.getSimpleName(); + @JsonProperty - final private ByteBuf content; + @JsonSerialize(using = PayloadSerializer.class) + private final ByteBuf content; @JsonProperty - final private RntbdResponseStatus frame; + private final RntbdResponseStatus frame; @JsonProperty - final private RntbdResponseHeaders headers; + private final RntbdResponseHeaders headers; private AtomicInteger referenceCount = new AtomicInteger(); // endregion - public RntbdResponse(UUID activityId, int statusCode, Map map, ByteBuf content) { + public RntbdResponse(final UUID activityId, final int statusCode, final Map map, final ByteBuf content) { this.headers = RntbdResponseHeaders.fromMap(map, content.readableBytes() > 0); this.content = content.retain(); - HttpResponseStatus status = HttpResponseStatus.valueOf(statusCode); - int length = RntbdResponseStatus.LENGTH + headers.computeLength(); + final HttpResponseStatus status = HttpResponseStatus.valueOf(statusCode); + final int length = RntbdResponseStatus.LENGTH + this.headers.computeLength(); this.frame = new RntbdResponseStatus(length, status, activityId); } - private RntbdResponse(RntbdResponseStatus frame, RntbdResponseHeaders headers, ByteBuf content) { + private RntbdResponse(final RntbdResponseStatus frame, final RntbdResponseHeaders headers, final ByteBuf content) { this.frame = frame; this.headers = headers; @@ -106,17 +103,17 @@ public RntbdResponseHeaders getHeaders() { return this.headers; } - public InputStreamReader getResponseStreamReader() { - InputStream istream = new ByteBufInputStream(this.content.retain(), true); - return new InputStreamReader(istream); - } - @JsonIgnore public HttpResponseStatus getStatus() { return this.frame.getStatus(); } - static RntbdResponse decode(ByteBuf in) { + @JsonIgnore + public Long getTransportRequestId() { + return this.getHeader(RntbdResponseHeader.TransportRequestID); + } + + static RntbdResponse decode(final ByteBuf in) { in.markReaderIndex(); @@ -124,7 +121,7 @@ static RntbdResponse decode(ByteBuf in) { final RntbdResponseHeaders headers = RntbdResponseHeaders.decode(in.readSlice(frame.getHeadersLength())); final boolean hasPayload = headers.isPayloadPresent(); - ByteBuf content; + final ByteBuf content; if (hasPayload) { @@ -143,18 +140,15 @@ static RntbdResponse decode(ByteBuf in) { return new RntbdResponse(frame, headers, content); } - public void encode(ByteBuf out) { + public void encode(final ByteBuf out) { - int start = out.writerIndex(); + final int start = out.writerIndex(); this.frame.encode(out); this.headers.encode(out); - int length = out.writerIndex() - start; - - if (length != this.frame.getLength()) { - throw new IllegalStateException(); - } + final int length = out.writerIndex() - start; + checkState(length == this.frame.getLength()); if (this.hasPayload()) { out.writeIntLE(this.content.readableBytes()); @@ -165,9 +159,9 @@ public void encode(ByteBuf out) { } @JsonIgnore - public T getHeader(RntbdResponseHeader header) { - T value = (T)this.headers.get(header).getValue(); - return value; + @SuppressWarnings("unchecked") + public T getHeader(final RntbdResponseHeader header) { + return (T)this.headers.get(header).getValue(); } public boolean hasPayload() { @@ -199,7 +193,7 @@ public boolean release() { * @return {@code true} if and only if the reference count became {@code 0} and this object has been de-allocated */ @Override - public boolean release(int decrement) { + public boolean release(final int decrement) { return this.referenceCount.getAndAccumulate(decrement, (value, n) -> { value = value - min(value, n); @@ -227,15 +221,15 @@ public ReferenceCounted retain() { * @param increment amount of the increase */ @Override - public ReferenceCounted retain(int increment) { + public ReferenceCounted retain(final int increment) { this.referenceCount.addAndGet(increment); return this; } - StoreResponse toStoreResponse(RntbdContext context) { + StoreResponse toStoreResponse(final RntbdContext context) { - Objects.requireNonNull(context); - int length = this.content.readableBytes(); + checkNotNull(context, "context"); + final int length = this.content.readableBytes(); return new StoreResponse( this.getStatus().code(), @@ -246,12 +240,7 @@ StoreResponse toStoreResponse(RntbdContext context) { @Override public String toString() { - ObjectWriter writer = RntbdObjectMapper.writer(); - try { - return writer.writeValueAsString(this); - } catch (JsonProcessingException error) { - throw new CorruptedFrameException(error); - } + return simpleClassName + '(' + RntbdObjectMapper.toJson(this) + ')'; } /** @@ -274,7 +263,7 @@ public ReferenceCounted touch() { * @param hint information useful for debugging (unused) */ @Override - public ReferenceCounted touch(Object hint) { + public ReferenceCounted touch(final Object hint) { return this; } @@ -285,9 +274,9 @@ public PayloadSerializer() { } @Override - public void serialize(ByteBuf value, JsonGenerator generator, SerializerProvider provider) throws IOException { + public void serialize(final ByteBuf value, final JsonGenerator generator, final SerializerProvider provider) throws IOException { - int length = value.readableBytes(); + final int length = value.readableBytes(); generator.writeStartObject(); generator.writeObjectField("length", length); diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseDecoder.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseDecoder.java index 6399a985ff258..ca735c4de860c 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseDecoder.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseDecoder.java @@ -32,9 +32,9 @@ import java.util.List; -final public class RntbdResponseDecoder extends ByteToMessageDecoder { +public final class RntbdResponseDecoder extends ByteToMessageDecoder { - final private static Logger Logger = LoggerFactory.getLogger(RntbdResponseDecoder.class); + private static final Logger Logger = LoggerFactory.getLogger(RntbdResponseDecoder.class); /** * Deserialize from an input {@link ByteBuf} to an {@link RntbdResponse} instance @@ -46,11 +46,11 @@ final public class RntbdResponseDecoder extends ByteToMessageDecoder { * @param out the {@link List} to which decoded messages are added */ @Override - protected void decode(ChannelHandlerContext context, ByteBuf in, List out) { + protected void decode(final ChannelHandlerContext context, final ByteBuf in, final List out) { if (RntbdFramer.canDecodeHead(in)) { - RntbdResponse response = RntbdResponse.decode(in); + final RntbdResponse response = RntbdResponse.decode(in); if (response != null) { Logger.debug("{} DECODE COMPLETE: {}", context.channel(), response); diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseHeaders.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseHeaders.java index a719e836dfbf0..af19df8f67139 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseHeaders.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseHeaders.java @@ -41,10 +41,10 @@ import java.util.function.BiConsumer; import java.util.function.Function; -import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; import static com.azure.data.cosmos.directconnectivity.WFConstants.BackendHeaders; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdIndexingDirective; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; +import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; @JsonFilter("RntbdToken") class RntbdResponseHeaders extends RntbdTokenStream { @@ -52,103 +52,103 @@ class RntbdResponseHeaders extends RntbdTokenStream { // region Fields @JsonProperty - final private RntbdToken LSN; + private final RntbdToken LSN; @JsonProperty - final private RntbdToken collectionLazyIndexProgress; + private final RntbdToken collectionLazyIndexProgress; @JsonProperty - final private RntbdToken collectionPartitionIndex; + private final RntbdToken collectionPartitionIndex; @JsonProperty - final private RntbdToken collectionSecurityIdentifier; + private final RntbdToken collectionSecurityIdentifier; @JsonProperty - final private RntbdToken collectionServiceIndex; + private final RntbdToken collectionServiceIndex; @JsonProperty - final private RntbdToken collectionUpdateProgress; + private final RntbdToken collectionUpdateProgress; @JsonProperty - final private RntbdToken continuationToken; + private final RntbdToken continuationToken; @JsonProperty - final private RntbdToken currentReplicaSetSize; + private final RntbdToken currentReplicaSetSize; @JsonProperty - final private RntbdToken currentWriteQuorum; + private final RntbdToken currentWriteQuorum; @JsonProperty - final private RntbdToken databaseAccountId; + private final RntbdToken databaseAccountId; @JsonProperty - final private RntbdToken disableRntbdChannel; + private final RntbdToken disableRntbdChannel; @JsonProperty - final private RntbdToken eTag; + private final RntbdToken eTag; @JsonProperty - final private RntbdToken globalCommittedLSN; + private final RntbdToken globalCommittedLSN; @JsonProperty - final private RntbdToken hasTentativeWrites; + private final RntbdToken hasTentativeWrites; @JsonProperty - final private RntbdToken indexTermsGenerated; + private final RntbdToken indexTermsGenerated; @JsonProperty - final private RntbdToken indexingDirective; + private final RntbdToken indexingDirective; @JsonProperty - final private RntbdToken isRUPerMinuteUsed; + private final RntbdToken isRUPerMinuteUsed; @JsonProperty - final private RntbdToken itemCount; + private final RntbdToken itemCount; @JsonProperty - final private RntbdToken itemLSN; + private final RntbdToken itemLSN; @JsonProperty - final private RntbdToken itemLocalLSN; + private final RntbdToken itemLocalLSN; @JsonProperty - final private RntbdToken lastStateChangeDateTime; + private final RntbdToken lastStateChangeDateTime; @JsonProperty - final private RntbdToken localLSN; + private final RntbdToken localLSN; @JsonProperty - final private RntbdToken logResults; + private final RntbdToken logResults; @JsonProperty - final private RntbdToken numberOfReadRegions; + private final RntbdToken numberOfReadRegions; @JsonProperty - final private RntbdToken offerReplacePending; + private final RntbdToken offerReplacePending; @JsonProperty - final private RntbdToken ownerFullName; + private final RntbdToken ownerFullName; @JsonProperty - final private RntbdToken ownerId; + private final RntbdToken ownerId; @JsonProperty - final private RntbdToken partitionKeyRangeId; + private final RntbdToken partitionKeyRangeId; @JsonProperty - final private RntbdToken payloadPresent; + private final RntbdToken payloadPresent; @JsonProperty - final private RntbdToken queriesPerformed; + private final RntbdToken queriesPerformed; @JsonProperty - final private RntbdToken queryMetrics; + private final RntbdToken queryMetrics; @JsonProperty - final private RntbdToken quorumAckedLSN; + private final RntbdToken quorumAckedLSN; @JsonProperty - final private RntbdToken quorumAckedLocalLSN; + private final RntbdToken quorumAckedLocalLSN; @JsonProperty - final private RntbdToken readsPerformed; + private final RntbdToken readsPerformed; @JsonProperty - final private RntbdToken requestCharge; + private final RntbdToken requestCharge; @JsonProperty - final private RntbdToken requestValidationFailure; + private final RntbdToken requestValidationFailure; @JsonProperty - final private RntbdToken restoreState; + private final RntbdToken restoreState; @JsonProperty - final private RntbdToken retryAfterMilliseconds; + private final RntbdToken retryAfterMilliseconds; @JsonProperty - final private RntbdToken schemaVersion; + private final RntbdToken schemaVersion; @JsonProperty - final private RntbdToken scriptsExecuted; + private final RntbdToken scriptsExecuted; @JsonProperty - final private RntbdToken serverDateTimeUtc; + private final RntbdToken serverDateTimeUtc; @JsonProperty - final private RntbdToken sessionToken; + private final RntbdToken sessionToken; @JsonProperty - final private RntbdToken shareThroughput; + private final RntbdToken shareThroughput; @JsonProperty - final private RntbdToken storageMaxResoureQuota; + private final RntbdToken storageMaxResoureQuota; @JsonProperty - final private RntbdToken storageResourceQuotaUsage; + private final RntbdToken storageResourceQuotaUsage; @JsonProperty - final private RntbdToken subStatus; + private final RntbdToken subStatus; @JsonProperty - final private RntbdToken transportRequestID; + private final RntbdToken transportRequestID; @JsonProperty - final private RntbdToken writesPerformed; + private final RntbdToken writesPerformed; @JsonProperty - final private RntbdToken xpRole; + private final RntbdToken xpRole; // endregion @@ -211,13 +211,13 @@ boolean isPayloadPresent() { return this.payloadPresent.isPresent() && this.payloadPresent.getValue(Byte.class) != 0x00; } - List> asList(RntbdContext context, UUID activityId) { + List> asList(final RntbdContext context, final UUID activityId) { - ImmutableList.Builder> builder = ImmutableList.builderWithExpectedSize(this.computeCount() + 2); + final ImmutableList.Builder> builder = ImmutableList.builderWithExpectedSize(this.computeCount() + 2); builder.add(new Entry(HttpHeaders.SERVER_VERSION, context.getServerVersion())); builder.add(new Entry(HttpHeaders.ACTIVITY_ID, activityId.toString())); - collectEntries((token, toEntry) -> { + this.collectEntries((token, toEntry) -> { if (token.isPresent()) { builder.add(toEntry.apply(token)); } @@ -226,13 +226,13 @@ List> asList(RntbdContext context, UUID activityId) { return builder.build(); } - public Map asMap(RntbdContext context, UUID activityId) { + public Map asMap(final RntbdContext context, final UUID activityId) { - ImmutableMap.Builder builder = ImmutableMap.builderWithExpectedSize(this.computeCount() + 2); + final ImmutableMap.Builder builder = ImmutableMap.builderWithExpectedSize(this.computeCount() + 2); builder.put(new Entry(HttpHeaders.SERVER_VERSION, context.getServerVersion())); builder.put(new Entry(HttpHeaders.ACTIVITY_ID, activityId.toString())); - collectEntries((token, toEntry) -> { + this.collectEntries((token, toEntry) -> { if (token.isPresent()) { builder.put(toEntry.apply(token)); } @@ -241,80 +241,80 @@ public Map asMap(RntbdContext context, UUID activityId) { return builder.build(); } - static RntbdResponseHeaders decode(ByteBuf in) { - RntbdResponseHeaders headers = new RntbdResponseHeaders(); + static RntbdResponseHeaders decode(final ByteBuf in) { + final RntbdResponseHeaders headers = new RntbdResponseHeaders(); RntbdTokenStream.decode(in, headers); return headers; } - public static RntbdResponseHeaders fromMap(Map map, boolean payloadPresent) { + public static RntbdResponseHeaders fromMap(final Map map, final boolean payloadPresent) { - RntbdResponseHeaders headers = new RntbdResponseHeaders(); + final RntbdResponseHeaders headers = new RntbdResponseHeaders(); headers.payloadPresent.setValue(payloadPresent); headers.setValues(map); return headers; } - public void setValues(Map headers) { - - mapValue(this.LSN, BackendHeaders.LSN, Long::parseLong, headers); - mapValue(this.collectionLazyIndexProgress, HttpHeaders.COLLECTION_LAZY_INDEXING_PROGRESS, Integer::parseInt, headers); - mapValue(this.collectionLazyIndexProgress, BackendHeaders.COLLECTION_PARTITION_INDEX, Integer::parseInt, headers); - mapValue(this.collectionSecurityIdentifier, BackendHeaders.COLLECTION_SECURITY_IDENTIFIER, String::toString, headers); - mapValue(this.collectionServiceIndex, BackendHeaders.COLLECTION_SERVICE_INDEX, Integer::parseInt, headers); - mapValue(this.collectionUpdateProgress, HttpHeaders.COLLECTION_INDEX_TRANSFORMATION_PROGRESS, Integer::parseInt, headers); - mapValue(this.continuationToken, HttpHeaders.CONTINUATION, String::toString, headers); - mapValue(this.currentReplicaSetSize, BackendHeaders.CURRENT_REPLICA_SET_SIZE, Integer::parseInt, headers); - mapValue(this.currentWriteQuorum, BackendHeaders.CURRENT_WRITE_QUORUM, Integer::parseInt, headers); - mapValue(this.databaseAccountId, BackendHeaders.DATABASE_ACCOUNT_ID, String::toString, headers); - mapValue(this.disableRntbdChannel, HttpHeaders.DISABLE_RNTBD_CHANNEL, Boolean::parseBoolean, headers); - mapValue(this.eTag, HttpHeaders.E_TAG, String::toString, headers); - mapValue(this.globalCommittedLSN, BackendHeaders.GLOBAL_COMMITTED_LSN, Long::parseLong, headers); - mapValue(this.hasTentativeWrites, BackendHeaders.HAS_TENTATIVE_WRITES, Boolean::parseBoolean, headers); - mapValue(this.indexingDirective, HttpHeaders.INDEXING_DIRECTIVE, RntbdIndexingDirective::valueOf, headers); - mapValue(this.isRUPerMinuteUsed, BackendHeaders.IS_RU_PER_MINUTE_USED, Byte::parseByte, headers); - mapValue(this.itemCount, HttpHeaders.ITEM_COUNT, Integer::parseInt, headers); - mapValue(this.itemLSN, BackendHeaders.ITEM_LSN, Long::parseLong, headers); - mapValue(this.itemLocalLSN, BackendHeaders.ITEM_LOCAL_LSN, Long::parseLong, headers); - mapValue(this.lastStateChangeDateTime, HttpHeaders.LAST_STATE_CHANGE_UTC, String::toString, headers); - mapValue(this.lastStateChangeDateTime, HttpHeaders.LAST_STATE_CHANGE_UTC, String::toString, headers); - mapValue(this.localLSN, BackendHeaders.LOCAL_LSN, Long::parseLong, headers); - mapValue(this.logResults, HttpHeaders.LOG_RESULTS, String::toString, headers); - mapValue(this.numberOfReadRegions, BackendHeaders.NUMBER_OF_READ_REGIONS, Integer::parseInt, headers); - mapValue(this.offerReplacePending, BackendHeaders.OFFER_REPLACE_PENDING, Boolean::parseBoolean, headers); - mapValue(this.ownerFullName, HttpHeaders.OWNER_FULL_NAME, String::toString, headers); - mapValue(this.ownerId, HttpHeaders.OWNER_ID, String::toString, headers); - mapValue(this.partitionKeyRangeId, BackendHeaders.PARTITION_KEY_RANGE_ID, String::toString, headers); - mapValue(this.queryMetrics, BackendHeaders.QUERY_METRICS, String::toString, headers); - mapValue(this.quorumAckedLSN, BackendHeaders.QUORUM_ACKED_LSN, Long::parseLong, headers); - mapValue(this.quorumAckedLocalLSN, BackendHeaders.QUORUM_ACKED_LOCAL_LSN, Long::parseLong, headers); - mapValue(this.requestCharge, HttpHeaders.REQUEST_CHARGE, Double::parseDouble, headers); - mapValue(this.requestValidationFailure, BackendHeaders.REQUEST_VALIDATION_FAILURE, Byte::parseByte, headers); - mapValue(this.restoreState, BackendHeaders.RESTORE_STATE, String::toString, headers); - mapValue(this.retryAfterMilliseconds, HttpHeaders.RETRY_AFTER_IN_MILLISECONDS, Integer::parseInt, headers); - mapValue(this.schemaVersion, HttpHeaders.SCHEMA_VERSION, String::toString, headers); - mapValue(this.serverDateTimeUtc, HttpHeaders.X_DATE, String::toString, headers); - mapValue(this.sessionToken, HttpHeaders.SESSION_TOKEN, String::toString, headers); - mapValue(this.shareThroughput, BackendHeaders.SHARE_THROUGHPUT, Boolean::parseBoolean, headers); - mapValue(this.storageMaxResoureQuota, HttpHeaders.MAX_RESOURCE_QUOTA, String::toString, headers); - mapValue(this.storageResourceQuotaUsage, HttpHeaders.CURRENT_RESOURCE_QUOTA_USAGE, String::toString, headers); - mapValue(this.subStatus, BackendHeaders.SUB_STATUS, Integer::parseInt, headers); - mapValue(this.transportRequestID, HttpHeaders.TRANSPORT_REQUEST_ID, Integer::parseInt, headers); - mapValue(this.xpRole, BackendHeaders.XP_ROLE, Integer::parseInt, headers); + public void setValues(final Map headers) { + + this.mapValue(this.LSN, BackendHeaders.LSN, Long::parseLong, headers); + this.mapValue(this.collectionLazyIndexProgress, HttpHeaders.COLLECTION_LAZY_INDEXING_PROGRESS, Integer::parseInt, headers); + this.mapValue(this.collectionLazyIndexProgress, BackendHeaders.COLLECTION_PARTITION_INDEX, Integer::parseInt, headers); + this.mapValue(this.collectionSecurityIdentifier, BackendHeaders.COLLECTION_SECURITY_IDENTIFIER, String::toString, headers); + this.mapValue(this.collectionServiceIndex, BackendHeaders.COLLECTION_SERVICE_INDEX, Integer::parseInt, headers); + this.mapValue(this.collectionUpdateProgress, HttpHeaders.COLLECTION_INDEX_TRANSFORMATION_PROGRESS, Integer::parseInt, headers); + this.mapValue(this.continuationToken, HttpHeaders.CONTINUATION, String::toString, headers); + this.mapValue(this.currentReplicaSetSize, BackendHeaders.CURRENT_REPLICA_SET_SIZE, Integer::parseInt, headers); + this.mapValue(this.currentWriteQuorum, BackendHeaders.CURRENT_WRITE_QUORUM, Integer::parseInt, headers); + this.mapValue(this.databaseAccountId, BackendHeaders.DATABASE_ACCOUNT_ID, String::toString, headers); + this.mapValue(this.disableRntbdChannel, HttpHeaders.DISABLE_RNTBD_CHANNEL, Boolean::parseBoolean, headers); + this.mapValue(this.eTag, HttpHeaders.E_TAG, String::toString, headers); + this.mapValue(this.globalCommittedLSN, BackendHeaders.GLOBAL_COMMITTED_LSN, Long::parseLong, headers); + this.mapValue(this.hasTentativeWrites, BackendHeaders.HAS_TENTATIVE_WRITES, Boolean::parseBoolean, headers); + this.mapValue(this.indexingDirective, HttpHeaders.INDEXING_DIRECTIVE, RntbdIndexingDirective::valueOf, headers); + this.mapValue(this.isRUPerMinuteUsed, BackendHeaders.IS_RU_PER_MINUTE_USED, Byte::parseByte, headers); + this.mapValue(this.itemCount, HttpHeaders.ITEM_COUNT, Integer::parseInt, headers); + this.mapValue(this.itemLSN, BackendHeaders.ITEM_LSN, Long::parseLong, headers); + this.mapValue(this.itemLocalLSN, BackendHeaders.ITEM_LOCAL_LSN, Long::parseLong, headers); + this.mapValue(this.lastStateChangeDateTime, HttpHeaders.LAST_STATE_CHANGE_UTC, String::toString, headers); + this.mapValue(this.lastStateChangeDateTime, HttpHeaders.LAST_STATE_CHANGE_UTC, String::toString, headers); + this.mapValue(this.localLSN, BackendHeaders.LOCAL_LSN, Long::parseLong, headers); + this.mapValue(this.logResults, HttpHeaders.LOG_RESULTS, String::toString, headers); + this.mapValue(this.numberOfReadRegions, BackendHeaders.NUMBER_OF_READ_REGIONS, Integer::parseInt, headers); + this.mapValue(this.offerReplacePending, BackendHeaders.OFFER_REPLACE_PENDING, Boolean::parseBoolean, headers); + this.mapValue(this.ownerFullName, HttpHeaders.OWNER_FULL_NAME, String::toString, headers); + this.mapValue(this.ownerId, HttpHeaders.OWNER_ID, String::toString, headers); + this.mapValue(this.partitionKeyRangeId, BackendHeaders.PARTITION_KEY_RANGE_ID, String::toString, headers); + this.mapValue(this.queryMetrics, BackendHeaders.QUERY_METRICS, String::toString, headers); + this.mapValue(this.quorumAckedLSN, BackendHeaders.QUORUM_ACKED_LSN, Long::parseLong, headers); + this.mapValue(this.quorumAckedLocalLSN, BackendHeaders.QUORUM_ACKED_LOCAL_LSN, Long::parseLong, headers); + this.mapValue(this.requestCharge, HttpHeaders.REQUEST_CHARGE, Double::parseDouble, headers); + this.mapValue(this.requestValidationFailure, BackendHeaders.REQUEST_VALIDATION_FAILURE, Byte::parseByte, headers); + this.mapValue(this.restoreState, BackendHeaders.RESTORE_STATE, String::toString, headers); + this.mapValue(this.retryAfterMilliseconds, HttpHeaders.RETRY_AFTER_IN_MILLISECONDS, Integer::parseInt, headers); + this.mapValue(this.schemaVersion, HttpHeaders.SCHEMA_VERSION, String::toString, headers); + this.mapValue(this.serverDateTimeUtc, HttpHeaders.X_DATE, String::toString, headers); + this.mapValue(this.sessionToken, HttpHeaders.SESSION_TOKEN, String::toString, headers); + this.mapValue(this.shareThroughput, BackendHeaders.SHARE_THROUGHPUT, Boolean::parseBoolean, headers); + this.mapValue(this.storageMaxResoureQuota, HttpHeaders.MAX_RESOURCE_QUOTA, String::toString, headers); + this.mapValue(this.storageResourceQuotaUsage, HttpHeaders.CURRENT_RESOURCE_QUOTA_USAGE, String::toString, headers); + this.mapValue(this.subStatus, BackendHeaders.SUB_STATUS, Integer::parseInt, headers); + this.mapValue(this.transportRequestID, HttpHeaders.TRANSPORT_REQUEST_ID, Integer::parseInt, headers); + this.mapValue(this.xpRole, BackendHeaders.XP_ROLE, Integer::parseInt, headers); } @Override public String toString() { - ObjectWriter writer = RntbdObjectMapper.writer(); + final ObjectWriter writer = RntbdObjectMapper.writer(); try { return writer.writeValueAsString(this); - } catch (JsonProcessingException error) { + } catch (final JsonProcessingException error) { throw new CorruptedFrameException(error); } } - private void collectEntries(BiConsumer>> collector) { + private void collectEntries(final BiConsumer>> collector) { collector.accept(this.LSN, token -> toLongEntry(BackendHeaders.LSN, token) @@ -461,7 +461,7 @@ private void collectEntries(BiConsumer - toSessionTokenEntry(HttpHeaders.SESSION_TOKEN, token) + this.toSessionTokenEntry(HttpHeaders.SESSION_TOKEN, token) ); collector.accept(this.shareThroughput, token -> @@ -489,46 +489,46 @@ private void collectEntries(BiConsumer parse, Map headers) { + private void mapValue(final RntbdToken token, final String name, final Function parse, final Map headers) { - String value = headers.get(name); + final String value = headers.get(name); if (value != null) { token.setValue(parse.apply(value)); } } - private static Map.Entry toBooleanEntry(String name, RntbdToken token) { + private static Map.Entry toBooleanEntry(final String name, final RntbdToken token) { return new Entry(name, String.valueOf(token.getValue(Byte.class) != 0)); } - private static Map.Entry toByteEntry(String name, RntbdToken token) { + private static Map.Entry toByteEntry(final String name, final RntbdToken token) { return new Entry(name, Byte.toString(token.getValue(Byte.class))); } - private static Map.Entry toCurrencyEntry(String name, RntbdToken token) { - BigDecimal value = new BigDecimal(Math.round(token.getValue(Double.class) * 100D)).scaleByPowerOfTen(-2); + private static Map.Entry toCurrencyEntry(final String name, final RntbdToken token) { + final BigDecimal value = new BigDecimal(Math.round(token.getValue(Double.class) * 100D)).scaleByPowerOfTen(-2); return new Entry(name, value.toString()); } - private static Map.Entry toIntegerEntry(String name, RntbdToken token) { + private static Map.Entry toIntegerEntry(final String name, final RntbdToken token) { return new Entry(name, Long.toString(token.getValue(Long.class))); } - private static Map.Entry toLongEntry(String name, RntbdToken token) { + private static Map.Entry toLongEntry(final String name, final RntbdToken token) { return new Entry(name, Long.toString(token.getValue(Long.class))); } - private Map.Entry toSessionTokenEntry(String name, RntbdToken token) { + private Map.Entry toSessionTokenEntry(final String name, final RntbdToken token) { return new Entry(name, this.partitionKeyRangeId.getValue(String.class) + ":" + this.sessionToken.getValue(String.class)); } - private static Map.Entry toStringEntry(String name, RntbdToken token) { + private static Map.Entry toStringEntry(final String name, final RntbdToken token) { return new Entry(name, token.getValue(String.class)); } - final private static class Entry extends AbstractMap.SimpleImmutableEntry { - Entry(String name, String value) { + private static final class Entry extends AbstractMap.SimpleImmutableEntry { + Entry(final String name, final String value) { super(name, value); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseStatus.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseStatus.java index 57ebdc44b6e32..4988bf1aaf4e9 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseStatus.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseStatus.java @@ -39,21 +39,21 @@ final class RntbdResponseStatus { // region Fields - final static int LENGTH = Integer.BYTES // length + static final int LENGTH = Integer.BYTES // length + Integer.BYTES // status + 2 * Long.BYTES; // activityId @JsonProperty("activityId") - final private UUID activityId; + private final UUID activityId; @JsonProperty("length") - final private int length; + private final int length; - final private HttpResponseStatus status; + private final HttpResponseStatus status; // endregion - RntbdResponseStatus(int length, HttpResponseStatus status, UUID activityId) { + RntbdResponseStatus(final int length, final HttpResponseStatus status, final UUID activityId) { this.length = length; this.status = status; this.activityId = activityId; @@ -80,28 +80,28 @@ public int getStatusCode() { return this.status.code(); } - static RntbdResponseStatus decode(ByteBuf in) { + static RntbdResponseStatus decode(final ByteBuf in) { - long length = in.readUnsignedIntLE(); + final long length = in.readUnsignedIntLE(); if (!(LENGTH <= length && length <= Integer.MAX_VALUE)) { - String reason = String.format("frame length: %d", length); + final String reason = String.format("frame length: %d", length); throw new CorruptedFrameException(reason); } - int code = in.readIntLE(); - HttpResponseStatus status = HttpResponseStatus.valueOf(code); + final int code = in.readIntLE(); + final HttpResponseStatus status = HttpResponseStatus.valueOf(code); if (status == null) { - String reason = String.format("status code: %d", code); + final String reason = String.format("status code: %d", code); throw new CorruptedFrameException(reason); } - UUID activityId = RntbdUUID.decode(in); + final UUID activityId = RntbdUUID.decode(in); return new RntbdResponseStatus((int)length, status, activityId); } - void encode(ByteBuf out) { + void encode(final ByteBuf out) { out.writeIntLE(this.getLength()); out.writeIntLE(this.getStatusCode()); RntbdUUID.encode(this.getActivityId(), out); @@ -109,10 +109,10 @@ void encode(ByteBuf out) { @Override public String toString() { - ObjectWriter writer = RntbdObjectMapper.writer(); + final ObjectWriter writer = RntbdObjectMapper.writer(); try { return writer.writeValueAsString(this); - } catch (JsonProcessingException error) { + } catch (final JsonProcessingException error) { throw new CorruptedFrameException(error); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java new file mode 100644 index 0000000000000..8f36c15095d8b --- /dev/null +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java @@ -0,0 +1,354 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package com.azure.data.cosmos.directconnectivity.rntbd; + +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.directconnectivity.GoneException; +import com.azure.data.cosmos.directconnectivity.RntbdTransportClient.Options; +import com.azure.data.cosmos.internal.HttpConstants; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.google.common.collect.ImmutableMap; +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelOption; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.ssl.SslContext; +import io.netty.util.concurrent.DefaultThreadFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.SocketAddress; +import java.net.URI; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Stream; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + +@JsonSerialize(using = RntbdServiceEndpoint.JsonSerializer.class) +public final class RntbdServiceEndpoint implements RntbdEndpoint { + + private static final AtomicLong instanceCount = new AtomicLong(); + private static final Logger logger = LoggerFactory.getLogger(RntbdServiceEndpoint.class); + private static final String namePrefix = RntbdServiceEndpoint.class.getSimpleName() + '-'; + + private final RntbdClientChannelPool channelPool; + private final AtomicBoolean closed; + private final RntbdMetrics metrics; + private final String name; + private final SocketAddress remoteAddress; + private final RntbdRequestTimer requestTimer; + + // region Constructors + + private RntbdServiceEndpoint( + final Config config, final NioEventLoopGroup group, final RntbdRequestTimer timer, final URI physicalAddress + ) { + + final Bootstrap bootstrap = new Bootstrap() + .channel(NioSocketChannel.class) + .group(group) + .option(ChannelOption.AUTO_READ, true) + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectionTimeout()) + .option(ChannelOption.SO_KEEPALIVE, true) + .remoteAddress(physicalAddress.getHost(), physicalAddress.getPort()); + + this.name = RntbdServiceEndpoint.namePrefix + instanceCount.incrementAndGet(); + this.channelPool = new RntbdClientChannelPool(bootstrap, config); + this.remoteAddress = bootstrap.config().remoteAddress(); + this.metrics = new RntbdMetrics(this.name); + this.closed = new AtomicBoolean(); + this.requestTimer = timer; + } + + // endregion + + // region Accessors + + @Override + public String getName() { + return this.name; + } + + // endregion + + // region Methods + + @Override + public void close() { + if (this.closed.compareAndSet(false, true)) { + this.channelPool.close(); + this.metrics.close(); + } + } + + public RntbdRequestRecord request(final RntbdRequestArgs args) { + + this.throwIfClosed(); + + if (logger.isDebugEnabled()) { + args.traceOperation(logger, null, "request"); + logger.debug("\n {}\n {}\n REQUEST", this, args); + } + + final RntbdRequestRecord requestRecord = this.write(args); + this.metrics.incrementRequestCount(); + + requestRecord.whenComplete((response, error) -> { + + args.traceOperation(logger, null, "requestComplete", response, error); + this.metrics.incrementResponseCount(); + + if (error != null) { + this.metrics.incrementErrorResponseCount(); + } + + if (logger.isDebugEnabled()) { + if (error == null) { + final int status = response.getStatus(); + logger.debug("\n [{}]\n {}\n request succeeded with response status: {}", this, args, status); + } else { + logger.debug("\n [{}]\n {}\n request failed due to ", this, args, error); + } + } + }); + + return requestRecord; + } + + @Override + public String toString() { + return RntbdObjectMapper.toJson(this); + } + + // endregion + + // region Privates + + private void releaseToPool(final Channel channel) { + + logger.debug("\n [{}]\n {}\n RELEASE", this, channel); + + this.channelPool.release(channel).addListener(future -> { + if (logger.isDebugEnabled()) { + if (future.isSuccess()) { + logger.debug("\n [{}]\n {}\n release succeeded", this, channel); + } else { + logger.debug("\n [{}]\n {}\n release failed due to {}", this, channel, future.cause()); + } + } + }); + } + + private void throwIfClosed() { + checkState(!this.closed.get(), "%s is closed", this); + } + + private RntbdRequestRecord write(final RntbdRequestArgs requestArgs) { + + final RntbdRequestRecord requestRecord = new RntbdRequestRecord(requestArgs, this.requestTimer); + logger.debug("\n [{}]\n {}\n WRITE", this, requestArgs); + + this.channelPool.acquire().addListener(connected -> { + + if (connected.isSuccess()) { + + requestArgs.traceOperation(logger, null, "write"); + final Channel channel = (Channel)connected.get(); + this.releaseToPool(channel); + + channel.write(requestRecord).addListener((ChannelFuture future) -> { + requestArgs.traceOperation(logger, null, "writeComplete", channel); + if (!future.isSuccess()) { + this.metrics.incrementErrorResponseCount(); + } + }); + + return; + } + + final UUID activityId = requestArgs.getActivityId(); + final Throwable cause = connected.cause(); + + if (connected.isCancelled()) { + + logger.debug("\n [{}]\n {}\n write cancelled: {}", this, requestArgs, cause); + requestRecord.cancel(true); + + } else { + + logger.debug("\n [{}]\n {}\n write failed due to {} ", this, requestArgs, cause); + final String reason = cause.getMessage(); + + final GoneException goneException = new GoneException( + String.format("failed to establish connection to %s: %s", this.remoteAddress, reason), + cause instanceof Exception ? (Exception)cause : new IOException(reason, cause), + ImmutableMap.of(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId.toString()), + requestArgs.getReplicaPath() + ); + + BridgeInternal.setRequestHeaders(goneException, requestArgs.getServiceRequest().getHeaders()); + requestRecord.completeExceptionally(goneException); + } + }); + + return requestRecord; + } + + // endregion + + // region Types + + static final class JsonSerializer extends StdSerializer { + + public JsonSerializer() { + this(null); + } + + public JsonSerializer(Class type) { + super(type); + } + + @Override + public void serialize(RntbdServiceEndpoint value, JsonGenerator generator, SerializerProvider provider) + throws IOException { + + generator.writeStartObject(); + generator.writeStringField(value.name, value.remoteAddress.toString()); + generator.writeObjectField("channelPool", value.channelPool); + generator.writeEndObject(); + } + } + + public static final class Provider implements RntbdEndpoint.Provider { + + private static final Logger logger = LoggerFactory.getLogger(Provider.class); + + private final AtomicBoolean closed = new AtomicBoolean(); + private final Config config; + private final ConcurrentHashMap endpoints = new ConcurrentHashMap<>(); + private final NioEventLoopGroup eventLoopGroup; + private final RntbdRequestTimer requestTimer; + + public Provider(final Options options, final SslContext sslContext) { + + checkNotNull(options, "options"); + checkNotNull(sslContext, "sslContext"); + + final DefaultThreadFactory threadFactory = new DefaultThreadFactory("CosmosEventLoop", true); + final int threadCount = Runtime.getRuntime().availableProcessors(); + final LogLevel wireLogLevel; + + if (logger.isTraceEnabled()) { + wireLogLevel = LogLevel.TRACE; + } else if (logger.isDebugEnabled()) { + wireLogLevel = LogLevel.DEBUG; + } else { + wireLogLevel = null; + } + + this.config = new Config(options, sslContext, wireLogLevel); + this.requestTimer = new RntbdRequestTimer(config.getRequestTimeout()); + this.eventLoopGroup = new NioEventLoopGroup(threadCount, threadFactory); + } + + @Override + public void close() throws RuntimeException { + + if (this.closed.compareAndSet(false, true)) { + + this.requestTimer.close(); + + for (final RntbdEndpoint endpoint : this.endpoints.values()) { + endpoint.close(); + } + + this.eventLoopGroup.shutdownGracefully().addListener(future -> { + if (future.isSuccess()) { + logger.debug("\n [{}]\n closed endpoints", this); + return; + } + logger.error("\n [{}]\n failed to close endpoints due to ", this, future.cause()); + }); + return; + } + + logger.debug("\n [{}]\n already closed", this); + } + + @Override + public Config config() { + return this.config; + } + + @Override + public int count() { + return this.endpoints.size(); + } + + @Override + public RntbdEndpoint get(URI physicalAddress) { + return endpoints.computeIfAbsent(physicalAddress.getAuthority(), authority -> + new RntbdServiceEndpoint(config, eventLoopGroup, requestTimer, physicalAddress) + ); + } + + @Override + public Stream list() { + return this.endpoints.values().stream(); + } + + private void deleteEndpoint(final URI physicalAddress) { + + // TODO: DANOBLE: Utilize this method of tearing down unhealthy endpoints + // Specifically, ensure that this method is called when a Read/WriteTimeoutException occurs or a health + // check request fails. This perhaps likely requires a change to RntbdClientChannelPool. + // Links: + // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/331552 + // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/331593 + + checkNotNull(physicalAddress, "physicalAddress: %s", physicalAddress); + + final String authority = physicalAddress.getAuthority(); + final RntbdEndpoint endpoint = this.endpoints.remove(authority); + + if (endpoint != null) { + endpoint.close(); + } + } + } + + // endregion +} diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdToken.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdToken.java index 85169cff66dcf..c02e68fd1268f 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdToken.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdToken.java @@ -24,30 +24,28 @@ package com.azure.data.cosmos.directconnectivity.rntbd; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.PropertyWriter; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import io.netty.buffer.ByteBuf; -import io.netty.handler.codec.CorruptedFrameException; - -import java.util.Objects; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdHeader; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; @JsonPropertyOrder({ "id", "name", "type", "present", "required", "value" }) -class RntbdToken { +final class RntbdToken { // region Fields private static final int HEADER_LENGTH = Short.BYTES + Byte.BYTES; static { - RntbdObjectMapper.registerPropertyFilter(RntbdToken.class, PropertyFilter.class); + RntbdObjectMapper.registerPropertyFilter(RntbdToken.class, RntbdToken.PropertyFilter.class); } private final RntbdHeader header; @@ -56,39 +54,43 @@ class RntbdToken { // endregion - private RntbdToken(RntbdHeader header) { - Objects.requireNonNull(header); + // region Constructors + + private RntbdToken(final RntbdHeader header) { + checkNotNull(header, "header"); this.header = header; this.value = null; this.length = Integer.MIN_VALUE; } - @JsonProperty - RntbdTokenType getType() { - return this.header.type(); - } + // endregion // region Accessors @JsonProperty - final short getId() { + public short getId() { return this.header.id(); } @JsonProperty - final String getName() { + public String getName() { return this.header.name(); } @JsonProperty - final Object getValue() { + public RntbdTokenType getTokenType() { + return this.header.type(); + } + + @JsonProperty + public Object getValue() { if (this.value == null) { return this.header.type().codec().defaultValue(); } if (this.value instanceof ByteBuf) { - ByteBuf buffer = (ByteBuf)this.value; + final ByteBuf buffer = (ByteBuf)this.value; this.value = this.header.type().codec().read(buffer); buffer.release(); } else { @@ -98,39 +100,29 @@ final Object getValue() { return this.value; } - final int computeLength() { - - if (!this.isPresent()) { - return 0; - } - - if (this.value instanceof ByteBuf) { - ByteBuf buffer = (ByteBuf)this.value; - assert buffer.readerIndex() == 0; - return HEADER_LENGTH + buffer.readableBytes(); - } - - if (this.length == Integer.MIN_VALUE) { - this.length = HEADER_LENGTH + this.header.type().codec().computeLength(this.value); - } - - return this.length; + public T getValue(final Class cls) { + return cls.cast(this.getValue()); } @JsonProperty - final void setValue(Object value) { + public void setValue(final Object value) { this.ensureValid(value); this.length = Integer.MIN_VALUE; this.value = value; } + @JsonIgnore + public final Class getValueType() { + return this.header.type().codec().valueType(); + } + @JsonProperty - final boolean isPresent() { + public boolean isPresent() { return this.value != null; } @JsonProperty - final boolean isRequired() { + public boolean isRequired() { return this.header.isRequired(); } @@ -138,73 +130,82 @@ final boolean isRequired() { // region Methods - static RntbdToken create(RntbdHeader header) { + public int computeLength() { + + if (!this.isPresent()) { + return 0; + } + + if (this.value instanceof ByteBuf) { + final ByteBuf buffer = (ByteBuf)this.value; + assert buffer.readerIndex() == 0; + return HEADER_LENGTH + buffer.readableBytes(); + } + + if (this.length == Integer.MIN_VALUE) { + this.length = HEADER_LENGTH + this.header.type().codec().computeLength(this.value); + } + + return this.length; + } + + public static RntbdToken create(final RntbdHeader header) { return new RntbdToken(header); } - void decode(ByteBuf in) { + public void decode(final ByteBuf in) { - Objects.requireNonNull(in); + checkNotNull(in, "in"); if (this.value instanceof ByteBuf) { ((ByteBuf)this.value).release(); } - this.value = this.header.type().codec().readSlice(in).retain(); // No data transfer until the first call to RntbdToken.value + this.value = this.header.type().codec().readSlice(in).retain(); // No data transfer until the first call to RntbdToken.getValue } - final void encode(ByteBuf out) { + public void encode(final ByteBuf out) { - Objects.requireNonNull(out); + checkNotNull(out, "out"); if (!this.isPresent()) { if (this.isRequired()) { - String message = String.format("Missing value for required header: %s", this); + final String message = String.format("Missing value for required header: %s", this); throw new IllegalStateException(message); } return; } out.writeShortLE(this.getId()); - out.writeByte(this.getType().id()); + out.writeByte(this.getTokenType().id()); if (this.value instanceof ByteBuf) { out.writeBytes((ByteBuf)this.value); } else { - this.ensureValid(value); - this.header.type().codec().write(value, out); + this.ensureValid(this.value); + this.header.type().codec().write(this.value, out); } } - @Override - public String toString() { - ObjectWriter writer = RntbdObjectMapper.writer(); - try { - return writer.writeValueAsString(this); - } catch (JsonProcessingException error) { - throw new CorruptedFrameException(error); - } - } - - final T getValue(Class cls) { - return cls.cast(this.getValue()); - } - - final void releaseBuffer() { + public void releaseBuffer() { if (this.value instanceof ByteBuf) { - ByteBuf buffer = (ByteBuf)this.value; + final ByteBuf buffer = (ByteBuf)this.value; buffer.release(); } } - private void ensureValid(Object value) { + @Override + public String toString() { + return RntbdObjectMapper.toJson(this); + } - Objects.requireNonNull(value); + // endregion - if (!this.header.type().codec().isValid(value)) { - String reason = String.format("value: %s", value.getClass()); - throw new IllegalArgumentException(reason); - } + // region Privates + + private void ensureValid(final Object value) { + checkNotNull(value, "value"); + checkArgument(this.header.type().codec().isValid(value), "value: %s", value.getClass()); } // endregion @@ -214,11 +215,11 @@ private void ensureValid(Object value) { static class PropertyFilter extends SimpleBeanPropertyFilter { @Override - public void serializeAsField(Object object, JsonGenerator generator, SerializerProvider provider, PropertyWriter writer) throws Exception { + public void serializeAsField(final Object object, final JsonGenerator generator, final SerializerProvider provider, final PropertyWriter writer) throws Exception { if (generator.canOmitFields()) { - Object value = writer.getMember().getValue(object); + final Object value = writer.getMember().getValue(object); if (value instanceof RntbdToken && !((RntbdToken)value).isPresent()) { return; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenStream.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenStream.java index 61ef60106e689..9e47a16210709 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenStream.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenStream.java @@ -29,22 +29,23 @@ import com.google.common.collect.Maps; import io.netty.buffer.ByteBuf; -import java.util.Objects; import java.util.stream.Collector; import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdHeader; +import static com.google.common.base.Preconditions.checkNotNull; +@SuppressWarnings("UnstableApiUsage") abstract class RntbdTokenStream & RntbdHeader> { final ImmutableMap headers; final ImmutableMap tokens; - RntbdTokenStream(ImmutableSet headers, ImmutableMap ids) { + RntbdTokenStream(final ImmutableSet headers, final ImmutableMap ids) { - Objects.requireNonNull(headers, "headers"); - Objects.requireNonNull(ids, "ids"); + checkNotNull(headers, "headers"); + checkNotNull(ids, "ids"); - Collector> collector = Maps.toImmutableEnumMap(h -> h, RntbdToken::create); + final Collector> collector = Maps.toImmutableEnumMap(h -> h, RntbdToken::create); this.tokens = headers.stream().collect(collector); this.headers = ids; } @@ -53,7 +54,7 @@ final int computeCount() { int count = 0; - for (RntbdToken token : this.tokens.values()) { + for (final RntbdToken token : this.tokens.values()) { if (token.isPresent()) { ++count; } @@ -66,14 +67,14 @@ final int computeLength() { int total = 0; - for (RntbdToken token : this.tokens.values()) { + for (final RntbdToken token : this.tokens.values()) { total += token.computeLength(); } return total; } - static > T decode(ByteBuf in, T stream) { + static > T decode(final ByteBuf in, final T stream) { while (in.readableBytes() > 0) { @@ -89,10 +90,10 @@ static > T decode(ByteBuf in, T stream) { token.decode(in); } - for (RntbdToken token : stream.tokens.values()) { + for (final RntbdToken token : stream.tokens.values()) { if (!token.isPresent() && token.isRequired()) { - String reason = String.format("Required token not found on RNTBD stream: type: %s, identifier: %s", - token.getType(), token.getId()); + final String reason = String.format("Required token not found on RNTBD stream: type: %s, identifier: %s", + token.getTokenType(), token.getId()); throw new IllegalStateException(reason); } } @@ -100,28 +101,28 @@ static > T decode(ByteBuf in, T stream) { return stream; } - final void encode(ByteBuf out) { - for (RntbdToken token : this.tokens.values()) { + final void encode(final ByteBuf out) { + for (final RntbdToken token : this.tokens.values()) { token.encode(out); } } - final RntbdToken get(T header) { + final RntbdToken get(final T header) { return this.tokens.get(header); } final void releaseBuffers() { - for (RntbdToken token : this.tokens.values()) { + for (final RntbdToken token : this.tokens.values()) { token.releaseBuffer(); } } - final static private class UndefinedHeader implements RntbdHeader { + private static final class UndefinedHeader implements RntbdHeader { - final private short id; - final private RntbdTokenType type; + private final short id; + private final RntbdTokenType type; - UndefinedHeader(short id, RntbdTokenType type) { + UndefinedHeader(final short id, final RntbdTokenType type) { this.id = id; this.type = type; } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenType.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenType.java index cf0ff0a6bb65c..a88a944963bc5 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenType.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenType.java @@ -24,17 +24,18 @@ package com.azure.data.cosmos.directconnectivity.rntbd; +import com.google.common.base.Strings; import com.google.common.base.Utf8; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; -import io.netty.handler.codec.CorruptedFrameException; +import io.netty.handler.codec.DecoderException; import java.nio.charset.StandardCharsets; import java.util.UUID; enum RntbdTokenType { - // ALL values are encoded as little endian byte sequences except for Guid + // All values are encoded as little endian byte sequences except for Guid // Guid values are serialized in Microsoft GUID byte order // Reference: GUID structure and System.Guid type @@ -46,9 +47,9 @@ enum RntbdTokenType { LongLong((byte)0x05, RntbdLong.codec), // long => long Guid((byte)0x06, RntbdGuid.codec), // byte[16] => UUID - SmallString((byte)0x07, RntbdShortString.codec), // (byte, byte[0..255]) => STRING - String((byte)0x08, RntbdString.codec), // (short, byte[0..64KiB]) => STRING - ULongString((byte)0x09, RntbdLongString.codec), // (int, byte[0..2GiB-1]) => STRING + SmallString((byte)0x07, RntbdShortString.codec), // (byte, byte[0..255]) => String + String((byte)0x08, RntbdString.codec), // (short, byte[0..64KiB]) => String + ULongString((byte)0x09, RntbdLongString.codec), // (int, byte[0..2GiB-1]) => String SmallBytes((byte)0x0A, RntbdShortBytes.codec), // (byte, byte[0..255]) => byte[] Bytes((byte)0x0B, RntbdBytes.codec), // (short, byte[0..64KiB]) => byte[] @@ -64,14 +65,18 @@ enum RntbdTokenType { private Codec codec; private byte id; - RntbdTokenType(byte id, Codec codec) { + RntbdTokenType(final byte id, final Codec codec) { this.codec = codec; this.id = id; } - public static RntbdTokenType fromId(byte value) { + public Codec codec() { + return this.codec; + } - for (RntbdTokenType tokenType : RntbdTokenType.values()) { + public static RntbdTokenType fromId(final byte value) { + + for (final RntbdTokenType tokenType : RntbdTokenType.values()) { if (value == tokenType.id) { return tokenType; } @@ -79,10 +84,6 @@ public static RntbdTokenType fromId(byte value) { return Invalid; } - public Codec codec() { - return this.codec; - } - public byte id() { return this.id; } @@ -105,6 +106,8 @@ public interface Codec { ByteBuf readSlice(ByteBuf in); + Class valueType(); + void write(Object value, ByteBuf out); } @@ -116,14 +119,14 @@ private RntbdByte() { } @Override - public final int computeLength(Object value) { + public final int computeLength(final Object value) { return java.lang.Byte.BYTES; } @Override - public final Object convert(Object value) { + public final Object convert(final Object value) { - assert isValid(value); + assert this.isValid(value); if (value instanceof Number) { return ((Number)value).byteValue(); @@ -137,24 +140,29 @@ public final Object defaultValue() { } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return value instanceof Number || value instanceof Boolean; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { return in.readByte(); } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return in.readSlice(java.lang.Byte.BYTES); } @Override - public final void write(Object value, ByteBuf out) { - assert isValid(value); - out.writeByte(value instanceof Byte ? (byte)value : ((boolean)value ? 0x01 : 0x00)); + public final Class valueType() { + return java.lang.Byte.class; + } + + @Override + public final void write(final Object value, final ByteBuf out) { + assert this.isValid(value); + out.writeByte(value instanceof java.lang.Byte ? (byte)value : ((boolean)value ? 0x01 : 0x00)); } } @@ -167,14 +175,14 @@ private RntbdBytes() { } @Override - public int computeLength(Object value) { - assert isValid(value); + public int computeLength(final Object value) { + assert this.isValid(value); return Short.BYTES + ((byte[])value).length; } @Override - public final Object convert(Object value) { - assert isValid(value); + public final Object convert(final Object value) { + assert this.isValid(value); return value; } @@ -184,29 +192,34 @@ public final Object defaultValue() { } @Override - public boolean isValid(Object value) { + public boolean isValid(final Object value) { return value instanceof byte[] && ((byte[])value).length < 0xFFFF; } @Override - public Object read(ByteBuf in) { - int length = in.readUnsignedShortLE(); + public Object read(final ByteBuf in) { + final int length = in.readUnsignedShortLE(); return in.readBytes(length); } @Override - public ByteBuf readSlice(ByteBuf in) { - int length = in.getUnsignedShortLE(in.readerIndex()); + public ByteBuf readSlice(final ByteBuf in) { + final int length = in.getUnsignedShortLE(in.readerIndex()); return in.readSlice(Short.BYTES + length); } @Override - public void write(Object value, ByteBuf out) { + public Class valueType() { + return java.lang.Byte[].class; + } + + @Override + public void write(final Object value, final ByteBuf out) { - assert isValid(value); + assert this.isValid(value); - byte[] bytes = (byte[])value; - int length = bytes.length; + final byte[] bytes = (byte[])value; + final int length = bytes.length; if (length > 0xFFFF) { throw new IllegalStateException(); @@ -225,14 +238,14 @@ private RntbdDouble() { } @Override - public final int computeLength(Object value) { - assert isValid(value); + public final int computeLength(final Object value) { + assert this.isValid(value); return java.lang.Double.BYTES; } @Override - public final Object convert(Object value) { - assert isValid(value); + public final Object convert(final Object value) { + assert this.isValid(value); return ((Number)value).doubleValue(); } @@ -242,23 +255,28 @@ public final Object defaultValue() { } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return value instanceof Number; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { return in.readDoubleLE(); } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return in.readSlice(java.lang.Double.BYTES); } @Override - public final void write(Object value, ByteBuf out) { - assert isValid(value); + public Class valueType() { + return java.lang.Double.class; + } + + @Override + public final void write(final Object value, final ByteBuf out) { + assert this.isValid(value); out.writeDoubleLE(((Number)value).doubleValue()); } } @@ -271,14 +289,14 @@ private RntbdFloat() { } @Override - public final int computeLength(Object value) { - assert isValid(value); + public final int computeLength(final Object value) { + assert this.isValid(value); return java.lang.Float.BYTES; } @Override - public final Object convert(Object value) { - assert isValid(value); + public final Object convert(final Object value) { + assert this.isValid(value); return ((Number)value).floatValue(); } @@ -288,23 +306,28 @@ public final Object defaultValue() { } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return value instanceof Number; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { return in.readFloatLE(); } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return in.readSlice(java.lang.Float.BYTES); } @Override - public final void write(Object value, ByteBuf out) { - assert isValid(value); + public Class valueType() { + return java.lang.Float.class; + } + + @Override + public final void write(final Object value, final ByteBuf out) { + assert this.isValid(value); out.writeFloatLE(((Number)value).floatValue()); } } @@ -317,14 +340,14 @@ private RntbdGuid() { } @Override - public final int computeLength(Object value) { - assert isValid(value); + public final int computeLength(final Object value) { + assert this.isValid(value); return 2 * java.lang.Long.BYTES; } @Override - public final Object convert(Object value) { - assert isValid(value); + public final Object convert(final Object value) { + assert this.isValid(value); return value; } @@ -334,23 +357,28 @@ public final Object defaultValue() { } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return value instanceof UUID; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { return RntbdUUID.decode(in); } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return in.readSlice(2 * java.lang.Long.BYTES); } @Override - public final void write(Object value, ByteBuf out) { - assert isValid(value); + public Class valueType() { + return UUID.class; + } + + @Override + public final void write(final Object value, final ByteBuf out) { + assert this.isValid(value); RntbdUUID.encode((UUID)value, out); } } @@ -363,14 +391,14 @@ private RntbdInteger() { } @Override - public final int computeLength(Object value) { - assert isValid(value); + public final int computeLength(final Object value) { + assert this.isValid(value); return Integer.BYTES; } @Override - public final Object convert(Object value) { - assert isValid(value); + public final Object convert(final Object value) { + assert this.isValid(value); return ((Number)value).intValue(); } @@ -380,23 +408,28 @@ public final Object defaultValue() { } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return value instanceof Number; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { return in.readIntLE(); } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return in.readSlice(Integer.BYTES); } @Override - public final void write(Object value, ByteBuf out) { - assert isValid(value); + public Class valueType() { + return Integer.class; + } + + @Override + public final void write(final Object value, final ByteBuf out) { + assert this.isValid(value); out.writeIntLE(((Number)value).intValue()); } } @@ -409,14 +442,14 @@ private RntbdLong() { } @Override - public final int computeLength(Object value) { - assert isValid(value); + public final int computeLength(final Object value) { + assert this.isValid(value); return java.lang.Long.BYTES; } @Override - public final Object convert(Object value) { - assert isValid(value); + public final Object convert(final Object value) { + assert this.isValid(value); return ((Number)value).longValue(); } @@ -426,23 +459,28 @@ public final Object defaultValue() { } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return value instanceof Number; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { return in.readLongLE(); } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return in.readSlice(java.lang.Long.BYTES); } @Override - public final void write(Object value, ByteBuf out) { - assert isValid(value); + public Class valueType() { + return java.lang.Long.class; + } + + @Override + public final void write(final Object value, final ByteBuf out) { + assert this.isValid(value); out.writeLongLE(((Number)value).longValue()); } } @@ -455,20 +493,20 @@ private RntbdLongBytes() { } @Override - public final int computeLength(Object value) { - assert isValid(value); + public final int computeLength(final Object value) { + assert this.isValid(value); return Integer.BYTES + ((byte[])value).length; } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return value instanceof byte[] && ((byte[])value).length < 0xFFFF; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { - long length = in.readUnsignedIntLE(); + final long length = in.readUnsignedIntLE(); if (length > Integer.MAX_VALUE) { throw new IllegalStateException(); @@ -477,9 +515,9 @@ public final Object read(ByteBuf in) { } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { - long length = in.getUnsignedIntLE(in.readerIndex()); + final long length = in.getUnsignedIntLE(in.readerIndex()); if (length > Integer.MAX_VALUE) { throw new IllegalStateException(); @@ -488,11 +526,11 @@ public final ByteBuf readSlice(ByteBuf in) { } @Override - public final void write(Object value, ByteBuf out) { + public final void write(final Object value, final ByteBuf out) { - assert isValid(value); + assert this.isValid(value); - byte[] bytes = (byte[])value; + final byte[] bytes = (byte[])value; out.writeIntLE(bytes.length); out.writeBytes(bytes); } @@ -506,14 +544,14 @@ private RntbdLongString() { } @Override - public final int computeLength(Object value) { + public final int computeLength(final Object value) { return Integer.BYTES + this.computeLength(value, Integer.MAX_VALUE); } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { - long length = in.readUnsignedIntLE(); + final long length = in.readUnsignedIntLE(); if (length > Integer.MAX_VALUE) { throw new IllegalStateException(); @@ -523,9 +561,9 @@ public final Object read(ByteBuf in) { } @Override - public final void write(Object value, ByteBuf out) { + public final void write(final Object value, final ByteBuf out) { - int length = this.computeLength(value, Integer.MAX_VALUE); + final int length = this.computeLength(value, Integer.MAX_VALUE); out.writeIntLE(length); writeValue(out, value, length); } @@ -536,12 +574,12 @@ private static class RntbdNone implements Codec { public static final Codec codec = new RntbdNone(); @Override - public final int computeLength(Object value) { + public final int computeLength(final Object value) { return 0; } @Override - public final Object convert(Object value) { + public final Object convert(final Object value) { return null; } @@ -551,22 +589,27 @@ public final Object defaultValue() { } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return true; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { return null; } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return null; } @Override - public final void write(Object value, ByteBuf out) { + public Class valueType() { + return null; + } + + @Override + public final void write(final Object value, final ByteBuf out) { } } @@ -578,38 +621,38 @@ private RntbdShortBytes() { } @Override - public final int computeLength(Object value) { - assert isValid(value); + public final int computeLength(final Object value) { + assert this.isValid(value); return java.lang.Byte.BYTES + ((byte[])value).length; } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return value instanceof byte[] && ((byte[])value).length < 0xFFFF; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { - int length = in.readUnsignedByte(); - byte[] bytes = new byte[length]; + final int length = in.readUnsignedByte(); + final byte[] bytes = new byte[length]; in.readBytes(bytes); return bytes; } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return in.readSlice(java.lang.Byte.BYTES + in.getUnsignedByte(in.readerIndex())); } @Override - public final void write(Object value, ByteBuf out) { + public final void write(final Object value, final ByteBuf out) { - assert isValid(value); + assert this.isValid(value); - byte[] bytes = (byte[])value; - int length = bytes.length; + final byte[] bytes = (byte[])value; + final int length = bytes.length; if (length > 0xFF) { throw new IllegalStateException(); @@ -628,24 +671,24 @@ private RntbdShortString() { } @Override - public final int computeLength(Object value) { + public final int computeLength(final Object value) { return java.lang.Byte.BYTES + this.computeLength(value, 0xFF); } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { return in.readCharSequence(in.readUnsignedByte(), StandardCharsets.UTF_8).toString(); } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return in.readSlice(java.lang.Byte.BYTES + in.getUnsignedByte(in.readerIndex())); } @Override - public final void write(Object value, ByteBuf out) { + public final void write(final Object value, final ByteBuf out) { - int length = this.computeLength(value, 0xFF); + final int length = this.computeLength(value, 0xFF); out.writeByte(length); writeValue(out, value, length); } @@ -658,45 +701,45 @@ private static class RntbdString implements Codec { private RntbdString() { } - final int computeLength(Object value, int maxLength) { + final int computeLength(final Object value, final int maxLength) { - assert isValid(value); - int length; + assert this.isValid(value); + final int length; - if (value instanceof String) { + if (value instanceof java.lang.String) { - String string = (String)value; + final java.lang.String string = (java.lang.String)value; length = Utf8.encodedLength(string); } else { - byte[] string = (byte[])value; + final byte[] string = (byte[])value; if (!Utf8.isWellFormed(string)) { - String reason = java.lang.String.format("UTF-8 byte string is ill-formed: %s", ByteBufUtil.hexDump(string)); - throw new CorruptedFrameException(reason); + final java.lang.String reason = Strings.lenientFormat("UTF-8 byte string is ill-formed: %s", ByteBufUtil.hexDump(string)); + throw new DecoderException(reason); } length = string.length; } if (length > maxLength) { - String reason = java.lang.String.format("UTF-8 byte string exceeds %d bytes: %d bytes", maxLength, length); - throw new CorruptedFrameException(reason); + final java.lang.String reason = Strings.lenientFormat("UTF-8 byte string exceeds %s bytes: %s bytes", maxLength, length); + throw new DecoderException(reason); } return length; } @Override - public int computeLength(Object value) { + public int computeLength(final Object value) { return Short.BYTES + this.computeLength(value, 0xFFFF); } @Override - public final Object convert(Object value) { - assert isValid(value); - return value instanceof String ? value : new String((byte[])value, StandardCharsets.UTF_8); + public final Object convert(final Object value) { + assert this.isValid(value); + return value instanceof java.lang.String ? value : new String((byte[])value, StandardCharsets.UTF_8); } @Override @@ -705,35 +748,40 @@ public final Object defaultValue() { } @Override - public final boolean isValid(Object value) { - return value instanceof String || value instanceof byte[]; + public final boolean isValid(final Object value) { + return value instanceof java.lang.String || value instanceof byte[]; } @Override - public Object read(ByteBuf in) { - int length = in.readUnsignedShortLE(); + public Object read(final ByteBuf in) { + final int length = in.readUnsignedShortLE(); return in.readCharSequence(length, StandardCharsets.UTF_8).toString(); } @Override - public ByteBuf readSlice(ByteBuf in) { + public ByteBuf readSlice(final ByteBuf in) { return in.readSlice(Short.BYTES + in.getUnsignedShortLE(in.readerIndex())); } @Override - public void write(Object value, ByteBuf out) { + public Class valueType() { + return java.lang.String.class; + } - int length = this.computeLength(value, 0xFFFF); + @Override + public void write(final Object value, final ByteBuf out) { + + final int length = this.computeLength(value, 0xFFFF); out.writeShortLE(length); writeValue(out, value, length); } - static void writeValue(ByteBuf out, Object value, int length) { + static void writeValue(final ByteBuf out, final Object value, final int length) { - int start = out.writerIndex(); + final int start = out.writerIndex(); - if (value instanceof String) { - out.writeCharSequence((String)value, StandardCharsets.UTF_8); + if (value instanceof java.lang.String) { + out.writeCharSequence((java.lang.String)value, StandardCharsets.UTF_8); } else { out.writeBytes((byte[])value); } @@ -750,14 +798,14 @@ private RntbdUnsignedInteger() { } @Override - public final int computeLength(Object value) { - assert isValid(value); + public final int computeLength(final Object value) { + assert this.isValid(value); return Integer.BYTES; } @Override - public final Object convert(Object value) { - assert isValid(value); + public final Object convert(final Object value) { + assert this.isValid(value); return ((Number)value).longValue() & 0xFFFFFFFFL; } @@ -767,23 +815,28 @@ public final Object defaultValue() { } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return value instanceof Number; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { return in.readUnsignedIntLE(); } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return in.readSlice(Integer.BYTES); } @Override - public final void write(Object value, ByteBuf out) { - assert isValid(value); + public Class valueType() { + return java.lang.Long.class; + } + + @Override + public final void write(final Object value, final ByteBuf out) { + assert this.isValid(value); out.writeIntLE(((Number)value).intValue()); } } @@ -796,14 +849,14 @@ private RntbdUnsignedShort() { } @Override - public final int computeLength(Object value) { - assert isValid(value); + public final int computeLength(final Object value) { + assert this.isValid(value); return Short.BYTES; } @Override - public final Object convert(Object value) { - assert isValid(value); + public final Object convert(final Object value) { + assert this.isValid(value); return ((Number)value).intValue() & 0xFFFF; } @@ -813,23 +866,28 @@ public final Object defaultValue() { } @Override - public final boolean isValid(Object value) { + public final boolean isValid(final Object value) { return value instanceof Number; } @Override - public final Object read(ByteBuf in) { + public final Object read(final ByteBuf in) { return in.readUnsignedShortLE(); } @Override - public final ByteBuf readSlice(ByteBuf in) { + public final ByteBuf readSlice(final ByteBuf in) { return in.readSlice(Short.BYTES); } @Override - public final void write(Object value, ByteBuf out) { - assert isValid(value); + public Class valueType() { + return Integer.class; + } + + @Override + public final void write(final Object value, final ByteBuf out) { + assert this.isValid(value); out.writeShortLE(((Number)value).shortValue()); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdUUID.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdUUID.java index cab3162b3c21c..37ed4f14f7bcd 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdUUID.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdUUID.java @@ -28,12 +28,13 @@ import io.netty.buffer.Unpooled; import io.netty.handler.codec.CorruptedFrameException; -import java.util.Objects; import java.util.UUID; -final public class RntbdUUID { +import static com.google.common.base.Preconditions.checkNotNull; - final public static UUID EMPTY = new UUID(0L, 0L); +public final class RntbdUUID { + + public static final UUID EMPTY = new UUID(0L, 0L); private RntbdUUID() { } @@ -44,7 +45,7 @@ private RntbdUUID() { * @param bytes a {@link byte} array containing the serialized {@link UUID} to be decoded * @return a new {@link UUID} */ - public static UUID decode(byte[] bytes) { + public static UUID decode(final byte[] bytes) { return decode(Unpooled.wrappedBuffer(bytes)); } @@ -54,12 +55,12 @@ public static UUID decode(byte[] bytes) { * @param in a {@link ByteBuf} containing the serialized {@link UUID} to be decoded * @return a new {@link UUID} */ - public static UUID decode(ByteBuf in) { + public static UUID decode(final ByteBuf in) { - Objects.requireNonNull(in); + checkNotNull(in, "in"); if (in.readableBytes() < 2 * Long.BYTES) { - String reason = String.format("invalid frame length: %d", in.readableBytes()); + final String reason = String.format("invalid frame length: %d", in.readableBytes()); throw new CorruptedFrameException(reason); } @@ -83,7 +84,7 @@ public static UUID decode(ByteBuf in) { * @param uuid a {@link UUID} to be encoded * @return a new byte array containing the encoded */ - public static byte[] encode(UUID uuid) { + public static byte[] encode(final UUID uuid) { final byte[] bytes = new byte[2 * Integer.BYTES]; encode(uuid, Unpooled.wrappedBuffer(bytes)); return bytes; @@ -95,7 +96,7 @@ public static byte[] encode(UUID uuid) { * @param uuid a {@link UUID} to be encoded * @param out an output {@link ByteBuf} */ - public static void encode(UUID uuid, ByteBuf out) { + public static void encode(final UUID uuid, final ByteBuf out) { final long mostSignificantBits = uuid.getMostSignificantBits(); diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java b/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java index dfdfdf0452803..bb40a6e61b63c 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java @@ -1,14 +1,13 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; +import com.fasterxml.jackson.databind.node.NullNode; +import org.testng.annotations.Test; + import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import org.testng.annotations.Test; - -import com.fasterxml.jackson.databind.node.NullNode; -import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; - import static org.assertj.core.api.AssertionsForClassTypes.assertThat; public class PartitionKeyHashingTests { @@ -76,7 +75,7 @@ public void effectivePartitionKeyHashV2() { @Test(groups = "unit") public void hashV2PartitionKeyDeserialization() { - String partitionKeyDefinitionStr = "{\"paths\":[\"/pk\"],\"kind\":\"HASH\",\"version\":2}"; + String partitionKeyDefinitionStr = "{\"paths\":[\"/pk\"],\"kind\":\"Hash\",\"version\":2}"; PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(partitionKeyDefinitionStr); assertThat(partitionKeyDef.version()).isEqualTo(PartitionKeyDefinitionVersion.V2); assertThat(partitionKeyDef.kind()).isEqualTo(PartitionKind.HASH); @@ -85,7 +84,7 @@ public void hashV2PartitionKeyDeserialization() { @Test(groups = "unit") public void hashV1PartitionKeyDeserialization() { - String partitionKeyDefinitionStr = "{\"paths\":[\"/pk\"],\"kind\":\"HASH\"}"; + String partitionKeyDefinitionStr = "{\"paths\":[\"/pk\"],\"kind\":\"Hash\"}"; PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(partitionKeyDefinitionStr); assertThat(partitionKeyDef.version()).isNull(); assertThat(partitionKeyDef.kind()).isEqualTo(PartitionKind.HASH); diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java index 3d5c815248ace..3146f28ef5078 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java @@ -24,25 +24,25 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.NotFoundException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import com.azure.data.cosmos.internal.routing.IServerIdentity; import com.azure.data.cosmos.internal.routing.InMemoryCollectionRoutingMap; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; -import com.azure.data.cosmos.internal.InvalidPartitionException; -import com.azure.data.cosmos.internal.NotFoundException; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.mutable.MutableObject; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java index da4b9cf72a555..2404ed08cf2e7 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java @@ -23,8 +23,8 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableList; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.google.common.collect.ImmutableList; import org.mockito.Matchers; import org.mockito.Mockito; import org.testng.annotations.Test; @@ -160,7 +160,7 @@ public void resolveAddressesAsync() { List res = selector.resolveAddressesAsync(request, false).toBlocking().value(); - assertThat(res).isEqualTo(replicaAddresses.stream().filter(a -> a.getProtocolName().equals(Protocol.HTTPS.name())).collect(Collectors.toList())); + assertThat(res).isEqualTo(replicaAddresses.stream().filter(a -> a.getProtocolName().equals(Protocol.HTTPS.toString())).collect(Collectors.toList())); } @Test(groups = "unit") diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java index b1f3b52d3a9f8..54061ed1b8561 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.google.common.base.Predicates; +import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.assertj.core.api.Condition; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java index a067058a7b2e4..89c104c10c6bf 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java @@ -23,24 +23,24 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableList; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.ISessionToken; +import com.azure.data.cosmos.internal.NotFoundException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.VectorSessionToken; -import com.azure.data.cosmos.rx.FailureValidator; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.DocumentServiceRequestContext; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.NotFoundException; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.VectorSessionToken; +import com.azure.data.cosmos.rx.FailureValidator; +import com.google.common.collect.ImmutableList; import org.mockito.Mockito; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -93,7 +93,7 @@ public void deduceReadMode(ConsistencyLevel accountConsistencyLevel, Consistency RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); if (requestConsistency != null) { - request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, requestConsistency.name()); + request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, requestConsistency.toString()); } ValueHolder consistencyLevel = ValueHolder.initialize(null); @@ -201,7 +201,7 @@ public void readAny() { RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.EVENTUAL.name()); + request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.EVENTUAL.toString()); TimeoutHelper timeout = Mockito.mock(TimeoutHelper.class); boolean forceRefresh = false; @@ -310,7 +310,7 @@ public void readSessionConsistency_SomeReplicasLagBehindAndReturningResponseWith RxDocumentServiceRequest request = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); + request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.toString()); request.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); assertThat(VectorSessionToken.tryCreate("-1#" + fasterReplicaLSN , sessionToken)).isTrue(); @@ -425,7 +425,7 @@ public void sessionNotAvailableFromSomeReplicasThrowingNotFound_FindReplicaSatis TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.toString()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); assertThat(VectorSessionToken.tryCreate("-1#" + fasterReplicaLSN , sessionToken)).isTrue(); @@ -477,7 +477,7 @@ public void sessionRead_LegitimateNotFound() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.toString()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); assertThat(VectorSessionToken.tryCreate("-1#" + lsn , sessionToken)).isTrue(); @@ -543,7 +543,7 @@ public void sessionRead_ReplicasDoNotHaveTheRequestedLSN() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.toString()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); assertThat(VectorSessionToken.tryCreate("-1#" + (lsn + 1) , sessionToken)).isTrue(); @@ -607,7 +607,7 @@ public void requestRateTooLarge_BubbleUp() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.toString()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); assertThat(VectorSessionToken.tryCreate("-1#" + lsn , sessionToken)).isTrue(); diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java index f5ca74e97b022..e1df184dc08a5 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java @@ -23,16 +23,16 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableList; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.PartitionIsMigratingException; import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.rx.FailureValidator; +import com.google.common.collect.ImmutableList; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/EndpointMock.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/EndpointMock.java index 3dc677c48daf3..1d67ee7c21c18 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/EndpointMock.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/EndpointMock.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableList; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.google.common.collect.ImmutableList; import org.apache.commons.collections.map.HashedMap; import java.net.URI; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java index d2a01a4a94ae9..8b8b8ae018032 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java @@ -25,14 +25,14 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IRetryPolicy; import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.PartitionIsMigratingException; import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.testng.annotations.Test; import rx.Single; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java index a8729e10cb6de..2883734c97097 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java @@ -23,19 +23,19 @@ package com.azure.data.cosmos.directconnectivity; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.InternalServerErrorException; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.UserAgentContainer; -import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.internal.BadRequestException; import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.InternalServerErrorException; import com.azure.data.cosmos.internal.InvalidPartitionException; import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.PartitionIsMigratingException; import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.rx.FailureValidator; import io.netty.buffer.ByteBuf; import io.netty.channel.ConnectTimeoutException; import io.netty.handler.codec.http.EmptyHttpHeaders; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MultiStoreResultValidator.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MultiStoreResultValidator.java index f6eabb6554778..918d28b89383d 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MultiStoreResultValidator.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MultiStoreResultValidator.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.base.Predicates; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.rx.FailureValidator; +import com.google.common.base.Predicates; import org.apache.commons.lang3.mutable.MutableObject; import org.assertj.core.description.Description; import org.assertj.core.description.TextDescription; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MurmurHash3_32Test.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MurmurHash3_32Test.java index bd6fb05c40584..d8099967a2ef9 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MurmurHash3_32Test.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MurmurHash3_32Test.java @@ -24,9 +24,9 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.internal.routing.MurmurHash3_32; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; -import com.azure.data.cosmos.internal.routing.MurmurHash3_32; import org.apache.commons.lang3.RandomUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java index 12f93f5600573..2663cda588fb4 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java @@ -24,16 +24,16 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; import com.azure.data.cosmos.CommonsBridgeInternal; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKind; import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalUtils; -import com.azure.data.cosmos.internal.RMResources; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import rx.functions.Func2; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java index 60bab86d51a5f..8c91719e9529b 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableList; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.Undefined; -import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; +import com.google.common.collect.ImmutableList; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java index 6fe2c07533bef..9069d3e81f3c9 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java @@ -23,19 +23,19 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.base.Stopwatch; -import com.google.common.collect.ImmutableList; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.DocumentServiceRequestContext; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.rx.DocumentServiceRequestContextValidator; import com.azure.data.cosmos.rx.DocumentServiceRequestValidator; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.DocumentServiceRequestContext; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.google.common.base.Stopwatch; +import com.google.common.collect.ImmutableList; import org.mockito.Mockito; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java index e5aff73af344e..10af24360da49 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java @@ -26,16 +26,16 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.SessionContainer; -import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.SessionContainer; +import com.azure.data.cosmos.rx.FailureValidator; import org.assertj.core.api.Assertions; import org.mockito.Mockito; import org.testng.annotations.DataProvider; @@ -143,7 +143,7 @@ public void partitionSplit_RefreshCache_Read(ConsistencyLevel consistencyLevel, OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); request.requestContext = new DocumentServiceRequestContext(); request.requestContext.resolvedPartitionKeyRange = partitionKeyRangeWithId(partitionKeyRangeIdBeforeSplit); - request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.name()); + request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); Func1> prepareRequestAsyncDelegate = null; Single storeResponseObs = resourceClient.invokeAsync(request, prepareRequestAsyncDelegate); diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java index 0328d3bd013aa..61da80e08983e 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java @@ -25,12 +25,12 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.rx.FailureValidator; import org.assertj.core.api.Assertions; import org.mockito.Matchers; import org.mockito.Mockito; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java index e39fc7894afe5..4ff28b3431c77 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java @@ -23,44 +23,46 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableMap; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.InternalServerErrorException; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.Paths; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.UserAgentContainer; -import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContext; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContextNegotiator; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContextRequest; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdEndpoint; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequest; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestArgs; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestEncoder; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestManager; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestRecord; +import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestTimer; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdResponse; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdResponseDecoder; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdUUID; -import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.InternalServerErrorException; import com.azure.data.cosmos.internal.InvalidPartitionException; import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.PartitionIsMigratingException; import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.rx.FailureValidator; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandler; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.logging.LogLevel; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; -import io.netty.util.concurrent.DefaultEventExecutor; -import io.netty.util.concurrent.Future; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Assertions; -import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.DataProvider; @@ -75,32 +77,29 @@ import java.util.Arrays; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; import static com.azure.data.cosmos.internal.HttpConstants.HttpMethods; import static com.azure.data.cosmos.internal.HttpConstants.SubStatusCodes; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.spy; +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; -public class RntbdTransportClientTest { +public final class RntbdTransportClientTest { - final private static Logger logger = LoggerFactory.getLogger(RntbdTransportClientTest.class); - final private static int lsn = 5; - final private static ByteBuf noContent = Unpooled.wrappedBuffer(new byte[0]); - final private static String partitionKeyRangeId = "3"; - final private static URI physicalAddress = URI.create("rntbd://host:10251/replica-path/"); - final private static Duration requestTimeout = Duration.ofSeconds(1000); + private static final Logger logger = LoggerFactory.getLogger(RntbdTransportClientTest.class); + private static final int lsn = 5; + private static final ByteBuf noContent = Unpooled.wrappedBuffer(new byte[0]); + private static final String partitionKeyRangeId = "3"; + private static final URI physicalAddress = URI.create("rntbd://host:10251/replica-path/"); + private static final Duration requestTimeout = Duration.ofSeconds(1000); @DataProvider(name = "fromMockedNetworkFailureToExpectedDocumentClientException") public Object[][] fromMockedNetworkFailureToExpectedDocumentClientException() { return new Object[][] { - // TODO: DANOBLE: add network failure exception test cases }; } @@ -129,7 +128,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 400, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(1L) ), noContent) }, @@ -154,7 +154,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 401, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(2L) ), noContent) }, @@ -179,7 +180,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 403, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(3L) ), noContent) }, @@ -204,7 +206,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 404, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(4L) ), noContent) }, @@ -229,7 +232,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 405, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(5L) ), noContent) }, @@ -254,7 +258,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 408, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(6L) ), noContent) }, @@ -279,7 +284,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 409, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(7L) ), noContent) }, @@ -305,7 +311,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, - HttpHeaders.SUB_STATUS, Integer.toString(SubStatusCodes.NAME_CACHE_IS_STALE) + HttpHeaders.SUB_STATUS, Integer.toString(SubStatusCodes.NAME_CACHE_IS_STALE), + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(8L) ), noContent) }, @@ -331,7 +338,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, - HttpHeaders.SUB_STATUS, Integer.toString(SubStatusCodes.PARTITION_KEY_RANGE_GONE) + HttpHeaders.SUB_STATUS, Integer.toString(SubStatusCodes.PARTITION_KEY_RANGE_GONE), + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(9L) ), noContent) }, @@ -357,7 +365,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, - HttpHeaders.SUB_STATUS, Integer.toString(SubStatusCodes.COMPLETING_SPLIT) + HttpHeaders.SUB_STATUS, Integer.toString(SubStatusCodes.COMPLETING_SPLIT), + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(10L) ), noContent) }, @@ -383,7 +392,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, - HttpHeaders.SUB_STATUS, Integer.toString(SubStatusCodes.COMPLETING_PARTITION_MIGRATION) + HttpHeaders.SUB_STATUS, Integer.toString(SubStatusCodes.COMPLETING_PARTITION_MIGRATION), + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(11L) ), noContent) }, @@ -409,7 +419,9 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, - HttpHeaders.SUB_STATUS, String.valueOf(SubStatusCodes.UNKNOWN)), + HttpHeaders.SUB_STATUS, String.valueOf(SubStatusCodes.UNKNOWN), + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(12L) + ), noContent) }, { @@ -433,7 +445,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 412, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(13L) ), noContent) }, @@ -458,7 +471,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 413, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(14L) ), noContent) }, @@ -483,7 +497,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 423, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(15L) ), noContent) }, @@ -508,7 +523,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 429, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(16L) ), noContent) }, @@ -533,7 +549,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 449, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(17L) ), noContent) }, @@ -558,7 +575,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 500, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(18L) ), noContent) }, @@ -583,7 +601,8 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { 503, ImmutableMap.of( HttpHeaders.LSN, Integer.toString(lsn), - HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId + HttpHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId, + HttpHeaders.TRANSPORT_REQUEST_ID, Long.toString(19L) ), noContent) }, @@ -593,14 +612,13 @@ public Object[][] fromMockedRntbdResponseToExpectedDocumentClientException() { /** * Verifies that a request for a non-existent resource produces a {@link }GoneException} */ - @Test(enabled = false, groups = "direct") + @Test(enabled = false, groups = { "direct" }) public void verifyGoneResponseMapsToGoneException() throws Exception { - final RntbdTransportClient.Options options = new RntbdTransportClient.Options(requestTimeout); + final RntbdTransportClient.Options options = new RntbdTransportClient.Options.Builder(requestTimeout).build(); final SslContext sslContext = SslContextBuilder.forClient().build(); - final UserAgentContainer userAgent = new UserAgentContainer(); - try (final RntbdTransportClient transportClient = new RntbdTransportClient(options, sslContext, userAgent)) { + try (final RntbdTransportClient transportClient = new RntbdTransportClient(options, sslContext)) { final BaseAuthorizationTokenProvider authorizationTokenProvider = new BaseAuthorizationTokenProvider( RntbdTestConfiguration.AccountKey @@ -623,13 +641,13 @@ public void verifyGoneResponseMapsToGoneException() throws Exception { builder.put(HttpHeaders.AUTHORIZATION, token); - RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, + final RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.DatabaseAccount, Paths.DATABASE_ACCOUNT_PATH_SEGMENT, builder.build() ); - Single responseSingle = transportClient.invokeStoreAsync(physicalAddress, null, request); + final Single responseSingle = transportClient.invokeStoreAsync(physicalAddress, null, request); responseSingle.toObservable().toBlocking().subscribe(new Subscriber() { @Override @@ -637,24 +655,24 @@ public void onCompleted() { } @Override - public void onError(Throwable error) { - String cs = "Expected %s, not %s"; - assertTrue(error instanceof GoneException, String.format(cs, GoneException.class, error.getClass())); - Throwable cause = error.getCause(); + public void onError(final Throwable error) { + final String format = "Expected %s, not %s"; + assertTrue(error instanceof GoneException, String.format(format, GoneException.class, error.getClass())); + final Throwable cause = error.getCause(); if (cause != null) { // assumption: cosmos isn't listening on 10251 - assertTrue(cause instanceof ConnectException, String.format(cs, ConnectException.class, error.getClass())); + assertTrue(cause instanceof ConnectException, String.format(format, ConnectException.class, error.getClass())); } } @Override - public void onNext(StoreResponse response) { + public void onNext(final StoreResponse response) { fail(String.format("Expected GoneException, not a StoreResponse: %s", response)); } }); - } catch (Exception error) { - String message = String.format("%s: %s", error.getClass(), error.getMessage()); + } catch (final Exception error) { + final String message = String.format("%s: %s", error.getClass(), error.getMessage()); fail(message, error); } } @@ -669,12 +687,15 @@ public void onNext(StoreResponse response) { * @param request An RNTBD request instance * @param exception An exception mapping */ - @Test(enabled = false, groups = "unit", dataProvider = "fromMockedNetworkFailureToExpectedDocumentClientException") + @Test(enabled = false, groups = { "unit" }, dataProvider = "fromMockedNetworkFailureToExpectedDocumentClientException") public void verifyNetworkFailure( - FailureValidator.Builder builder, - RxDocumentServiceRequest request, - CosmosClientException exception + final FailureValidator.Builder builder, + final RxDocumentServiceRequest request, + final CosmosClientException exception ) { + // TODO: DANOBLE: Implement RntbdTransportClientTest.verifyNetworkFailure + // Links: + // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/378750 throw new UnsupportedOperationException("TODO: DANOBLE: Implement this test"); } @@ -685,70 +706,59 @@ public void verifyNetworkFailure( * @param request An RNTBD request instance * @param response The RNTBD response instance to be returned as a result of the request */ - @Test(enabled = true, groups = "unit", dataProvider = "fromMockedRntbdResponseToExpectedDocumentClientException") + @Test(enabled = true, groups = { "unit" }, dataProvider = "fromMockedRntbdResponseToExpectedDocumentClientException") public void verifyRequestFailures( - FailureValidator.Builder builder, - RxDocumentServiceRequest request, - RntbdResponse response + final FailureValidator.Builder builder, + final RxDocumentServiceRequest request, + final RntbdResponse response ) { final UserAgentContainer userAgent = new UserAgentContainer(); final Duration timeout = Duration.ofMillis(1000); try (final RntbdTransportClient client = getRntbdTransportClientUnderTest(userAgent, timeout, response)) { - Single responseSingle; + final Single responseSingle; try { - responseSingle = client.invokeStoreAsync( - physicalAddress, new ResourceOperation(request.getOperationType(), request.getResourceType()), request - ); - } catch (Exception error) { - throw new AssertionError(String.format("%s: %s", error.getClass(), error.getMessage())); + responseSingle = client.invokeStoreAsync(physicalAddress, null, request); + } catch (final Exception error) { + throw new AssertionError(String.format("%s: %s", error.getClass(), error)); } - validateFailure(responseSingle, builder.build()); + this.validateFailure(responseSingle, builder.build()); } } private static RntbdTransportClient getRntbdTransportClientUnderTest( - UserAgentContainer userAgent, - Duration requestTimeout, - RntbdResponse expected + final UserAgentContainer userAgent, + final Duration requestTimeout, + final RntbdResponse expected ) { - final RntbdTransportClient.Options options = new RntbdTransportClient.Options(requestTimeout); + final RntbdTransportClient.Options options = new RntbdTransportClient.Options.Builder(requestTimeout) + .userAgent(userAgent) + .build(); + final SslContext sslContext; try { sslContext = SslContextBuilder.forClient().build(); - } catch (Exception error) { + } catch (final Exception error) { throw new AssertionError(String.format("%s: %s", error.getClass(), error.getMessage())); } - final RntbdTransportClient.EndpointFactory endpointFactory = spy(new RntbdTransportClient.EndpointFactory( - options, sslContext, userAgent - )); - - final RntbdTransportClient client = new RntbdTransportClient(endpointFactory); - - doAnswer((Answer) invocation -> { - - RntbdTransportClient.EndpointFactory factory = (RntbdTransportClient.EndpointFactory) invocation.getMock(); - URI physicalAddress = invocation.getArgumentAt(0, URI.class); - return new FakeEndpoint(factory, physicalAddress, expected); - - }).when(endpointFactory).createEndpoint(any()); - - return client; + return new RntbdTransportClient(new FakeEndpoint.Provider(options, sslContext, expected)); } - private void validateFailure(Single single, FailureValidator validator) { + private void validateFailure(final Single single, final FailureValidator validator) { validateFailure(single, validator, requestTimeout.toMillis()); } - private static void validateFailure(Single single, FailureValidator validator, long timeout) { + private static void validateFailure( + final Single single, final FailureValidator validator, final long timeout + ) { - TestSubscriber testSubscriber = new TestSubscriber<>(); + final TestSubscriber testSubscriber = new TestSubscriber<>(); single.toObservable().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNotCompleted(); @@ -759,24 +769,24 @@ private static void validateFailure(Single single, FailureValidat // region Types - final private static class FakeChannel extends EmbeddedChannel { + private static final class FakeChannel extends EmbeddedChannel { - final private static ServerProperties serverProperties = new ServerProperties("agent", "3.0.0"); - final private BlockingQueue responses; + private static final ServerProperties serverProperties = new ServerProperties("agent", "3.0.0"); + private final BlockingQueue responses; - FakeChannel(BlockingQueue responses, ChannelHandler... handlers) { + FakeChannel(final BlockingQueue responses, final ChannelHandler... handlers) { super(handlers); this.responses = responses; } @Override - protected void handleInboundMessage(Object message) { + protected void handleInboundMessage(final Object message) { super.handleInboundMessage(message); assertTrue(message instanceof ByteBuf); } @Override - protected void handleOutboundMessage(Object message) { + protected void handleOutboundMessage(final Object message) { assertTrue(message instanceof ByteBuf); @@ -787,21 +797,23 @@ protected void handleOutboundMessage(Object message) { if (in.getUnsignedIntLE(4) == 0) { - RntbdContextRequest request = RntbdContextRequest.decode(in.copy()); - RntbdContext rntbdContext = RntbdContext.from(request, serverProperties, HttpResponseStatus.OK); + final RntbdContextRequest request = RntbdContextRequest.decode(in.copy()); + final RntbdContext rntbdContext = RntbdContext.from(request, serverProperties, HttpResponseStatus.OK); rntbdContext.encode(out); } else { - RntbdResponse rntbdResponse; + final RntbdRequest rntbdRequest = RntbdRequest.decode(in.copy()); + final RntbdResponse rntbdResponse; try { rntbdResponse = this.responses.take(); - } catch (Exception error) { + } catch (final Exception error) { throw new AssertionError(String.format("%s: %s", error.getClass(), error.getMessage())); } + assertEquals(rntbdRequest.getTransportRequestId(), rntbdResponse.getTransportRequestId()); rntbdResponse.encode(out); out.setBytes(8, in.slice(8, 16)); // Overwrite activityId } @@ -810,50 +822,90 @@ protected void handleOutboundMessage(Object message) { } } - final private static class FakeEndpoint implements RntbdTransportClient.Endpoint { + private static final class FakeEndpoint implements RntbdEndpoint { + final RntbdRequestTimer requestTimer; final FakeChannel fakeChannel; final URI physicalAddress; - final RntbdRequestManager requestManager; - FakeEndpoint( - RntbdTransportClient.EndpointFactory factory, - URI physicalAddress, - RntbdResponse... expected + private FakeEndpoint( + final Config config, final RntbdRequestTimer timer, final URI physicalAddress, + final RntbdResponse... expected ) { - ArrayBlockingQueue responses = new ArrayBlockingQueue( + final ArrayBlockingQueue responses = new ArrayBlockingQueue<>( expected.length, true, Arrays.asList(expected) ); - this.requestManager = new RntbdRequestManager(); + RntbdRequestManager requestManager = new RntbdRequestManager(30); this.physicalAddress = physicalAddress; + this.requestTimer = timer; this.fakeChannel = new FakeChannel(responses, - new RntbdContextNegotiator(this.requestManager, factory.getUserAgent()), + new RntbdContextNegotiator(requestManager, config.getUserAgent()), new RntbdRequestEncoder(), new RntbdResponseDecoder(), - this.requestManager + requestManager ); } @Override - public Future close() { - DefaultEventExecutor executor = new DefaultEventExecutor(); - Future future = executor.newSucceededFuture(true); + public String getName() { + return "FakeEndpoint"; + } + + @Override + public void close() { this.fakeChannel.close().syncUninterruptibly(); - return future; } @Override - public CompletableFuture write(RntbdRequestArgs requestArgs) { - final CompletableFuture responseFuture = this.requestManager.createStoreResponseFuture(requestArgs); - this.fakeChannel.writeOutbound(requestArgs); - return responseFuture; + public RntbdRequestRecord request(final RntbdRequestArgs requestArgs) { + final RntbdRequestRecord requestRecord = new RntbdRequestRecord(requestArgs, this.requestTimer); + this.fakeChannel.writeOutbound(requestRecord); + return requestRecord; + } + + static class Provider implements RntbdEndpoint.Provider { + + final Config config; + final RntbdResponse expected; + final RntbdRequestTimer timer; + + Provider(RntbdTransportClient.Options options, SslContext sslContext, RntbdResponse expected) { + this.config = new Config(options, sslContext, LogLevel.WARN); + this.timer = new RntbdRequestTimer(config.getRequestTimeout()); + this.expected = expected; + } + + @Override + public void close() throws RuntimeException { + this.timer.close(); + } + + @Override + public Config config() { + return this.config; + } + + @Override + public int count() { + return 1; + } + + @Override + public RntbdEndpoint get(URI physicalAddress) { + return new FakeEndpoint(config, timer, physicalAddress, expected); + } + + @Override + public Stream list() { + return Stream.empty(); + } } } - final private static class RntbdTestConfiguration { + private static final class RntbdTestConfiguration { static String AccountHost = System.getProperty("ACCOUNT_HOST", StringUtils.defaultString( diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java index b8d6733b10744..5bd7a1fac7838 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java @@ -28,20 +28,20 @@ import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.ReplicationPolicy; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.RequestChargeTracker; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.SessionContainer; -import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.SessionContainer; import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.rx.FailureValidator; import org.apache.commons.lang3.StringUtils; import org.mockito.Matchers; import org.mockito.Mockito; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java index 9010e80abde8b..9b9da76166cd7 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java @@ -23,24 +23,24 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableList; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.RequestChargeTracker; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.VectorSessionToken; -import com.azure.data.cosmos.rx.FailureValidator; -import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.PartitionIsMigratingException; import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.VectorSessionToken; +import com.azure.data.cosmos.rx.FailureValidator; +import com.google.common.collect.ImmutableList; import org.assertj.core.api.AssertionsForClassTypes; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; @@ -247,7 +247,7 @@ public void sessionNotAvailableFromSomeReplicas_FindReplicaSatisfyingRequestedSe TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.toString()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); dsr.requestContext.sessionToken = sessionToken.v; @@ -324,7 +324,7 @@ public void sessionRead_LegitimateNotFound() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.toString()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); dsr.requestContext.sessionToken = sessionToken.v; @@ -393,7 +393,7 @@ public void sessionRead_ReplicasDoNotHaveTheRequestedLSN_NoResult() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.toString()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); dsr.requestContext.sessionToken = sessionToken.v; @@ -455,7 +455,7 @@ public void requestRateTooLarge_BubbleUp() { TimeoutHelper timeoutHelper = Mockito.mock(TimeoutHelper.class); RxDocumentServiceRequest dsr = RxDocumentServiceRequest.createFromName( OperationType.Read, "/dbs/db/colls/col/docs/docId", ResourceType.Document); - dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.name()); + dsr.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.SESSION.toString()); dsr.requestContext = new DocumentServiceRequestContext(); Utils.ValueHolder sessionToken = Utils.ValueHolder.initialize(null); dsr.requestContext.sessionToken = sessionToken.v; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java index aeeef1bf3478e..f5ca74b627471 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableList; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.tuple.Pair; import rx.Single; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java index 20a67b7123e0c..c651ed6584047 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java @@ -22,28 +22,27 @@ */ package com.azure.data.cosmos.internal; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import com.azure.data.cosmos.directconnectivity.GoneException; +import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.azure.data.cosmos.directconnectivity.StoreResponseBuilder; +import com.azure.data.cosmos.directconnectivity.StoreResponseValidator; +import com.azure.data.cosmos.internal.IRetryPolicy.ShouldRetryResult; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; - -import com.azure.data.cosmos.directconnectivity.GoneException; -import com.azure.data.cosmos.directconnectivity.StoreResponse; -import com.azure.data.cosmos.directconnectivity.StoreResponseBuilder; -import com.azure.data.cosmos.directconnectivity.StoreResponseValidator; -import com.azure.data.cosmos.internal.IRetryPolicy.ShouldRetryResult; - import rx.Single; import rx.functions.Func1; import rx.observers.TestSubscriber; +import java.time.Duration; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + public class RetryUtilsTest { IRetryPolicy retryPolicy; Func1, Single> callbackMethod; diff --git a/examples/pom.xml b/examples/pom.xml index e37d8f347da83..299b1f815143c 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -126,16 +126,32 @@ guava ${guava.version} + + log4j + log4j + ${log4j.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-log4j12 + ${slf4j.version} + + io.reactivex rxjava-guava - 1.0.3 + ${rxjava-guava.version} test - org.testng - testng - ${testng.version} + org.hamcrest + hamcrest-all + ${hamcrest.version} test @@ -145,25 +161,10 @@ test - org.hamcrest - hamcrest-all - 1.3 + org.testng + testng + ${testng.version} test - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - slf4j-log4j12 - ${slf4j.version} - - - log4j - log4j - ${log4j.version} - diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java b/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java index 00fd6d45a78ba..d82a72e6dcaa2 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java @@ -22,9 +22,14 @@ */ package com.azure.data.cosmos.examples; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Flux; diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java index d483bad06208f..5f15e70098fc4 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java @@ -22,11 +22,17 @@ */ package com.azure.data.cosmos.examples.ChangeFeed; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.ChangeFeedProcessor; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosContainerResponse; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.SerializationFormattingPolicy; import org.apache.commons.lang3.RandomStringUtils; import reactor.core.publisher.Mono; diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java index 269d75153181d..0f12dd70894b1 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java @@ -25,7 +25,6 @@ import com.azure.data.cosmos.ChangeFeedObserver; import com.azure.data.cosmos.ChangeFeedObserverCloseReason; import com.azure.data.cosmos.ChangeFeedObserverContext; -import com.azure.data.cosmos.*; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.SerializationFormattingPolicy; diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java index 27d275f03ba29..4e602cf378a85 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos.rx.examples.multimaster; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.AsyncDocumentClient; import rx.Observable; import rx.Single; diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java index 9af8773ae8381..3a77790ce968e 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java @@ -23,7 +23,19 @@ package com.azure.data.cosmos.rx.examples.multimaster.samples; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.AccessCondition; +import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.Conflict; +import com.azure.data.cosmos.ConflictResolutionPolicy; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.StoredProcedure; import com.azure.data.cosmos.rx.examples.multimaster.Helpers; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java index bb3cdbb1ff70f..c41aa76c8dbe0 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos.rx.examples.multimaster.samples; -import com.google.common.base.Preconditions; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.rx.examples.multimaster.ConfigurationManager; +import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; diff --git a/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java b/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java new file mode 100644 index 0000000000000..2cf4d67cd8d37 --- /dev/null +++ b/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java @@ -0,0 +1,73 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.azure.data.cosmos; + +import com.google.common.base.Strings; +import org.testng.ITest; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; + +import java.lang.reflect.Method; + +public abstract class DocumentClientTest implements ITest { + + private final AsyncDocumentClient.Builder clientBuilder;; + private String testName; + + public DocumentClientTest() { + this(new AsyncDocumentClient.Builder()); + } + + public DocumentClientTest(AsyncDocumentClient.Builder clientBuilder) { + this.clientBuilder = clientBuilder; + } + + public final AsyncDocumentClient.Builder clientBuilder() { + return this.clientBuilder; + } + + @Override + public final String getTestName() { + return this.testName; + } + + @BeforeMethod(alwaysRun = true) + public final void setTestName(Method method) { + + String connectionMode = this.clientBuilder.getConnectionPolicy().connectionMode() == ConnectionMode.DIRECT + ? "Direct " + this.clientBuilder.getConfigs().getProtocol() + : "Gateway"; + + this.testName = Strings.lenientFormat("%s::%s[%s with %s consistency]", + method.getDeclaringClass().getSimpleName(), + method.getName(), + connectionMode, + clientBuilder.getDesiredConsistencyLevel()); + } + + @AfterMethod(alwaysRun = true) + public final void unsetTestName() { + this.testName = null; + } +} diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java index 7e9d50bacf271..800582be895d5 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java @@ -22,7 +22,22 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.DataType; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DocumentClientTest; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.IncludedPath; +import com.azure.data.cosmos.Index; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.ResourceResponse; import com.google.common.util.concurrent.ListenableFuture; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -68,24 +83,27 @@ * update the corresponding Offer. Please see * {@see com.azure.data.cosmos.rx.examples.OfferCRUDAsyncAPITest#testUpdateOffer()} */ -public class CollectionCRUDAsyncAPITest { +public class CollectionCRUDAsyncAPITest extends DocumentClientTest { + private final static int TIMEOUT = 120000; - private static Database createdDatabase; - private static AsyncDocumentClient asyncClient; + private Database createdDatabase; + private AsyncDocumentClient client; private DocumentCollection collectionDefinition; @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.DIRECT); - asyncClient = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.SESSION) - .build(); - - createdDatabase = Utils.createDatabaseForTest(asyncClient); + + ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + + this.clientBuilder() + .withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.SESSION); + + this.client = this.clientBuilder().build(); + + createdDatabase = Utils.createDatabaseForTest(client); } @BeforeMethod(groups = "samples", timeOut = TIMEOUT) @@ -101,8 +119,8 @@ public void before() { @AfterClass(groups = "samples", timeOut = TIMEOUT) public void shutdown() { - Utils.safeClean(asyncClient, createdDatabase); - Utils.safeClose(asyncClient); + Utils.safeClean(client, createdDatabase); + Utils.safeClose(client); } /** @@ -115,7 +133,7 @@ public void shutdown() { public void createCollection_SinglePartition_Async() throws Exception { RequestOptions singlePartitionRequestOptions = new RequestOptions(); singlePartitionRequestOptions.setOfferThroughput(400); - Observable> createCollectionObservable = asyncClient + Observable> createCollectionObservable = client .createCollection(getDatabaseLink(), collectionDefinition, singlePartitionRequestOptions); final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -147,7 +165,7 @@ public void createCollection_MultiPartition_Async() throws Exception { RequestOptions multiPartitionRequestOptions = new RequestOptions(); multiPartitionRequestOptions.setOfferThroughput(20000); - Observable> createCollectionObservable = asyncClient.createCollection( + Observable> createCollectionObservable = client.createCollection( getDatabaseLink(), getMultiPartitionCollectionDefinition(), multiPartitionRequestOptions); final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -171,7 +189,7 @@ public void createCollection_MultiPartition_Async() throws Exception { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createCollection_Async_withoutLambda() throws Exception { - Observable> createCollectionObservable = asyncClient + Observable> createCollectionObservable = client .createCollection(getDatabaseLink(), collectionDefinition, null); final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -206,7 +224,7 @@ public void call(Throwable error) { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createCollection_toBlocking() { - Observable> createCollectionObservable = asyncClient + Observable> createCollectionObservable = client .createCollection(getDatabaseLink(), collectionDefinition, null); // toBlocking() converts the observable to a blocking observable. @@ -223,10 +241,10 @@ public void createCollection_toBlocking() { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createCollection_toBlocking_CollectionAlreadyExists_Fails() { - asyncClient.createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single(); + client.createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single(); // CREATE the collection for test. - Observable> collectionForTestObservable = asyncClient + Observable> collectionForTestObservable = client .createCollection(getDatabaseLink(), collectionDefinition, null); try { @@ -247,7 +265,7 @@ public void createCollection_toBlocking_CollectionAlreadyExists_Fails() { */ @Test(groups = "samples", timeOut = TIMEOUT) public void transformObservableToGoogleGuavaListenableFuture() throws Exception { - Observable> createCollectionObservable = asyncClient + Observable> createCollectionObservable = client .createCollection(getDatabaseLink(), collectionDefinition, null); ListenableFuture> future = ListenableFutureObservable .to(createCollectionObservable); @@ -264,12 +282,12 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception @Test(groups = "samples", timeOut = TIMEOUT) public void createAndReadCollection() throws Exception { // CREATE a Collection - DocumentCollection documentCollection = asyncClient + DocumentCollection documentCollection = client .createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single() .getResource(); // READ the created collection using async api - Observable> readCollectionObservable = asyncClient + Observable> readCollectionObservable = client .readCollection(getCollectionLink(documentCollection), null); final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -294,12 +312,12 @@ public void createAndReadCollection() throws Exception { @Test(groups = "samples", timeOut = TIMEOUT) public void createAndDeleteCollection() throws Exception { // CREATE a Collection - DocumentCollection documentCollection = asyncClient + DocumentCollection documentCollection = client .createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single() .getResource(); // DELETE the created collection using async api - Observable> deleteCollectionObservable = asyncClient + Observable> deleteCollectionObservable = client .deleteCollection(getCollectionLink(documentCollection), null); final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -324,12 +342,12 @@ public void createAndDeleteCollection() throws Exception { @Test(groups = "samples", timeOut = TIMEOUT) public void collectionCreateAndQuery() throws Exception { // CREATE a Collection - DocumentCollection collection = asyncClient + DocumentCollection collection = client .createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single() .getResource(); // Query the created collection using async api - Observable> queryCollectionObservable = asyncClient.queryCollections( + Observable> queryCollectionObservable = client.queryCollections( getDatabaseLink(), String.format("SELECT * FROM r where r.id = '%s'", collection.id()), null); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java index 212a8d2852750..ee9baa5ce48a2 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java @@ -22,19 +22,20 @@ */ package com.azure.data.cosmos.rx.examples; -import com.google.common.util.concurrent.ListenableFuture; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Conflict; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.google.common.util.concurrent.ListenableFuture; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -59,7 +60,7 @@ * transform an observable to ListenableFuture. Please see * {@link #transformObservableToGoogleGuavaListenableFuture()} */ -public class ConflictAPITest { +public class ConflictAPITest extends DocumentClientTest { private final static int TIMEOUT = 60000; private AsyncDocumentClient client; @@ -68,14 +69,16 @@ public class ConflictAPITest { @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.DIRECT); - client = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.SESSION) - .build(); + + ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + + this.clientBuilder() + .withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.SESSION); + + this.client = this.clientBuilder().build(); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.id(UUID.randomUUID().toString()); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java index 826f119ed278e..15407866d34fa 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java @@ -22,7 +22,15 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DocumentClientTest; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.ResourceResponse; import com.google.common.util.concurrent.ListenableFuture; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -61,22 +69,24 @@ * transform an observable to ListenableFuture. Please see * {@link #transformObservableToGoogleGuavaListenableFuture()} */ -public class DatabaseCRUDAsyncAPITest { +public class DatabaseCRUDAsyncAPITest extends DocumentClientTest { private final static int TIMEOUT = 60000; private final List databaseIds = new ArrayList<>(); - private AsyncDocumentClient asyncClient; + private AsyncDocumentClient client; @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.DIRECT); - asyncClient = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.SESSION) - .build(); + + ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + + this.clientBuilder() + .withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.SESSION); + + this.client = this.clientBuilder().build(); } private Database getDatabaseDefinition() { @@ -91,9 +101,9 @@ private Database getDatabaseDefinition() { @AfterClass(groups = "samples", timeOut = TIMEOUT) public void shutdown() { for (String id : databaseIds) { - Utils.safeClean(asyncClient, id); + Utils.safeClean(client, id); } - Utils.safeClose(asyncClient); + Utils.safeClose(client); } /** @@ -103,7 +113,7 @@ public void shutdown() { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDatabase_Async() throws Exception { - Observable> createDatabaseObservable = asyncClient.createDatabase(getDatabaseDefinition(), + Observable> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -127,7 +137,7 @@ public void createDatabase_Async() throws Exception { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDatabase_Async_withoutLambda() throws Exception { - Observable> createDatabaseObservable = asyncClient.createDatabase(getDatabaseDefinition(), + Observable> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -162,7 +172,7 @@ public void call(Throwable error) { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDatabase_toBlocking() { - Observable> createDatabaseObservable = asyncClient.createDatabase(getDatabaseDefinition(), + Observable> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), null); // toBlocking() converts to a blocking observable. @@ -180,10 +190,10 @@ public void createDatabase_toBlocking() { @Test(groups = "samples", timeOut = TIMEOUT) public void createDatabase_toBlocking_DatabaseAlreadyExists_Fails() { Database databaseDefinition = getDatabaseDefinition(); - asyncClient.createDatabase(databaseDefinition, null).toBlocking().single(); + client.createDatabase(databaseDefinition, null).toBlocking().single(); // CREATE the database for test. - Observable> databaseForTestObservable = asyncClient + Observable> databaseForTestObservable = client .createDatabase(databaseDefinition, null); try { @@ -204,7 +214,7 @@ public void createDatabase_toBlocking_DatabaseAlreadyExists_Fails() { */ @Test(groups = "samples", timeOut = TIMEOUT) public void transformObservableToGoogleGuavaListenableFuture() throws Exception { - Observable> createDatabaseObservable = asyncClient.createDatabase(getDatabaseDefinition(), + Observable> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), null); ListenableFuture> future = ListenableFutureObservable.to(createDatabaseObservable); @@ -220,10 +230,10 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception @Test(groups = "samples", timeOut = TIMEOUT) public void createAndReadDatabase() throws Exception { // CREATE a database - Database database = asyncClient.createDatabase(getDatabaseDefinition(), null).toBlocking().single().getResource(); + Database database = client.createDatabase(getDatabaseDefinition(), null).toBlocking().single().getResource(); // READ the created database using async api - Observable> readDatabaseObservable = asyncClient.readDatabase("dbs/" + database.id(), + Observable> readDatabaseObservable = client.readDatabase("dbs/" + database.id(), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -248,10 +258,10 @@ public void createAndReadDatabase() throws Exception { @Test(groups = "samples", timeOut = TIMEOUT) public void createAndDeleteDatabase() throws Exception { // CREATE a database - Database database = asyncClient.createDatabase(getDatabaseDefinition(), null).toBlocking().single().getResource(); + Database database = client.createDatabase(getDatabaseDefinition(), null).toBlocking().single().getResource(); // DELETE the created database using async api - Observable> deleteDatabaseObservable = asyncClient + Observable> deleteDatabaseObservable = client .deleteDatabase("dbs/" + database.id(), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -277,10 +287,10 @@ public void createAndDeleteDatabase() throws Exception { public void databaseCreateAndQuery() throws Exception { // CREATE a database Database databaseDefinition = getDatabaseDefinition(); - asyncClient.createDatabase(databaseDefinition, null).toBlocking().single().getResource(); + client.createDatabase(databaseDefinition, null).toBlocking().single().getResource(); // Query the created database using async api - Observable> queryDatabaseObservable = asyncClient + Observable> queryDatabaseObservable = client .queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseDefinition.id()), null); final CountDownLatch completionLatch = new CountDownLatch(1); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java index 0c7ba9fbb8349..9ed6519cdb42f 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java @@ -22,7 +22,21 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentClientTest; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.ResourceResponse; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -73,24 +87,26 @@ * transform an observable to ListenableFuture. Please see * {@link #transformObservableToGoogleGuavaListenableFuture()} */ -public class DocumentCRUDAsyncAPITest { +public class DocumentCRUDAsyncAPITest extends DocumentClientTest { + private final static String PARTITION_KEY_PATH = "/mypk"; private final static int TIMEOUT = 60000; - private AsyncDocumentClient asyncClient; + + private AsyncDocumentClient client; private Database createdDatabase; private DocumentCollection createdCollection; @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { - // Sets up the requirements for each test - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.DIRECT); - asyncClient = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.SESSION) - .build(); + + ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + + this.clientBuilder() + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.SESSION); + + this.client = this.clientBuilder().build(); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.id(UUID.randomUUID().toString()); @@ -102,18 +118,18 @@ public void setUp() { collectionDefinition.setPartitionKey(partitionKeyDefinition); // CREATE database - createdDatabase = Utils.createDatabaseForTest(asyncClient); + createdDatabase = Utils.createDatabaseForTest(client); // CREATE collection - createdCollection = asyncClient - .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) - .toBlocking().single().getResource(); + createdCollection = client + .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) + .toBlocking().single().getResource(); } @AfterClass(groups = "samples", timeOut = TIMEOUT) public void shutdown() { - Utils.safeClean(asyncClient, createdDatabase); - Utils.safeClose(asyncClient); + Utils.safeClean(client, createdDatabase); + Utils.safeClose(client); } /** @@ -122,7 +138,7 @@ public void shutdown() { @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_Async() throws Exception { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - Observable> createDocumentObservable = asyncClient + Observable> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, true); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -148,7 +164,7 @@ public void createDocument_Async() throws Exception { @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_Async_withoutLambda() throws Exception { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - Observable> createDocumentObservable = asyncClient + Observable> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, true); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -185,7 +201,7 @@ public void call(Throwable error) { @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_toBlocking() { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - Observable> createDocumentObservable = asyncClient + Observable> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, true); // toBlocking() converts to a blocking observable. @@ -203,14 +219,14 @@ public void createDocumentWithProgrammableDocumentDefinition() throws Exception documentDefinition.set("counter", 1); // CREATE a document - Document createdDocument = asyncClient + Document createdDocument = client .createDocument(getCollectionLink(), documentDefinition, null, false).toBlocking().single() .getResource(); RequestOptions options = new RequestOptions(); options.setPartitionKey(PartitionKey.None); // READ the created document - Observable> readDocumentObservable = asyncClient + Observable> readDocumentObservable = client .readDocument(getDocumentLink(createdDocument), options); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -241,7 +257,7 @@ public void documentCreation_SumUpRequestCharge() throws Exception { for (int i = 0; i < 10; i++) { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), i)); - Observable> createDocumentObservable = asyncClient + Observable> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, false); listOfCreateDocumentObservables.add(createDocumentObservable); } @@ -280,10 +296,10 @@ public void documentCreation_SumUpRequestCharge() throws Exception { @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_toBlocking_DocumentAlreadyExists_Fails() { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - asyncClient.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); // CREATE the document - Observable> createDocumentObservable = asyncClient + Observable> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, false); try { @@ -306,10 +322,10 @@ public void createDocument_toBlocking_DocumentAlreadyExists_Fails() { @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_Async_DocumentAlreadyExists_Fails() throws Exception { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - asyncClient.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); // CREATE the document - Observable> createDocumentObservable = asyncClient + Observable> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, false); List errorList = Collections.synchronizedList(new ArrayList<>()); @@ -333,13 +349,13 @@ public void createDocument_Async_DocumentAlreadyExists_Fails() throws Exception public void documentReplace_Async() throws Exception { // CREATE a document Document createdDocument = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - createdDocument = asyncClient.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() - .single().getResource(); + createdDocument = client.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() + .single().getResource(); // Try to replace the existing document Document replacingDocument = new Document( String.format("{ 'id': 'doc%s', 'counter': '%d', 'new-prop' : '2'}", createdDocument.id(), 1)); - Observable> replaceDocumentObservable = asyncClient + Observable> replaceDocumentObservable = client .replaceDocument(getDocumentLink(createdDocument), replacingDocument, null); List> capturedResponse = Collections @@ -362,12 +378,12 @@ public void documentReplace_Async() throws Exception { public void documentUpsert_Async() throws Exception { // CREATE a document Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - asyncClient.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); // Upsert the existing document Document upsertingDocument = new Document( String.format("{ 'id': 'doc%s', 'counter': '%d', 'new-prop' : '2'}", doc.id(), 1)); - Observable> upsertDocumentObservable = asyncClient + Observable> upsertDocumentObservable = client .upsertDocument(getCollectionLink(), upsertingDocument, null, false); List> capturedResponse = Collections @@ -390,14 +406,14 @@ public void documentUpsert_Async() throws Exception { public void documentDelete_Async() throws Exception { // CREATE a document Document createdDocument = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d', 'mypk' : '%s'}", UUID.randomUUID().toString(), 1, UUID.randomUUID().toString())); - createdDocument = asyncClient.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() - .single().getResource(); + createdDocument = client.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() + .single().getResource(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(createdDocument.getString("mypk"))); // DELETE the existing document - Observable> deleteDocumentObservable = asyncClient + Observable> deleteDocumentObservable = client .deleteDocument(getDocumentLink(createdDocument), options); List> capturedResponse = Collections @@ -414,7 +430,7 @@ public void documentDelete_Async() throws Exception { // Assert document is deleted FeedOptions queryOptions = new FeedOptions(); queryOptions.enableCrossPartitionQuery(true); - List listOfDocuments = asyncClient + List listOfDocuments = client .queryDocuments(getCollectionLink(), String.format("SELECT * FROM r where r.id = '%s'", createdDocument.id()), queryOptions) .map(FeedResponse::results) // Map page to its list of documents .concatMap(Observable::from) // Flatten the observable @@ -433,13 +449,13 @@ public void documentDelete_Async() throws Exception { public void documentRead_Async() throws Exception { // CREATE a document Document createdDocument = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d', 'mypk' : '%s'}", UUID.randomUUID().toString(), 1, UUID.randomUUID().toString())); - createdDocument = asyncClient.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() - .single().getResource(); + createdDocument = client.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() + .single().getResource(); // READ the document RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(createdDocument.getString("mypk"))); - Observable> readDocumentObservable = asyncClient + Observable> readDocumentObservable = client .readDocument(getDocumentLink(createdDocument), options); List> capturedResponse = Collections @@ -479,7 +495,7 @@ public void customSerialization() throws Exception { String itemAsJsonString = mapper.writeValueAsString(testObject); Document doc = new Document(itemAsJsonString); - Document createdDocument = asyncClient + Document createdDocument = client .createDocument(getCollectionLink(), doc, null, false) .toBlocking() .single() @@ -488,7 +504,7 @@ public void customSerialization() throws Exception { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(testObject.mypk)); - Document readDocument = asyncClient + Document readDocument = client .readDocument(createdDocument.selfLink(), options) .toBlocking() .single() @@ -507,7 +523,7 @@ public void customSerialization() throws Exception { @Test(groups = "samples", timeOut = TIMEOUT) public void transformObservableToGoogleGuavaListenableFuture() throws Exception { Document doc = new Document(String.format("{ 'id': 'doc%d', 'counter': '%d'}", RandomUtils.nextInt(), 1)); - Observable> createDocumentObservable = asyncClient + Observable> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, false); ListenableFuture> listenableFuture = ListenableFutureObservable .to(createDocumentObservable); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java index dd5c7ecb504b0..3a4052103b95f 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java @@ -22,12 +22,13 @@ */ package com.azure.data.cosmos.rx.examples; -import com.google.common.util.concurrent.ListenableFuture; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; @@ -36,7 +37,7 @@ import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.google.common.util.concurrent.ListenableFuture; import org.apache.commons.lang3.RandomStringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -82,23 +83,27 @@ * transform an observable to ListenableFuture. Please see * {@link #transformObservableToGoogleGuavaListenableFuture()} */ -public class DocumentQueryAsyncAPITest { +public class DocumentQueryAsyncAPITest extends DocumentClientTest { + private final static int TIMEOUT = 3 * 60000; - private AsyncDocumentClient asyncClient; + + private AsyncDocumentClient client; private DocumentCollection createdCollection; private Database createdDatabase; private int numberOfDocuments; @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.DIRECT); - asyncClient = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.SESSION) - .build(); + + ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + + this.clientBuilder() + .withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.SESSION); + + this.client = this.clientBuilder().build(); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.id(UUID.randomUUID().toString()); @@ -110,10 +115,10 @@ public void setUp() { // CREATE database - createdDatabase = Utils.createDatabaseForTest(asyncClient); + createdDatabase = Utils.createDatabaseForTest(client); // CREATE collection - createdCollection = asyncClient + createdCollection = client .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) .toBlocking().single().getResource(); @@ -121,14 +126,14 @@ public void setUp() { // Add documents for (int i = 0; i < numberOfDocuments; i++) { Document doc = new Document(String.format("{ 'id': 'loc%d', 'counter': %d}", i, i)); - asyncClient.createDocument(getCollectionLink(), doc, null, true).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, true).toBlocking().single(); } } @AfterClass(groups = "samples", timeOut = TIMEOUT) public void shutdown() { - Utils.safeClean(asyncClient, createdDatabase); - Utils.safeClose(asyncClient); + Utils.safeClean(client, createdDatabase); + Utils.safeClose(client); } /** @@ -143,7 +148,7 @@ public void queryDocuments_Async() throws Exception { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable> documentQueryObservable = asyncClient + Observable> documentQueryObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); final CountDownLatch mainThreadBarrier = new CountDownLatch(1); @@ -190,7 +195,7 @@ public void queryDocuments_Async_withoutLambda() throws Exception { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable> documentQueryObservable = asyncClient + Observable> documentQueryObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); final CountDownLatch mainThreadBarrier = new CountDownLatch(1); @@ -240,7 +245,7 @@ public void queryDocuments_findTotalRequestCharge() throws Exception { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable totalChargeObservable = asyncClient + Observable totalChargeObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options) .map(FeedResponse::requestCharge) // Map the page to its request charge .reduce((totalCharge, charge) -> totalCharge + charge); // Sum up all the request charges @@ -266,7 +271,7 @@ public void queryDocuments_unsubscribeAfterFirstPage() throws Exception { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable> requestChargeObservable = asyncClient + Observable> requestChargeObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); AtomicInteger onNextCounter = new AtomicInteger(); @@ -328,11 +333,11 @@ public Boolean call(Document doc) { List resultList = Collections.synchronizedList(new ArrayList()); - asyncClient.queryDocuments(getCollectionLink(), "SELECT * FROM root", options) - .map(FeedResponse::results) // Map the page to the list of documents - .concatMap(Observable::from) // Flatten the observable> to observable - .filter(isPrimeNumber) // Filter documents using isPrimeNumber predicate - .subscribe(doc -> resultList.add(doc)); // Collect the results + client.queryDocuments(getCollectionLink(), "SELECT * FROM root", options) + .map(FeedResponse::results) // Map the page to the list of documents + .concatMap(Observable::from) // Flatten the observable> to observable + .filter(isPrimeNumber) // Filter documents using isPrimeNumber predicate + .subscribe(doc -> resultList.add(doc)); // Collect the results Thread.sleep(4000); @@ -371,7 +376,7 @@ public void queryDocuments_toBlocking_toIterator() { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable> documentQueryObservable = asyncClient + Observable> documentQueryObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); // Covert the observable to a blocking observable, then convert the blocking @@ -411,7 +416,7 @@ public void qrderBy_Async() throws Exception { Document doc = new Document(String.format("{\"id\":\"documentId%d\",\"key\":\"%s\",\"prop\":%d}", i, RandomStringUtils.randomAlphabetic(2), i)); - asyncClient.createDocument("dbs/" + createdDatabase.id() + "/colls/" + multiPartitionCollection.id(), + client.createDocument("dbs/" + createdDatabase.id() + "/colls/" + multiPartitionCollection.id(), doc, null, true).toBlocking().single(); } @@ -426,7 +431,7 @@ public void qrderBy_Async() throws Exception { options.maxDegreeOfParallelism(2); // Get the observable order by query documents - Observable> documentQueryObservable = asyncClient.queryDocuments( + Observable> documentQueryObservable = client.queryDocuments( "dbs/" + createdDatabase.id() + "/colls/" + multiPartitionCollection.id(), query, options); List resultList = Collections.synchronizedList(new ArrayList<>()); @@ -461,7 +466,7 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable> documentQueryObservable = asyncClient + Observable> documentQueryObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); // Convert to observable of list of pages @@ -495,8 +500,8 @@ private DocumentCollection createMultiPartitionCollection(String databaseLink, S DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.id(collectionId); collectionDefinition.setPartitionKey(partitionKeyDef); - DocumentCollection createdCollection = asyncClient.createCollection(databaseLink, collectionDefinition, options) - .toBlocking().single().getResource(); + DocumentCollection createdCollection = client.createCollection(databaseLink, collectionDefinition, options) + .toBlocking().single().getResource(); return createdCollection; } diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java index 5e22f6cd16d5a..571f1cc78d6f2 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java @@ -22,18 +22,19 @@ */ package com.azure.data.cosmos.rx.examples; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.SqlParameter; import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -45,26 +46,29 @@ import java.util.List; import java.util.UUID; -public class InMemoryGroupbyTest { +public class InMemoryGroupbyTest extends DocumentClientTest { + private final static int TIMEOUT = 60000; - private static AsyncDocumentClient asyncClient; - private static Database createdDatabase; - private static DocumentCollection createdCollection; + private AsyncDocumentClient client; + private Database createdDatabase; + private DocumentCollection createdCollection; @BeforeClass(groups = "samples", timeOut = TIMEOUT) - public static void setUp() throws Exception { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.DIRECT); - asyncClient = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.SESSION) - .build(); + public void setUp() throws Exception { + + ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + + this.clientBuilder() + .withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.SESSION); + + this.client = this.clientBuilder().build(); // CREATE database - createdDatabase = Utils.createDatabaseForTest(asyncClient); + createdDatabase = Utils.createDatabaseForTest(client); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.id(UUID.randomUUID().toString()); @@ -75,7 +79,7 @@ public static void setUp() throws Exception { collectionDefinition.setPartitionKey(partitionKeyDef); // CREATE collection - createdCollection = asyncClient + createdCollection = client .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) .toBlocking().single().getResource(); @@ -94,7 +98,7 @@ public static void setUp() throws Exception { + "'payer_id': %d, " + " 'created_time' : %d " + "}", UUID.randomUUID().toString(), i, currentTime.getSecond())); - asyncClient.createDocument(getCollectionLink(), doc, null, true).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, true).toBlocking().single(); Thread.sleep(100); } @@ -103,9 +107,9 @@ public static void setUp() throws Exception { } @AfterClass(groups = "samples", timeOut = TIMEOUT) - public static void shutdown() { - Utils.safeClean(asyncClient, createdDatabase); - asyncClient.close(); + public void shutdown() { + Utils.safeClean(client, createdDatabase); + client.close(); } /** @@ -121,7 +125,7 @@ public void groupByInMemory() { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable documentsObservable = asyncClient + Observable documentsObservable = client .queryDocuments(getCollectionLink(), new SqlQuerySpec("SELECT * FROM root r WHERE r.site_id=@site_id", new SqlParameterCollection(new SqlParameter("@site_id", "ABC"))), @@ -154,7 +158,7 @@ public void groupByInMemory_MoreDetail() { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable documentsObservable = asyncClient + Observable documentsObservable = client .queryDocuments(getCollectionLink(), new SqlQuerySpec("SELECT * FROM root r WHERE r.site_id=@site_id", new SqlParameterCollection(new SqlParameter("@site_id", "ABC"))), @@ -179,7 +183,7 @@ public void groupByInMemory_MoreDetail() { } } - private static String getCollectionLink() { + private String getCollectionLink() { return "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(); } } diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java index c20ef269916bc..39a1a21497dd6 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java @@ -23,11 +23,13 @@ package com.azure.data.cosmos.rx.examples; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.DataType; import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; @@ -35,7 +37,6 @@ import com.azure.data.cosmos.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -53,30 +54,32 @@ * This integration test class demonstrates how to use Async API to query and * replace an Offer. */ -public class OfferCRUDAsyncAPITest { +public class OfferCRUDAsyncAPITest extends DocumentClientTest { private final static int TIMEOUT = 60000; private Database createdDatabase; - private AsyncDocumentClient asyncClient; + private AsyncDocumentClient client; @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.DIRECT); - asyncClient = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.SESSION) - .build(); + + ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + + this.clientBuilder() + .withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.SESSION); + + this.client = this.clientBuilder().build(); // CREATE database - createdDatabase = Utils.createDatabaseForTest(asyncClient); + createdDatabase = Utils.createDatabaseForTest(client); } @AfterClass(groups = "samples", timeOut = TIMEOUT) public void shutdown() { - Utils.safeClean(asyncClient, createdDatabase); - Utils.safeClose(asyncClient); + Utils.safeClean(client, createdDatabase); + Utils.safeClose(client); } /** @@ -94,14 +97,14 @@ public void updateOffer() throws Exception { multiPartitionRequestOptions.setOfferThroughput(initialThroughput); // CREATE the collection - DocumentCollection createdCollection = asyncClient.createCollection("dbs/" + createdDatabase.id(), + DocumentCollection createdCollection = client.createCollection("dbs/" + createdDatabase.id(), getMultiPartitionCollectionDefinition(), multiPartitionRequestOptions).toBlocking().single() - .getResource(); + .getResource(); final CountDownLatch successfulCompletionLatch = new CountDownLatch(1); // Find offer associated with this collection - asyncClient.queryOffers( + client.queryOffers( String.format("SELECT * FROM r where r.offerResourceId = '%s'", createdCollection.resourceId()), null).flatMap(offerFeedResponse -> { List offerList = offerFeedResponse.results(); @@ -119,7 +122,7 @@ public void updateOffer() throws Exception { offer.setThroughput(newThroughput); // REPLACE the offer - return asyncClient.replaceOffer(offer); + return client.replaceOffer(offer); }).subscribe(offerResourceResponse -> { Offer offer = offerResourceResponse.getResource(); int currentThroughput = offer.getThroughput(); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java index a3abfc1bc210a..0549f86f152c1 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java @@ -23,11 +23,13 @@ package com.azure.data.cosmos.rx.examples; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.DataType; import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; @@ -37,7 +39,6 @@ import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.StoredProcedure; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -58,35 +59,37 @@ * This integration test class demonstrates how to use Async API to create * and execute Stored Procedures. */ -public class StoredProcedureAsyncAPITest { +public class StoredProcedureAsyncAPITest extends DocumentClientTest { private final static int TIMEOUT = 60000; private Database createdDatabase; private DocumentCollection createdCollection; - private AsyncDocumentClient asyncClient; + private AsyncDocumentClient client; @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.DIRECT); - asyncClient = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.SESSION) - .build(); - - createdDatabase = Utils.createDatabaseForTest(asyncClient); - - createdCollection = asyncClient + + ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + + this.clientBuilder() + .withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.SESSION); + + this.client = this.clientBuilder().build(); + + createdDatabase = Utils.createDatabaseForTest(client); + + createdCollection = client .createCollection("dbs/" + createdDatabase.id(), getMultiPartitionCollectionDefinition(), null) .toBlocking().single().getResource(); } @AfterClass(groups = "samples", timeOut = TIMEOUT) public void shutdown() { - Utils.safeClean(asyncClient, createdDatabase); - Utils.safeClose(asyncClient); + Utils.safeClean(client, createdDatabase); + Utils.safeClose(client); } /** @@ -104,16 +107,16 @@ public void scriptConsoleLogEnabled() throws Exception { " var myval = 1;" + " try {" + " console.log(\"The value of %s is %s.\", mytext, myval);" + - " getContext().getResponse().body(\"Success!\");" + + " getContext().getResponse().setBody(\"Success!\");" + " }" + " catch(err) {" + - " getContext().getResponse().body(\"inline err: [\" + err.number + \"] \" + err);" + + " getContext().getResponse().setBody(\"inline err: [\" + err.number + \"] \" + err);" + " }" + " }'" + "}"); - storedProcedure = asyncClient.createStoredProcedure(getCollectionLink(), storedProcedure, null) - .toBlocking().single().getResource(); + storedProcedure = client.createStoredProcedure(getCollectionLink(), storedProcedure, null) + .toBlocking().single().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setScriptLoggingEnabled(true); @@ -122,8 +125,8 @@ public void scriptConsoleLogEnabled() throws Exception { final CountDownLatch successfulCompletionLatch = new CountDownLatch(1); // Execute the stored procedure - asyncClient.executeStoredProcedure(getSprocLink(storedProcedure), requestOptions, new Object[]{}) - .subscribe(storedProcedureResponse -> { + client.executeStoredProcedure(getSprocLink(storedProcedure), requestOptions, new Object[]{}) + .subscribe(storedProcedureResponse -> { String logResult = "The value of x is 1."; try { assertThat(URLDecoder.decode(storedProcedureResponse.getScriptLog(), "UTF-8"), is(logResult)); @@ -153,13 +156,13 @@ public void executeStoredProcWithArgs() throws Exception { " 'id': 'multiplySample'," + " 'body':" + " 'function (value, num) {" + - " getContext().getResponse().body(" + + " getContext().getResponse().setBody(" + " \"2*\" + value + \" is \" + num * 2 );" + " }'" + "}"); - storedProcedure = asyncClient.createStoredProcedure(getCollectionLink(), storedProcedure, null) - .toBlocking().single().getResource(); + storedProcedure = client.createStoredProcedure(getCollectionLink(), storedProcedure, null) + .toBlocking().single().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey("Seattle")); @@ -168,8 +171,8 @@ public void executeStoredProcWithArgs() throws Exception { // Execute the stored procedure Object[] storedProcedureArgs = new Object[]{"a", 123}; - asyncClient.executeStoredProcedure(getSprocLink(storedProcedure), requestOptions, storedProcedureArgs) - .subscribe(storedProcedureResponse -> { + client.executeStoredProcedure(getSprocLink(storedProcedure), requestOptions, storedProcedureArgs) + .subscribe(storedProcedureResponse -> { String storedProcResultAsString = storedProcedureResponse.getResponseAsString(); assertThat(storedProcResultAsString, equalTo("\"2*a is 246\"")); successfulCompletionLatch.countDown(); @@ -193,13 +196,13 @@ public void executeStoredProcWithPojoArgs() throws Exception { " 'id': 'storedProcedurePojoSample'," + " 'body':" + " 'function (value) {" + - " getContext().getResponse().body(" + + " getContext().getResponse().setBody(" + " \"a is \" + value.temp);" + " }'" + "}"); - storedProcedure = asyncClient.createStoredProcedure(getCollectionLink(), storedProcedure, null) - .toBlocking().single().getResource(); + storedProcedure = client.createStoredProcedure(getCollectionLink(), storedProcedure, null) + .toBlocking().single().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey("Seattle")); @@ -214,8 +217,8 @@ class SamplePojo { // Execute the stored procedure Object[] storedProcedureArgs = new Object[]{samplePojo}; - asyncClient.executeStoredProcedure(getSprocLink(storedProcedure), requestOptions, storedProcedureArgs) - .subscribe(storedProcedureResponse -> { + client.executeStoredProcedure(getSprocLink(storedProcedure), requestOptions, storedProcedureArgs) + .subscribe(storedProcedureResponse -> { String storedProcResultAsString = storedProcedureResponse.getResponseAsString(); assertThat(storedProcResultAsString, equalTo("\"a is my temp value\"")); successfulCompletionLatch.countDown(); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java index 0b7c7467cbb6d..7054ca8e7a08d 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java @@ -22,9 +22,8 @@ */ package com.azure.data.cosmos.rx.examples; -import org.apache.commons.lang3.StringUtils; - import com.google.common.base.Strings; +import org.apache.commons.lang3.StringUtils; /** * Contains the configurations for tests. diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java index 7ace3b7d0d852..2f2e36953f05b 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java @@ -23,13 +23,14 @@ package com.azure.data.cosmos.rx.examples; -import com.google.common.collect.ImmutableMap; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosResourceType; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; @@ -39,7 +40,7 @@ import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.TokenResolver; import com.azure.data.cosmos.User; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.google.common.collect.ImmutableMap; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -53,14 +54,15 @@ import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.IsInstanceOf.instanceOf; -public class TokenResolverTest { +public class TokenResolverTest extends DocumentClientTest { + private final static int TIMEOUT = 60000; private final static String USER_ID = "userId"; - private AsyncDocumentClient asyncClient; + private AsyncDocumentClient client; private Database createdDatabase; private DocumentCollection createdCollection; private Map userToReadOnlyResourceTokenMap = new HashMap<>(); @@ -76,15 +78,16 @@ public class TokenResolverTest { */ @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { - // Sets up the requirements for each test - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.DIRECT); - asyncClient = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.SESSION) - .build(); + + ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + + this.clientBuilder() + .withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.SESSION); + + this.client = this.clientBuilder().build(); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.id(UUID.randomUUID().toString()); @@ -95,10 +98,10 @@ public void setUp() { collectionDefinition.setPartitionKey(partitionKeyDef); // CREATE database - createdDatabase = Utils.createDatabaseForTest(asyncClient); + createdDatabase = Utils.createDatabaseForTest(client); // CREATE collection - createdCollection = asyncClient + createdCollection = client .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) .toBlocking().single().getResource(); @@ -106,12 +109,12 @@ public void setUp() { // CREATE a document Document documentDefinition = new Document(); documentDefinition.id(UUID.randomUUID().toString()); - Document createdDocument = asyncClient.createDocument(createdCollection.selfLink(), documentDefinition, null, true).toBlocking().first().getResource(); + Document createdDocument = client.createDocument(createdCollection.selfLink(), documentDefinition, null, true).toBlocking().first().getResource(); // CREATE a User who is meant to only read this document User readUserDefinition = new User(); readUserDefinition.id(UUID.randomUUID().toString()); - User createdReadUser = asyncClient.createUser(createdDatabase.selfLink(), readUserDefinition, null).toBlocking().first().getResource(); + User createdReadUser = client.createUser(createdDatabase.selfLink(), readUserDefinition, null).toBlocking().first().getResource(); // CREATE a read only permission for the above document Permission readOnlyPermissionDefinition = new Permission(); @@ -120,7 +123,7 @@ public void setUp() { readOnlyPermissionDefinition.setPermissionMode(PermissionMode.READ); // Assign the permission to the above user - Permission readOnlyCreatedPermission = asyncClient.createPermission(createdReadUser.selfLink(), readOnlyPermissionDefinition, null).toBlocking().first().getResource(); + Permission readOnlyCreatedPermission = client.createPermission(createdReadUser.selfLink(), readOnlyPermissionDefinition, null).toBlocking().first().getResource(); userToReadOnlyResourceTokenMap.put(createdReadUser.id(), readOnlyCreatedPermission.getToken()); documentToReadUserMap.put(createdDocument.selfLink(), createdReadUser.id()); @@ -128,7 +131,7 @@ public void setUp() { // CREATE a User who can both read and write this document User readWriteUserDefinition = new User(); readWriteUserDefinition.id(UUID.randomUUID().toString()); - User createdReadWriteUser = asyncClient.createUser(createdDatabase.selfLink(), readWriteUserDefinition, null).toBlocking().first().getResource(); + User createdReadWriteUser = client.createUser(createdDatabase.selfLink(), readWriteUserDefinition, null).toBlocking().first().getResource(); // CREATE a read/write permission for the above document Permission readWritePermissionDefinition = new Permission(); @@ -137,7 +140,7 @@ public void setUp() { readWritePermissionDefinition.setPermissionMode(PermissionMode.ALL); // Assign the permission to the above user - Permission readWriteCreatedPermission = asyncClient.createPermission(createdReadWriteUser.selfLink(), readWritePermissionDefinition, null).toBlocking().first().getResource(); + Permission readWriteCreatedPermission = client.createPermission(createdReadWriteUser.selfLink(), readWritePermissionDefinition, null).toBlocking().first().getResource(); userToReadWriteResourceTokenMap.put(createdReadWriteUser.id(), readWriteCreatedPermission.getToken()); documentToReadWriteUserMap.put(createdDocument.selfLink(), createdReadWriteUser.id()); @@ -339,7 +342,7 @@ private TokenResolver getTokenResolverWithBlockList(String blockListedUserId, St @AfterClass(groups = "samples", timeOut = TIMEOUT) public void shutdown() { - Utils.safeClean(asyncClient, createdDatabase); - Utils.safeClose(asyncClient); + Utils.safeClean(client, createdDatabase); + Utils.safeClose(client); } } diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java index de891e6d020e7..44c8b56193ee4 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java @@ -22,7 +22,19 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentClientTest; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.UniqueKey; +import com.azure.data.cosmos.UniqueKeyPolicy; import com.google.common.collect.ImmutableList; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -38,7 +50,8 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; -public class UniqueIndexAsyncAPITest { +public class UniqueIndexAsyncAPITest extends DocumentClientTest { + private final static int TIMEOUT = 60000; private AsyncDocumentClient client; @@ -86,15 +99,16 @@ public void uniqueIndex() { @BeforeClass(groups = "samples", timeOut = TIMEOUT) public void setUp() { - // Sets up the requirements for each test - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.DIRECT); - client = new AsyncDocumentClient.Builder() - .withServiceEndpoint(TestConfigurations.HOST) - .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) - .withConnectionPolicy(connectionPolicy) - .withConsistencyLevel(ConsistencyLevel.SESSION) - .build(); + + ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); + + this.clientBuilder() + .withServiceEndpoint(TestConfigurations.HOST) + .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) + .withConnectionPolicy(connectionPolicy) + .withConsistencyLevel(ConsistencyLevel.SESSION); + + this.client = this.clientBuilder().build(); DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.id(UUID.randomUUID().toString()); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java index 6f386435ac7e1..32d9bdd93aeb9 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.rx.examples; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.Database; @@ -32,7 +33,6 @@ import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.rx.TestConfigurations; import org.testng.annotations.AfterSuite; import rx.Observable; diff --git a/gateway/pom.xml b/gateway/pom.xml index ab4eaec0ab1ab..d382cfcdc2b3e 100644 --- a/gateway/pom.xml +++ b/gateway/pom.xml @@ -114,12 +114,6 @@ SOFTWARE. ${assertj.version} test - - org.mockito - mockito-all - ${mockito.version} - test - org.slf4j slf4j-log4j12 diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java b/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java index 957589bd79f3d..1d2bd67ef18de 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java @@ -22,15 +22,14 @@ */ package com.azure.data.cosmos.internal; -import java.time.Duration; - - import rx.Observable; import rx.Single; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; +import java.time.Duration; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java index 31051a2c88e45..b537fd1b557f6 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java @@ -23,6 +23,12 @@ package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.directconnectivity.HttpUtils; +import org.apache.commons.lang3.StringUtils; + +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; import java.net.URI; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -31,14 +37,6 @@ import java.util.Locale; import java.util.Map; -import javax.crypto.Mac; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.lang3.StringUtils; - -import com.azure.data.cosmos.directconnectivity.HttpUtils; - /** * This class is used internally by both client (for generating the auth header with master/system key) and by the GATEWAY when * verifying the auth header in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java b/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java index b098305b6c683..e5f9de5aea0f2 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java @@ -23,12 +23,13 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.routing.LocationHelper; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.DatabaseAccount; import com.azure.data.cosmos.DatabaseAccountManagerInternal; import com.azure.data.cosmos.internal.routing.LocationCache; +import com.azure.data.cosmos.internal.routing.LocationHelper; +import org.apache.commons.collections4.list.UnmodifiableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Completable; @@ -37,8 +38,6 @@ import rx.Single; import rx.functions.Func1; import rx.schedulers.Schedulers; -import org.apache.commons.collections4.list.UnmodifiableList; - import java.net.URISyntaxException; import java.net.URL; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java index 301805724c7fa..c3be709965255 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; - import rx.Single; import java.util.Map; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java index a282ad4950861..f1fcab0f6f4bc 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos.internal; -import java.time.Duration; - import rx.Single; +import java.time.Duration; + // TODO update documentation /** * While this class is public, but it is not part of our published public APIs. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java index 986a5296d3122..ef8f4fa74868e 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java @@ -22,14 +22,13 @@ */ package com.azure.data.cosmos.internal; -import java.util.List; -import java.util.Map; - import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.internal.routing.Range; - import rx.Single; +import java.util.List; +import java.util.Map; + //TODO: update documentation //TODO: add two overload methods for forceRefresh = false /** diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java index 01dfc640aa77b..15caec2ee57c3 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java @@ -22,14 +22,13 @@ */ package com.azure.data.cosmos.internal; -import java.time.Duration; - -import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; - +import com.azure.data.cosmos.internal.caches.RxCollectionCache; import rx.Single; +import java.time.Duration; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java index a13a01ed1210c..88830089cb014 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java @@ -22,15 +22,14 @@ */ package com.azure.data.cosmos.internal; -import java.time.Duration; -import java.util.concurrent.atomic.AtomicInteger; - -import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.RequestOptions; - +import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import rx.Single; +import java.time.Duration; +import java.util.concurrent.atomic.AtomicInteger; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java index eaa826d076a66..74bf67abcb011 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java @@ -22,18 +22,17 @@ */ package com.azure.data.cosmos.internal; -import java.time.Duration; - -import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; -import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; - import rx.Observable; import rx.Single; +import java.time.Duration; + // TODO: this need testing /** * While this class is public, but it is not part of our published public APIs. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java index cbc952f930104..d9a5a8de7f1e4 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java @@ -22,16 +22,13 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.ISessionContainer; - +import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import org.apache.commons.lang3.StringUtils; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import rx.Single; import java.time.Duration; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java index 89273b00427cf..dd6c46770e2f3 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java @@ -22,8 +22,8 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; public class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java index e1252acf54c6a..4095df95601f8 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java @@ -22,14 +22,13 @@ */ package com.azure.data.cosmos.internal; -import java.time.Duration; - import com.azure.data.cosmos.CosmosClientException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import rx.Single; +import java.time.Duration; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java index 4fcf2e16b80c6..c356d4eb645bd 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java @@ -22,17 +22,16 @@ */ package com.azure.data.cosmos.internal; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - import org.apache.commons.lang3.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import rx.Observable; import rx.Single; import rx.functions.Func1; +import java.time.Duration; +import java.util.concurrent.TimeUnit; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java index 7500a5249e3c4..2719039b3e1c6 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java @@ -23,8 +23,11 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.StoreResponse; import io.netty.buffer.ByteBuf; @@ -528,7 +531,7 @@ private void applySessionToken(RxDocumentServiceRequest request) { boolean sessionConsistency = this.defaultConsistencyLevel == ConsistencyLevel.SESSION || (!Strings.isNullOrEmpty(requestConsistencyLevel) - && Strings.areEqual(requestConsistencyLevel, ConsistencyLevel.SESSION.name())); + && Strings.areEqual(requestConsistencyLevel, ConsistencyLevel.SESSION.toString())); if (!sessionConsistency || ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) { return; // Only apply the session token in case of session consistency and when resource is not a master resource diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java index 090b3c139fac8..32a5f75ffe47d 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java @@ -22,15 +22,14 @@ */ package com.azure.data.cosmos.internal.caches; -import java.util.concurrent.ConcurrentHashMap; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import rx.Observable; import rx.Single; import rx.functions.Func0; +import java.util.concurrent.ConcurrentHashMap; + public class AsyncCache { private final Logger logger = LoggerFactory.getLogger(AsyncCache.class); diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java index ce303a8c88457..cc7053a2735a0 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java @@ -24,7 +24,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import rx.Single; import rx.functions.Func0; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java index 28cc4742fda47..43f5c8ec066ea 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java @@ -22,17 +22,16 @@ */ package com.azure.data.cosmos.internal.caches; -import java.util.List; -import java.util.Map; - import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; -import com.azure.data.cosmos.internal.routing.Range; import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; import com.azure.data.cosmos.internal.IRoutingMapProvider; - +import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.Range; import rx.Single; +import java.util.List; +import java.util.Map; + /** * */ diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java index bdf003c8d58ad..08a1346bbbd36 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java @@ -22,32 +22,31 @@ */ package com.azure.data.cosmos.internal.caches; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.Map; - -import com.azure.data.cosmos.internal.AuthorizationTokenType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.PathsHelper; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.ClearingSessionContainerClientRetryPolicy; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; import com.azure.data.cosmos.internal.IRetryPolicyFactory; import com.azure.data.cosmos.internal.ObservableHelper; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import com.azure.data.cosmos.internal.RxStoreModel; - +import com.azure.data.cosmos.internal.Utils; import rx.Observable; import rx.Single; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.Map; + /** * Caches collection information. * While this class is public, but it is not part of our published public APIs. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java index 999c5e31848a6..adfcc0689804a 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java @@ -22,17 +22,15 @@ */ package com.azure.data.cosmos.internal.caches; -import com.azure.data.cosmos.internal.RMResources; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import org.apache.commons.lang3.StringUtils; - import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.internal.NotFoundException; import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.ResourceId; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.internal.InvalidPartitionException; -import com.azure.data.cosmos.internal.NotFoundException; - +import org.apache.commons.lang3.StringUtils; import rx.Completable; import rx.Single; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java index cce589007c151..4abc554dda8f2 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java @@ -23,17 +23,10 @@ package com.azure.data.cosmos.internal.query; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.function.Function; - import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.Undefined; import com.azure.data.cosmos.internal.Constants; @@ -45,10 +38,16 @@ import com.azure.data.cosmos.internal.query.aggregation.MaxAggregator; import com.azure.data.cosmos.internal.query.aggregation.MinAggregator; import com.azure.data.cosmos.internal.query.aggregation.SumAggregator; -import com.azure.data.cosmos.QueryMetrics; - import rx.Observable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.function.Function; + public class AggregateDocumentQueryExecutionContext implements IDocumentQueryExecutionComponent{ private IDocumentQueryExecutionComponent component; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java index bf18b9a748636..27e8ed69d592c 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java @@ -24,9 +24,8 @@ package com.azure.data.cosmos.internal.query; import com.azure.data.cosmos.JsonSerializable; -import com.azure.data.cosmos.internal.routing.Range; import com.azure.data.cosmos.internal.Utils.ValueHolder; - +import com.azure.data.cosmos.internal.routing.Range; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java index 33af8d8b68699..bd24a186bf5c4 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java @@ -22,39 +22,33 @@ */ package com.azure.data.cosmos.internal.query; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.Strings; -import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; -import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.BackoffRetryUtility; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.PathsHelper; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; -import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.internal.routing.Range; -import com.azure.data.cosmos.internal.BackoffRetryUtility; import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; import com.azure.data.cosmos.internal.InvalidPartitionExceptionRetryPolicy; import com.azure.data.cosmos.internal.PartitionKeyRangeGoneRetryPolicy; +import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.internal.Utils.ValueHolder; +import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; import com.azure.data.cosmos.internal.query.metrics.FetchExecutionRangeAccumulator; -import com.azure.data.cosmos.QueryMetrics; import com.azure.data.cosmos.internal.query.metrics.SchedulingStopwatch; import com.azure.data.cosmos.internal.query.metrics.SchedulingTimeSpan; - +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.routing.Range; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import rx.Observable; @@ -62,6 +56,11 @@ import rx.functions.Func1; import rx.functions.Func2; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java index 0743397c3b2f3..9181fbeef53f8 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java @@ -22,31 +22,29 @@ */ package com.azure.data.cosmos.internal.query; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.QueryMetricsConstants; +import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.Exceptions; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; import com.azure.data.cosmos.internal.ObservableHelper; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; import com.azure.data.cosmos.internal.query.metrics.FetchExecutionRangeAccumulator; import com.azure.data.cosmos.internal.query.metrics.SchedulingStopwatch; import com.azure.data.cosmos.internal.query.metrics.SchedulingTimeSpan; - +import com.azure.data.cosmos.internal.routing.Range; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import com.azure.data.cosmos.internal.routing.Range; -import com.azure.data.cosmos.internal.Utils; - import rx.Observable; import rx.Single; import rx.functions.Func0; @@ -54,6 +52,12 @@ import rx.functions.Func2; import rx.functions.Func3; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java index 23b4b6967ebbb..e317c133dec78 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java @@ -22,14 +22,6 @@ */ package com.azure.data.cosmos.internal.query; -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.RxDocumentServiceResponse; -import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.FeedOptions; @@ -40,16 +32,23 @@ import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ReplicatedResourceClientUtils; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RuntimeConstants.MediaTypes; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.internal.ReplicatedResourceClientUtils; -import com.azure.data.cosmos.internal.Utils; - import rx.Observable; import rx.Single; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. @@ -200,7 +199,7 @@ public Map createCommonHeadersAsync(FeedOptions feedOptions) { } if (desiredConsistencyLevel != null) { - requestHeaders.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, desiredConsistencyLevel.name()); + requestHeaders.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, desiredConsistencyLevel.toString()); } if(feedOptions.populateQueryMetrics()){ diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java index 09ced6f4a909d..8b1118dd45e74 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java @@ -22,12 +22,6 @@ */ package com.azure.data.cosmos.internal.query; -import java.util.List; -import java.util.UUID; - -import com.azure.data.cosmos.internal.BadRequestException; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; @@ -35,13 +29,18 @@ import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.BadRequestException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; - +import com.azure.data.cosmos.internal.caches.RxCollectionCache; import rx.Observable; import rx.Single; +import java.util.List; +import java.util.UUID; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java index 4f12105383908..d5f1834c53897 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java @@ -23,16 +23,14 @@ package com.azure.data.cosmos.internal.query; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.FeedOptionsBase; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; - +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java index 99358069c2a8f..6a9016170dcb1 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java @@ -22,13 +22,12 @@ */ package com.azure.data.cosmos.internal.query; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.internal.IRetryPolicyFactory; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; import com.azure.data.cosmos.internal.caches.RxCollectionCache; -import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.internal.IRetryPolicyFactory; - import rx.Single; /** diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java index 21db3d2249cee..a0f223edf6e7e 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java @@ -24,7 +24,6 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; - import rx.Observable; /** diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java index f26e61a9ca83c..abac466aa9595 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java @@ -24,7 +24,6 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; - import rx.Observable; /** diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java index 08f2c477ed6ec..5928d5fa0cd6b 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java @@ -23,16 +23,15 @@ package com.azure.data.cosmos.internal.query; -import java.util.ArrayList; -import java.util.List; - +import com.azure.data.cosmos.JsonSerializable; +import com.azure.data.cosmos.internal.Utils.ValueHolder; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.azure.data.cosmos.JsonSerializable; -import com.azure.data.cosmos.internal.Utils.ValueHolder; +import java.util.ArrayList; +import java.util.List; /** * While this class is public, but it is not part of our published public APIs. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java index 1a656332fb45e..beca1b5f00d90 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java @@ -22,30 +22,29 @@ */ package com.azure.data.cosmos.internal.query; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; import com.azure.data.cosmos.internal.RequestChargeTracker; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; -import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; -import com.azure.data.cosmos.internal.Utils; - -import com.azure.data.cosmos.QueryMetrics; import rx.Observable; import rx.functions.Func0; import rx.functions.Func1; import rx.functions.Func3; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + class OrderByDocumentProducer extends DocumentProducer { private final OrderbyRowComparer consumeComparer; private final Map targetRangeToOrderByContinuationTokenMap; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java index a34ac6091ff22..927f456fa646e 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java @@ -22,37 +22,42 @@ */ package com.azure.data.cosmos.internal.query; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.function.Function; - -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import org.apache.commons.lang3.NotImplementedException; -import org.apache.commons.lang3.tuple.ImmutablePair; - +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; import com.azure.data.cosmos.internal.routing.Range; -import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; -import com.azure.data.cosmos.internal.Utils; -import com.azure.data.cosmos.internal.Utils.ValueHolder; - +import org.apache.commons.lang3.NotImplementedException; +import org.apache.commons.lang3.tuple.ImmutablePair; import rx.Observable; import rx.Observable.Transformer; import rx.functions.Func0; import rx.functions.Func1; import rx.functions.Func3; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.function.Function; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java index 614668acd8ea4..05730e8398d95 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java @@ -22,26 +22,25 @@ */ package com.azure.data.cosmos.internal.query; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.internal.BadRequestException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.github.davidmoten.rx.Transformers; +import com.azure.data.cosmos.QueryMetrics; import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.BadRequestException; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceId; import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; -import com.azure.data.cosmos.QueryMetrics; - +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.github.davidmoten.rx.Transformers; import org.apache.commons.lang3.tuple.Pair; import rx.Observable; import rx.Observable.Transformer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + class OrderByUtils { public static Observable> orderedMerge(Class klass, diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java index d042f7a8d0f1f..62fc3f463b1bd 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java @@ -22,12 +22,12 @@ */ package com.azure.data.cosmos.internal.query; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedOptionsBase; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java index 231edd075b6d7..faf83eac6c9bd 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java @@ -22,30 +22,34 @@ */ package com.azure.data.cosmos.internal.query; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import org.apache.commons.lang3.tuple.ImmutablePair; - +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.Utils.ValueHolder; - +import org.apache.commons.lang3.tuple.ImmutablePair; import rx.Observable; import rx.Observable.Transformer; import rx.functions.Func0; import rx.functions.Func1; import rx.functions.Func3; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java index 59ed7a63f95cb..be0fdd8a3971b 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java @@ -22,14 +22,6 @@ */ package com.azure.data.cosmos.internal.query; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; @@ -37,15 +29,22 @@ import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.internal.routing.Range; -import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; - import rx.Observable; import rx.functions.Func0; import rx.functions.Func1; import rx.functions.Func3; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java index 845cd62b8d522..0052d917d6582 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.query; -import java.util.List; - import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.routing.Range; +import java.util.List; + /** * Used internally to encapsulates execution information for a query in the Azure Cosmos DB database service. */ diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java index 0a760d5206072..3fd872b9607fb 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java @@ -23,14 +23,14 @@ package com.azure.data.cosmos.internal.query; -import java.util.List; - -import com.fasterxml.jackson.core.JsonProcessingException; import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.routing.Range; +import com.fasterxml.jackson.core.JsonProcessingException; + +import java.util.List; public final class PartitionedQueryExecutionInfoInternal extends JsonSerializable { static final String QUERY_INFO_PROPERTY = "queryInfo"; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java index eee88a441c474..61d0fd68cc4c8 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java @@ -22,10 +22,6 @@ */ package com.azure.data.cosmos.internal.query; -import java.util.List; -import java.util.UUID; -import java.util.function.Function; - import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyRange; @@ -33,9 +29,12 @@ import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.Utils; - import rx.Observable; +import java.util.List; +import java.util.UUID; +import java.util.function.Function; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java index 149c39de27526..dc8879b669cfc 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java @@ -22,14 +22,6 @@ */ package com.azure.data.cosmos.internal.query; -import java.lang.invoke.MethodHandles; -import java.util.List; -import java.util.UUID; - -import com.azure.data.cosmos.internal.Exceptions; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; @@ -37,14 +29,20 @@ import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.Utils; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import rx.Observable; import rx.Single; import rx.functions.Func1; +import java.lang.invoke.MethodHandles; +import java.util.List; +import java.util.UUID; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java index 3fe617fa279a9..8c4d6e1cd3c77 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java @@ -23,13 +23,12 @@ package com.azure.data.cosmos.internal.query; -import java.util.Collection; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; - import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.internal.query.aggregation.AggregateOperator; +import org.apache.commons.lang3.StringUtils; + +import java.util.Collection; +import java.util.List; /** * Used internally to encapsulates a query's information in the Azure Cosmos DB database service. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java index 0c4723593c54d..c0922f0d454a6 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java @@ -25,7 +25,6 @@ import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.internal.Utils.ValueHolder; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java index 0ced4bfbe3de2..e04b0e052b7df 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java @@ -23,20 +23,19 @@ package com.azure.data.cosmos.internal.query; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Utils.ValueHolder; - import rx.Observable; import rx.functions.Func1; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + public class TopDocumentQueryExecutionContext implements IDocumentQueryExecutionComponent { private final IDocumentQueryExecutionComponent component; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java index 535f6ba1d681d..1ecbbb4afaf06 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos.internal.query.aggregation; -import java.io.IOException; - import com.azure.data.cosmos.Undefined; import com.azure.data.cosmos.internal.Utils; +import java.io.IOException; + public class AverageAggregator implements Aggregator { private AverageInfo averageInfo; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java index 851988e86538d..18509e3fe8027 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.query.orderbyquery; -import java.util.List; - import com.azure.data.cosmos.Document; import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.internal.query.QueryItem; +import java.util.List; + /** * Represents the result of a query in the Azure Cosmos DB database service. */ diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java index 4b0682cde9171..a61aee098509c 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java @@ -23,19 +23,18 @@ package com.azure.data.cosmos.internal.query.orderbyquery; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.azure.data.cosmos.internal.query.ItemComparator; import com.azure.data.cosmos.internal.query.ItemType; import com.azure.data.cosmos.internal.query.ItemTypeHelper; import com.azure.data.cosmos.internal.query.QueryItem; import com.azure.data.cosmos.internal.query.SortOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; public final class OrderbyRowComparer implements Comparator> { private static final Logger logger = LoggerFactory.getLogger(OrderbyRowComparer.class); diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java index 38b6080b5f414..b5ad73c4a1453 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; -import java.util.Collection; -import java.util.List; - import com.azure.data.cosmos.PartitionKeyRange; import org.apache.commons.lang3.tuple.ImmutablePair; +import java.util.Collection; +import java.util.List; + /** * Used internally in request routing in the Azure Cosmos DB database service. */ diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java index ae67c6570239b..b15f5fd96c1e2 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java @@ -23,6 +23,11 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.PartitionKeyRange; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; + import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -35,12 +40,6 @@ import java.util.TreeMap; import java.util.stream.Collectors; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; - -import com.azure.data.cosmos.PartitionKeyRange; -import org.apache.commons.lang3.tuple.Pair; - /** * Used internally to cache partition key ranges of a collection in the Azure Cosmos DB database service. */ diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java index 2af8746a7236f..7e7f276919f32 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java @@ -26,16 +26,17 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.DatabaseAccount; import com.azure.data.cosmos.DatabaseAccountLocation; -import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.internal.Utils; +import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.apache.commons.collections4.map.UnmodifiableMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.apache.commons.collections4.list.UnmodifiableList; -import org.apache.commons.collections4.map.UnmodifiableMap; + import java.net.URL; import java.time.Duration; import java.time.Instant; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java index d0b996534f5ac..6791dc2aa7e7a 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos.internal.routing; -import java.util.Collection; - import com.azure.data.cosmos.PartitionKeyRange; +import java.util.Collection; + /** * Used internally in request routing in the Azure Cosmos DB database service. */ diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java index e8e0ba56148fa..4f6ebf240143a 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.PartitionKeyRange; + import java.util.ArrayList; import java.util.Collection; import java.util.List; -import com.azure.data.cosmos.PartitionKeyRange; - /** * Provide utility functionality to route request in direct connectivity mode in the Azure Cosmos DB database service. */ diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java index 7c74f302ffa55..e6c245b49787b 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos.internal; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; import com.azure.data.cosmos.GatewayTestUtils; import com.azure.data.cosmos.PartitionKeyRange; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java index bf7e6ee2c0ad5..86795d1ca6f34 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java @@ -22,18 +22,17 @@ */ package com.azure.data.cosmos.internal.caches; -import static org.assertj.core.api.Assertions.assertThat; +import org.testng.annotations.Test; +import rx.Observable; +import rx.Single; +import rx.functions.Func1; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; -import org.testng.annotations.Test; - -import rx.Observable; -import rx.Single; -import rx.functions.Func1; +import static org.assertj.core.api.Assertions.assertThat; public class AsyncCacheTest { diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java index 9b3dbc0dd9259..5466feb4f943f 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java @@ -23,19 +23,18 @@ package com.azure.data.cosmos.internal.routing; -import static org.assertj.core.api.Assertions.assertThat; +import com.azure.data.cosmos.PartitionKeyRange; +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; -import com.google.common.collect.ImmutableList; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.testng.annotations.Test; - -import com.azure.data.cosmos.PartitionKeyRange; +import static org.assertj.core.api.Assertions.assertThat; public class InMemoryCollectionRoutingMapTest { diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java index dad666bda1b6c..62cc7ce65bfbf 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java @@ -23,20 +23,20 @@ package com.azure.data.cosmos.internal.routing; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.BridgeUtils; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.DatabaseAccount; import com.azure.data.cosmos.DatabaseAccountLocation; +import com.azure.data.cosmos.DatabaseAccountManagerInternal; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.GlobalEndpointManager; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.GlobalEndpointManager; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.DatabaseAccountManagerInternal; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import org.apache.commons.collections4.list.UnmodifiableList; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java index e5d3016706e11..6cb444c4ad964 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java @@ -23,7 +23,10 @@ package com.azure.data.cosmos.internal.routing; -import static org.assertj.core.api.Assertions.assertThat; +import com.azure.data.cosmos.PartitionKeyRange; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; @@ -33,11 +36,7 @@ import java.util.function.Function; import java.util.stream.Collectors; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.testng.annotations.Test; - -import com.azure.data.cosmos.PartitionKeyRange; +import static org.assertj.core.api.Assertions.assertThat; public class RoutingMapProviderHelperTest { private static final MockRoutingMapProvider ROUTING_MAP_PROVIDER = new MockRoutingMapProvider( diff --git a/pom.xml b/pom.xml index 426d6986c9501..24fbe695a5028 100644 --- a/pom.xml +++ b/pom.xml @@ -34,41 +34,46 @@ commons gateway - examples - benchmark commons-test-utils sdk direct-impl + benchmark + examples UTF-8 UTF-8 + 3.11.1 2.5 3.8.1 - 1.6 1.6 + 1.6 + 1.6 + 3.0.0-a1-SNAPSHOT + 3.0.0-a1-SNAPSHOT + 27.0.1-jre + 1.3 2.9.8 3.1.4 - 1.7.6 + 1.58 1.2.17 - 4.1.32.Final - 0.4.20 - 1.3.8 + 3.2.6 + 1.10.19 + 4.1.36.Final + 2.0.25.Final + 3.2.2.RELEASE + Bismuth-RELEASE 0.8.0.17 + 1.0.3 1.1.1 - 3.2.2.RELEASE - 6.14.3 - 3.11.1 - 1.10.19 - 27.0.1-jre - 0.13.3 + 1.3.8 2.2.4 - 1.6 - Bismuth-RELEASE - unit + 0.13.3 + 0.4.20 3.0.0-a1-SNAPSHOT - 3.0.0-a1-SNAPSHOT - 3.0.0-a1-SNAPSHOT + 1.7.6 + unit + 6.14.3 ${project.basedir}/target/collectedArtifactsForRelease @@ -443,14 +448,7 @@ - - - org.testng - testng - ${testng.version} - test - - + MIT License diff --git a/sdk/pom.xml b/sdk/pom.xml index 6c7c9920a867b..47f5d22f5863e 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -258,12 +258,6 @@ SOFTWARE. ${assertj.version} test - - org.mockito - mockito-all - ${mockito.version} - test - org.slf4j slf4j-log4j12 diff --git a/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java b/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java index bc70d8771aded..d0190ad050548 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java @@ -22,15 +22,14 @@ */ package com.azure.data.cosmos; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; - import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.RxDocumentClientImpl; - import rx.Observable; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + /** * Provides a client-side logical representation of the Azure Cosmos DB * database service. This async client is used to configure and execute requests diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java index 8ce56f5a86c69..fce5651c8feb0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.changefeed.internal.ChangeFeedProcessorBuilderImpl; - import reactor.core.publisher.Mono; /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java index a1875b6c54f10..46f7585d61d52 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java @@ -22,9 +22,8 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Configs; - +import com.azure.data.cosmos.internal.HttpConstants; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index 3f91daed14afb..1e067bfaada93 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -24,7 +24,6 @@ import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Paths; - import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; @@ -274,7 +273,7 @@ public Mono upsertItem(Object item, CosmosItemRequestOptions return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.getDatabase() .getDocClientWrapper() .upsertDocument(this.getLink(), - item, + CosmosItemProperties.fromObject(item), options.toRequestOptions(), true) .map(response -> new CosmosItemResponse(response, diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java index cd029919fd2fc..b80f8ffd889b2 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java @@ -24,7 +24,6 @@ import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Paths; - import hu.akarnokd.rxjava.interop.RxJavaInterop; import org.apache.commons.lang3.StringUtils; import reactor.adapter.rxjava.RxJava2Adapter; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionSettings.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionSettings.java index 5e2f2eb583104..8a476087d63ca 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionSettings.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionSettings.java @@ -24,7 +24,6 @@ import com.azure.data.cosmos.internal.Constants; import org.apache.commons.lang3.StringUtils; -import org.apache.commons.text.WordUtils; import java.util.List; import java.util.stream.Collectors; @@ -87,7 +86,7 @@ public PermissionMode getPermissionMode() { */ public void setPermissionMode(PermissionMode permissionMode) { this.set(Constants.Properties.PERMISSION_MODE, - permissionMode.name().toLowerCase()); + permissionMode.toString().toLowerCase()); } /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ChangeFeedContextClient.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ChangeFeedContextClient.java index b7d2dbfe39083..ecb79c0552b31 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ChangeFeedContextClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ChangeFeedContextClient.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.changefeed; +import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerResponse; @@ -30,10 +31,9 @@ import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.CosmosDatabaseResponse; import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.CosmosItemResponse; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyRange; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseManager.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseManager.java index 44c85186b8bb1..b6c80a72e50fc 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseManager.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseManager.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos.changefeed; import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; - import reactor.core.publisher.Mono; /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLease.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLease.java index dd15a593b153a..19e4b177030ef 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLease.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLease.java @@ -22,11 +22,11 @@ */ package com.azure.data.cosmos.changefeed; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.changefeed.internal.Constants; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; import java.time.ZoneId; import java.time.ZonedDateTime; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java index b09968c6de410..c8870be98941a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java @@ -22,7 +22,8 @@ */ package com.azure.data.cosmos.changefeed.internal; -import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerResponse; @@ -31,15 +32,14 @@ import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.CosmosDatabaseResponse; import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.CosmosItemResponse; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; import hu.akarnokd.rxjava.interop.RxJavaInterop; import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java index 5d917c11a54d8..6d462d8ef64ac 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java @@ -25,8 +25,8 @@ import com.azure.data.cosmos.ChangeFeedObserverContext; import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.changefeed.PartitionCheckpointer; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.changefeed.PartitionCheckpointer; import reactor.core.publisher.Mono; /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java index 6c001b584bb11..a7cf1282c160e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java @@ -23,8 +23,8 @@ package com.azure.data.cosmos.changefeed.internal; import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.changefeed.exceptions.ObserverException; import com.azure.data.cosmos.ChangeFeedObserverFactory; +import com.azure.data.cosmos.changefeed.exceptions.ObserverException; /** * DEFAULT implementation for {@link ChangeFeedObserverFactory}. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java index 833fa861bc187..b395a103015cc 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos.changefeed.internal; import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.ChangeFeedObserverFactory; import com.azure.data.cosmos.ChangeFeedProcessor; import com.azure.data.cosmos.ChangeFeedProcessorOptions; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.ChangeFeedObserverFactory; import com.azure.data.cosmos.changefeed.Bootstrapper; import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; import com.azure.data.cosmos.changefeed.HealthMonitor; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/CheckpointerObserverFactory.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/CheckpointerObserverFactory.java index 2988cb9d47bf7..fa85b98b90d81 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/CheckpointerObserverFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/CheckpointerObserverFactory.java @@ -23,8 +23,8 @@ package com.azure.data.cosmos.changefeed.internal; import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.changefeed.CheckpointFrequency; import com.azure.data.cosmos.ChangeFeedObserverFactory; +import com.azure.data.cosmos.changefeed.CheckpointFrequency; /** * Factory class used to create instance(s) of {@link ChangeFeedObserver}. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseStore.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseStore.java index 89da881d1c2d0..60254fcc80ec1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseStore.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseStore.java @@ -22,18 +22,18 @@ */ package com.azure.data.cosmos.changefeed.internal; +import com.azure.data.cosmos.AccessCondition; +import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosItem; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.Document; import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; import com.azure.data.cosmos.changefeed.LeaseStore; import com.azure.data.cosmos.changefeed.RequestOptionsFactory; import com.azure.data.cosmos.changefeed.ServiceItemLease; -import com.azure.data.cosmos.AccessCondition; -import com.azure.data.cosmos.AccessConditionType; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Document; import reactor.core.publisher.Mono; import java.time.Duration; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java index 9969ae4f50c8a..0fdd09b749c97 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java @@ -22,6 +22,9 @@ */ package com.azure.data.cosmos.changefeed.internal; +import com.azure.data.cosmos.AccessCondition; +import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosItem; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemRequestOptions; @@ -31,9 +34,6 @@ import com.azure.data.cosmos.changefeed.ServiceItemLease; import com.azure.data.cosmos.changefeed.ServiceItemLeaseUpdater; import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; -import com.azure.data.cosmos.AccessCondition; -import com.azure.data.cosmos.AccessConditionType; -import com.azure.data.cosmos.CosmosClientException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java index ddd96dca5806a..7756d54e7ddb9 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java @@ -22,11 +22,11 @@ */ package com.azure.data.cosmos.changefeed.internal; +import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.changefeed.HealthMonitor; import com.azure.data.cosmos.changefeed.HealthMonitoringRecord; import com.azure.data.cosmos.changefeed.Lease; import com.azure.data.cosmos.changefeed.PartitionController; -import com.azure.data.cosmos.CosmosClientException; import reactor.core.publisher.Mono; /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseStoreManagerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseStoreManagerImpl.java index fc73b6c6f2b79..426640a6079ee 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseStoreManagerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseStoreManagerImpl.java @@ -22,8 +22,14 @@ */ package com.azure.data.cosmos.changefeed.internal; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.SqlParameter; +import com.azure.data.cosmos.SqlParameterCollection; +import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; import com.azure.data.cosmos.changefeed.Lease; import com.azure.data.cosmos.changefeed.LeaseStore; @@ -32,6 +38,7 @@ import com.azure.data.cosmos.changefeed.RequestOptionsFactory; import com.azure.data.cosmos.changefeed.ServiceItemLease; import com.azure.data.cosmos.changefeed.ServiceItemLeaseUpdater; +import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionControllerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionControllerImpl.java index 450c89cecba95..b53cce50cd806 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionControllerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionControllerImpl.java @@ -22,8 +22,6 @@ */ package com.azure.data.cosmos.changefeed.internal; -import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; -import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; import com.azure.data.cosmos.changefeed.CancellationToken; import com.azure.data.cosmos.changefeed.CancellationTokenSource; import com.azure.data.cosmos.changefeed.Lease; @@ -33,6 +31,8 @@ import com.azure.data.cosmos.changefeed.PartitionSupervisor; import com.azure.data.cosmos.changefeed.PartitionSupervisorFactory; import com.azure.data.cosmos.changefeed.PartitionSynchronizer; +import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; +import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorImpl.java index a52501c7a762f..e596806cf47f1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorImpl.java @@ -24,18 +24,18 @@ import com.azure.data.cosmos.ChangeFeedObserver; import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.changefeed.exceptions.PartitionNotFoundException; -import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; -import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; +import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.changefeed.CancellationToken; import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; import com.azure.data.cosmos.changefeed.PartitionCheckpointer; import com.azure.data.cosmos.changefeed.PartitionProcessor; import com.azure.data.cosmos.changefeed.ProcessorSettings; -import com.azure.data.cosmos.ChangeFeedOptions; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.changefeed.exceptions.PartitionNotFoundException; +import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; +import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; import reactor.core.publisher.Mono; import java.time.Duration; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java index cfb51eb77b664..8830f758f9529 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java @@ -23,8 +23,8 @@ package com.azure.data.cosmos.changefeed.internal; import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedProcessorOptions; import com.azure.data.cosmos.ChangeFeedObserverFactory; +import com.azure.data.cosmos.ChangeFeedProcessorOptions; import com.azure.data.cosmos.changefeed.Lease; import com.azure.data.cosmos.changefeed.LeaseManager; import com.azure.data.cosmos.changefeed.LeaseRenewer; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java index 7b2fce321e25e..e25a94b466063 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java @@ -25,16 +25,16 @@ import com.azure.data.cosmos.ChangeFeedObserver; import com.azure.data.cosmos.ChangeFeedObserverCloseReason; import com.azure.data.cosmos.ChangeFeedObserverContext; -import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; -import com.azure.data.cosmos.changefeed.exceptions.ObserverException; -import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; -import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; import com.azure.data.cosmos.changefeed.CancellationToken; import com.azure.data.cosmos.changefeed.CancellationTokenSource; import com.azure.data.cosmos.changefeed.Lease; import com.azure.data.cosmos.changefeed.LeaseRenewer; import com.azure.data.cosmos.changefeed.PartitionProcessor; import com.azure.data.cosmos.changefeed.PartitionSupervisor; +import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.changefeed.exceptions.ObserverException; +import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; +import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; import reactor.core.publisher.Mono; import java.io.Closeable; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSynchronizerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSynchronizerImpl.java index 9606a536d5a86..0b9a9f4115d9c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSynchronizerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSynchronizerImpl.java @@ -23,13 +23,13 @@ package com.azure.data.cosmos.changefeed.internal; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; import com.azure.data.cosmos.changefeed.Lease; import com.azure.data.cosmos.changefeed.LeaseContainer; import com.azure.data.cosmos.changefeed.LeaseManager; import com.azure.data.cosmos.changefeed.PartitionSynchronizer; -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.PartitionKeyRange; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java index 042ce44cd912f..69d68d1ad3be9 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos.changefeed.internal; import com.azure.data.cosmos.CosmosItemRequestOptions; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.RequestOptionsFactory; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.changefeed.RequestOptionsFactory; /** * Used to create request options for partitioned lease collections, when partition key is defined as /id. diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java index 82e954abeb21e..59a2d5c34ff4b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java @@ -22,22 +22,21 @@ */ package com.azure.data.cosmos.internal; -import java.util.HashMap; -import java.util.Map; - import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.query.Paginator; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.internal.query.Paginator; - import rx.Observable; import rx.Single; import rx.functions.Func1; import rx.functions.Func2; +import java.util.HashMap; +import java.util.Map; + class ChangeFeedQueryImpl { private static final String IfNonMatchAllHeaderValue = "*"; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java index 69b517b17eba0..8a1262f426e88 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java @@ -22,11 +22,8 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; -import com.azure.data.cosmos.internal.directconnectivity.GlobalAddressResolver; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.Conflict; @@ -64,15 +61,18 @@ import com.azure.data.cosmos.directconnectivity.ServerStoreModel; import com.azure.data.cosmos.directconnectivity.StoreClient; import com.azure.data.cosmos.directconnectivity.StoreClientFactory; -import com.azure.data.cosmos.internal.routing.PartitionKeyAndResourceTokenPair; -import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.directconnectivity.GlobalAddressResolver; import com.azure.data.cosmos.internal.query.DocumentQueryExecutionContextFactory; import com.azure.data.cosmos.internal.query.IDocumentQueryClient; import com.azure.data.cosmos.internal.query.IDocumentQueryExecutionContext; import com.azure.data.cosmos.internal.query.Paginator; +import com.azure.data.cosmos.internal.routing.PartitionKeyAndResourceTokenPair; +import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import io.reactivex.netty.protocol.http.client.CompositeHttpClientBuilder; @@ -835,7 +835,7 @@ private Map getRequestHeaders(RequestOptions options) { } if (consistencyLevel != null) { - headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.name()); + headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); } if (options == null) { @@ -856,11 +856,11 @@ private Map getRequestHeaders(RequestOptions options) { } if (options.getConsistencyLevel() != null) { - headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().name()); + headers.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, options.getConsistencyLevel().toString()); } if (options.getIndexingDirective() != null) { - headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().name()); + headers.put(HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, options.getIndexingDirective().toString()); } if (options.getPostTriggerInclude() != null && options.getPostTriggerInclude().size() > 0) { @@ -1085,7 +1085,7 @@ public String getUserAuthorizationToken(String resourceName, private CosmosResourceType resolveCosmosResourceType(ResourceType resourceType) { try { - return CosmosResourceType.valueOf(resourceType.name()); + return CosmosResourceType.valueOf(resourceType.toString()); } catch (IllegalArgumentException e) { return CosmosResourceType.System; } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java index a878a93823ab0..b0af21cb3a3d5 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java @@ -22,38 +22,36 @@ */ package com.azure.data.cosmos.internal.caches; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.internal.routing.IServerIdentity; -import com.azure.data.cosmos.internal.NotFoundException; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.NotFoundException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.IServerIdentity; import com.azure.data.cosmos.internal.routing.InMemoryCollectionRoutingMap; import com.azure.data.cosmos.internal.routing.Range; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.internal.Exceptions; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.Utils; - +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import rx.Observable; import rx.Single; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java index 1fc1822e73e50..3d0fb93b71678 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java @@ -24,23 +24,23 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.directconnectivity.AddressInformation; import com.azure.data.cosmos.directconnectivity.AddressResolver; import com.azure.data.cosmos.directconnectivity.GatewayAddressCache; import com.azure.data.cosmos.directconnectivity.GatewayServiceConfigurationReader; import com.azure.data.cosmos.directconnectivity.IAddressResolver; import com.azure.data.cosmos.directconnectivity.Protocol; -import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; -import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import com.azure.data.cosmos.internal.GlobalEndpointManager; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import rx.Completable; diff --git a/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java index b3caac72443bd..afe66309bdb19 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java @@ -22,12 +22,12 @@ */ package com.azure.data.cosmos; -import java.net.URI; -import java.net.URISyntaxException; - import com.azure.data.cosmos.internal.RxDocumentClientUnderTest; import com.azure.data.cosmos.internal.directconnectivity.ReflectionUtils; +import java.net.URI; +import java.net.URISyntaxException; + public class ClientUnderTestBuilder extends CosmosClientBuilder { public ClientUnderTestBuilder(CosmosClientBuilder builder) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java new file mode 100644 index 0000000000000..b94f12975433e --- /dev/null +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java @@ -0,0 +1,73 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.azure.data.cosmos; + +import com.google.common.base.Strings; +import org.testng.ITest; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; + +import java.lang.reflect.Method; + +public abstract class CosmosClientTest implements ITest { + + private final CosmosClientBuilder clientBuilder; + private String testName; + + public CosmosClientTest() { + this(new CosmosClientBuilder()); + } + + public CosmosClientTest(CosmosClientBuilder clientBuilder) { + this.clientBuilder = clientBuilder; + } + + public final CosmosClientBuilder clientBuilder() { + return this.clientBuilder; + } + + @Override + public final String getTestName() { + return this.testName; + } + + @BeforeMethod(alwaysRun = true) + public final void setTestName(Method method) { + + String connectionMode = this.clientBuilder.getConnectionPolicy().connectionMode() == ConnectionMode.DIRECT + ? "Direct " + this.clientBuilder.getConfigs().getProtocol() + : "Gateway"; + + this.testName = Strings.lenientFormat("%s::%s[%s with %s consistency]", + method.getDeclaringClass().getSimpleName(), + method.getName(), + connectionMode, + clientBuilder.getDesiredConsistencyLevel()); + } + + @AfterMethod(alwaysRun = true) + public final void unsetTestName() { + this.testName = null; + } +} diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosContainerCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosContainerCrudTest.java deleted file mode 100644 index 1f47de95c35e1..0000000000000 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosContainerCrudTest.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.azure.data.cosmos; - -import com.azure.data.cosmos.rx.FailureValidator; - -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; -import reactor.core.publisher.Mono; - -import static org.assertj.core.api.Assertions.assertThat; - -public class CosmosContainerCrudTest extends CosmosTestSuiteBase { - private final static String PRE_EXISTING_DATABASE_ID = getDatabaseId(CosmosContainerCrudTest.class) + "db1"; - private final static String PRE_EXISTING_CONTAINER_ID = getDatabaseId(CosmosContainerCrudTest.class) + "_CONTAINER"; - private final static String DATABASE_ID2 = getDatabaseId(CosmosContainerCrudTest.class) + "db2"; - private final static String CONTAINER_ID2 = getDatabaseId(CosmosContainerCrudTest.class) + "_CONTAINER_2"; - - private CosmosClient client; - private CosmosClientBuilder clientBuilder; - - @Factory(dataProvider = "clientBuilders") - public CosmosContainerCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void testCreateContainer() throws Exception { - CosmosContainerSettings containerSettings = new CosmosContainerSettings(CONTAINER_ID2, "/mypk"); - CosmosDatabase database = client.getDatabase(PRE_EXISTING_DATABASE_ID); - // create the container - Mono createMono = database.createContainer(containerSettings); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(containerSettings.id()).build(); - validateSuccess(createMono, validator); - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void testCreateContainer_AlreadyExists() throws Exception { - CosmosContainerSettings containerSettings = new CosmosContainerSettings("new_container", "/mypk"); - CosmosDatabase database = client.getDatabase(PRE_EXISTING_DATABASE_ID); - - database.createContainer(containerSettings).block(); - - // attempt to create the container again - Mono createMono = database.createContainer(containerSettings); - - // validate - FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); - validateFailure(createMono, validator); - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void testReadContainer() throws Exception { - // read container - CosmosContainerSettings settings = getContainerSettings(); - CosmosContainer container = - client.getDatabase(PRE_EXISTING_DATABASE_ID).createContainer(settings).block().container(); - Mono containerResponseMono = container.read(); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(settings.id()).build(); - validateSuccess(containerResponseMono, validator); - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void testReadContainer_DoesntExist() throws Exception { - CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer("I dont exist"); - // read container - Mono containerResponseMono = container.read(); - // validate - FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(containerResponseMono, validator); - } - - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void testDeleteContainer() throws Exception { - Mono deleteMono = client.getDatabase(PRE_EXISTING_DATABASE_ID) - .getContainer(PRE_EXISTING_CONTAINER_ID) - .delete(); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .nullResource().build(); - validateSuccess(deleteMono, validator); - //TODO validate after deletion the resource is actually deleted (not found) - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void testDeleteContainer_DoesntExist() throws Exception { - Mono deleteMono = client.getDatabase(PRE_EXISTING_DATABASE_ID) - .getContainer("doesnt exixt") - .delete(); - - // validate - FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(deleteMono, validator); - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void testreplaceContainer() throws Exception { - CosmosDatabase database = client.getDatabase(PRE_EXISTING_DATABASE_ID); - - Mono containerMono = database.createContainer(getContainerSettings()); - CosmosContainerResponse containerResponse = containerMono.block(); - CosmosContainer container = containerResponse.container(); - CosmosContainerSettings settings = containerResponse.settings(); - // sanity check - assertThat(settings.indexingPolicy().indexingMode()).isEqualTo(IndexingMode.CONSISTENT); - - // replace indexing mode - IndexingPolicy indexingMode = new IndexingPolicy(); - indexingMode.indexingMode(IndexingMode.LAZY); - settings.indexingPolicy(indexingMode); - Mono replaceMono = container.replace(settings, null); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .indexingMode(IndexingMode.LAZY).build(); - validateSuccess(replaceMono, validator); - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void testGetThroughput(){ - CosmosDatabase database = client.getDatabase(PRE_EXISTING_DATABASE_ID); - - Mono containerMono = database.createContainer(getContainerSettings()); - - CosmosContainerResponse containerResponse = containerMono.block(); - CosmosContainer container = containerResponse.container(); - - Integer throughput = container.readProvisionedThroughput().block(); - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void testReplaceThroughput(){ - CosmosDatabase database = client.getDatabase(PRE_EXISTING_DATABASE_ID); - int newThroughput = 1000; - - Mono containerMono = database.createContainer(getContainerSettings()); - - CosmosContainerResponse containerResponse = containerMono.block(); - CosmosContainer container = containerResponse.container(); - - Integer throughput = container.replaceProvisionedThroughputAsync(newThroughput).block(); - assertThat(throughput).isEqualTo(newThroughput); - } - - - @BeforeClass(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - client = clientBuilder.build(); - createDatabase(client, PRE_EXISTING_DATABASE_ID); - createContainerInDB(client, PRE_EXISTING_CONTAINER_ID, PRE_EXISTING_DATABASE_ID); - } - - @AfterClass(groups = { "cosmosv3" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeDeleteDatabase(client, PRE_EXISTING_DATABASE_ID); - safeClose(client); - } -} diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseCrudTest.java deleted file mode 100644 index 68eccbdc3492a..0000000000000 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseCrudTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.azure.data.cosmos; - -import com.azure.data.cosmos.rx.FailureValidator; - -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import reactor.core.publisher.Mono; - -public class CosmosDatabaseCrudTest extends CosmosTestSuiteBase { - private final static String PRE_EXISTING_DATABASE_ID = getDatabaseId(CosmosDatabaseCrudTest.class) + "1"; - private final static String DATABASE_ID2 = getDatabaseId(CosmosDatabaseCrudTest.class) + "2"; - - private CosmosClient client; - private CosmosClientBuilder clientBuilder; - - @Factory(dataProvider = "clientBuilders") - public CosmosDatabaseCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void createDatabase() throws Exception { - CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings(DATABASE_ID2); - - // create the database - Mono createMono = client.createDatabase(databaseSettings); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(databaseSettings.id()).build(); - validateSuccess(createMono , validator); - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void createDatabase_AlreadyExists() throws Exception { - CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings(DATABASE_ID2); - - client.createDatabase(databaseSettings).block(); - - // attempt to create the database again - Mono createMono = client.createDatabase(databaseSettings); - - // validate - FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); - validateFailure(createMono, validator); - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void readDatabase() throws Exception { - // read database - Mono readMono = client.getDatabase(PRE_EXISTING_DATABASE_ID).read(); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(PRE_EXISTING_DATABASE_ID).build(); - validateSuccess(readMono, validator); - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void readDatabase_DoesntExist() throws Exception { - // read database - Mono readMono = client.getDatabase("I dont exist").read(); - - // validate - FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(readMono, validator); - } - - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void deleteDatabase() throws Exception { - // delete the database - Mono deleteMono = client.getDatabase(PRE_EXISTING_DATABASE_ID).delete(); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .nullResource().build(); - validateSuccess(deleteMono, validator); -// //TODO validate after deletion the resource is actually deleted (not found) - } - - @Test(groups = { "cosmosv3" }, timeOut = TIMEOUT) - public void deleteDatabase_DoesntExist() throws Exception { - // delete the database - Mono deleteMono = client - .getDatabase("I don't exist").delete(); - - // validate - FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); - validateFailure(deleteMono, validator); - - } - - @BeforeClass(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - client = clientBuilder.build(); - } - - @AfterClass(groups = { "cosmosv3" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeClose(client); - } - - @AfterMethod(groups = { "cosmosv3" }, timeOut = SHUTDOWN_TIMEOUT) - public void afterMethod() { - safeDeleteDatabase(client, PRE_EXISTING_DATABASE_ID); - safeDeleteDatabase(client, DATABASE_ID2); - } - - @BeforeMethod(groups = { "cosmosv3" }, timeOut = SETUP_TIMEOUT) - public void beforeMethod() { - createDatabase(client, PRE_EXISTING_DATABASE_ID); - } -} diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java index c6b67cb5d6589..27628ef747527 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java @@ -27,7 +27,6 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosItemCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosItemCrudTest.java deleted file mode 100644 index 2cfb6bc8e3854..0000000000000 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosItemCrudTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.azure.data.cosmos; - -import com.azure.data.cosmos.rx.FailureValidator; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; -import reactor.core.publisher.Mono; - -import java.util.UUID; - -public class CosmosItemCrudTest extends CosmosTestSuiteBase { - private final static String PRE_EXISTING_DATABASE_ID = getDatabaseId(CosmosItemCrudTest.class) + "db1"; - private final static String PRE_EXISTING_CONTAINER_ID = getDatabaseId(CosmosItemCrudTest.class) + "_CONTAINER"; - private final static String DATABASE_ID2 = getDatabaseId(CosmosItemCrudTest.class) + "db2"; - private final static String CONTAINER_ID2 = getDatabaseId(CosmosItemCrudTest.class) + "_CONTAINER_2"; - - private CosmosClient client; - private CosmosClientBuilder clientBuilder; - - @Factory(dataProvider = "clientBuilders") - public CosmosItemCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void testCreateItem() throws Exception { - CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItemProperties itemDefinition = getItemDefinition(); - // create the item - Mono createMono = container.createItem(itemDefinition, "mypk"); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(itemDefinition.id()).build(); - validateSuccess(createMono, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void testCreateItem_AlreadyExists() throws Exception { - CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItemProperties itemDefinition = getItemDefinition(); - // create the item - container.createItem(itemDefinition, itemDefinition.get("mypk")).block(); - - // try creating the same item again - Mono createMono = container.createItem(itemDefinition, itemDefinition.get("mypk")); - - // validate - FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); - validateFailure(createMono, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void testReadItem() throws Exception { - // read item - CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItemProperties itemDefinition = getItemDefinition(); - // create the item - CosmosItem item = container.createItem(itemDefinition, "mypk").block().item(); - Mono readMono = item.read(); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(itemDefinition.id()).build(); - validateSuccess(readMono, validator); - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void testDeleteItem() throws Exception { - CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItemProperties itemDefinition = getItemDefinition(); - // create the item - CosmosItem item = container.createItem(itemDefinition, "mypk").block().item(); - Mono deleteMono = item.delete(); - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .nullResource().build(); - validateSuccess(deleteMono, validator); - //TODO validate after deletion the resource is actually deleted (not found) - } - - @Test(groups = { "simple" }, timeOut = TIMEOUT) - public void testreplaceItem() throws Exception { - CosmosContainer container = client.getDatabase(PRE_EXISTING_DATABASE_ID).getContainer(PRE_EXISTING_CONTAINER_ID); - CosmosItemProperties itemDefinition = getItemDefinition(); - // create the item - CosmosItem item = container.createItem(itemDefinition, "mypk").block().item(); - - String newPropValue = UUID.randomUUID().toString(); - itemDefinition.set("newProp", newPropValue); - - // replace document - Mono readMono = item.replace(itemDefinition); - - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withProperty("newProp", newPropValue).build(); - validateSuccess(readMono, validator); - } - - @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) - public void beforeClass() { - client = clientBuilder.build(); - createDatabase(client, PRE_EXISTING_DATABASE_ID); - createContainerInDB(client, PRE_EXISTING_CONTAINER_ID, PRE_EXISTING_DATABASE_ID); - } - - @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) - public void afterClass() { - safeDeleteDatabase(client, PRE_EXISTING_DATABASE_ID); - safeClose(client); - } - - private CosmosItemProperties getItemDefinition() { - String uuid = UUID.randomUUID().toString(); - return new CosmosItemProperties(String.format("{ " - + "\"id\": \"%s\", " - + "\"mypk\": \"%s\", " - + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" - + "}" - , uuid, "mypk")); - } -} diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java index 0d8578e6527ae..0c496ab37d9b6 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java @@ -22,48 +22,46 @@ */ package com.azure.data.cosmos; -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.io.IOUtils; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.HttpClientFactory; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.Paths; import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.rx.FeedResponseListValidator; import com.azure.data.cosmos.rx.TestConfigurations; import com.azure.data.cosmos.rx.TestSuiteBase; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.HttpClientFactory; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; - import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import io.reactivex.netty.protocol.http.client.HttpClientRequest; +import org.apache.commons.io.IOUtils; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import rx.Observable; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + public class CosmosPartitionKeyTests extends TestSuiteBase { private final static String NON_PARTITIONED_CONTAINER_ID = "NonPartitionContainer" + UUID.randomUUID().toString(); @@ -237,10 +235,10 @@ public void testNonPartitionedCollectionOperations() throws Exception { " 'body':'" + " function() {" + " var client = getContext().getCollection();" + - " var doc = client.createDocument(client.selfLink(), { \\'id\\': \\'" + documentCreatedBySprocId + "\\'}, {}, function(err, docCreated, options) { " + + " var doc = client.createDocument(client.getSelfLink(), { \\'id\\': \\'" + documentCreatedBySprocId + "\\'}, {}, function(err, docCreated, options) { " + " if(err) throw new Error(\\'Error while creating document: \\' + err.message);" + " else {" + - " getContext().getResponse().body(1);" + + " getContext().getResponse().setBody(1);" + " }" + " });" + "}'" + diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosTestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosTestSuiteBase.java deleted file mode 100644 index 8ef6db8816829..0000000000000 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosTestSuiteBase.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.azure.data.cosmos; - -import com.azure.data.cosmos.rx.FailureValidator; -import com.azure.data.cosmos.rx.TestConfigurations; -import com.azure.data.cosmos.internal.RxDocumentClientImpl; -import io.reactivex.subscribers.TestSubscriber; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.DataProvider; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.util.ArrayList; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import static org.assertj.core.api.Assertions.assertThat; - -public class CosmosTestSuiteBase { - - protected static final int TIMEOUT = 8000; - protected static final int SETUP_TIMEOUT = 30000; - protected static final int SHUTDOWN_TIMEOUT = 12000; - protected static final int SUITE_SETUP_TIMEOUT = 120000; - private static final Logger logger = LoggerFactory.getLogger(RxDocumentClientImpl.class); - - protected int subscriberValidationTimeout = TIMEOUT; - - public static String getDatabaseId(Class klass) { - return String.format("java.rx.%s", klass.getName()); - } - - public void validateSuccess(Mono single, - CosmosResponseValidator validator) throws InterruptedException { - validateSuccess(single.flux(), validator, subscriberValidationTimeout); - } - - public static void validateSuccess(Flux flowable, - CosmosResponseValidator validator, long timeout) throws InterruptedException { - - TestSubscriber testSubscriber = new TestSubscriber<>(); - - flowable.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNoErrors(); - testSubscriber.assertComplete(); - testSubscriber.assertValueCount(1); - validator.validate( testSubscriber.values().get(0)); - } - - public void validateFailure(Mono mono, - FailureValidator validator) throws InterruptedException { - validateFailure(mono.flux(), validator, subscriberValidationTimeout); - } - - public static void validateFailure(Flux flowable, - FailureValidator validator, long timeout) throws InterruptedException { - - TestSubscriber testSubscriber = new TestSubscriber<>(); - - flowable.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotComplete(); - testSubscriber.assertTerminated(); - assertThat(testSubscriber.errors()).hasSize(1); - validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); - } - - @DataProvider - public static Object[][] clientBuilders() { - return new Object[][] { { createGatewayRxCosmosClient() } }; - } - - static protected CosmosClientBuilder createGatewayRxCosmosClient() { - ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - connectionPolicy.connectionMode(ConnectionMode.GATEWAY); - RetryOptions options = new RetryOptions(); - options.maxRetryWaitTimeInSeconds(SUITE_SETUP_TIMEOUT); - connectionPolicy.retryOptions(options); - - return CosmosClient.builder().connectionPolicy(connectionPolicy) - .endpoint(TestConfigurations.HOST) - .key(TestConfigurations.MASTER_KEY) - .consistencyLevel(ConsistencyLevel.SESSION); - } - - static protected CosmosDatabase safeCreateDatabase(CosmosClient client, CosmosDatabaseSettings databaseSettings) { - safeDeleteDatabase(client, databaseSettings.id()); - return createDatabase(client, databaseSettings); - } - - static protected CosmosDatabase createDatabase(CosmosClient client, String databaseId) { - Mono databaseSingle = client.createDatabase(databaseId); - return databaseSingle.block().database(); - } - - static protected CosmosContainer createContainerInDB(CosmosClient client, String containerID, String databaseId) { - CosmosDatabase cosmosDatabaseProxy = client.getDatabase(databaseId); - Mono containerSingle = cosmosDatabaseProxy.createContainer(containerID, "/mypk"); - return containerSingle.block().container(); - } - - static private CosmosDatabase createDatabase(CosmosClient client, CosmosDatabaseSettings databaseSettings) { - Mono databaseSingle = client.createDatabase(databaseSettings, - new CosmosDatabaseRequestOptions()); - return databaseSingle.block().database(); - } - - static protected void safeDeleteDatabase(CosmosClient client, String databaseId) { - CosmosDatabase database = client.getDatabase(databaseId); - if (client != null) { - try { - database.delete().block(); - } catch (Exception e) { - } - } - } - - static protected void safeDeleteContainer(CosmosClient client, String containerId, String databaseId) { - CosmosContainer container = client.getDatabase(databaseId).getContainer(containerId); - if (client != null) { - try { - container.delete().block(); - } catch (Exception e) { - } - } - } - - static protected CosmosContainerSettings getContainerSettings() { - PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); - ArrayList paths = new ArrayList<>(); - paths.add("/mypk"); - partitionKeyDef.paths(paths); - - CosmosContainerSettings settings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); - return settings; - } - - static protected void safeClose(CosmosClient client) { - if (client != null) { - try { - client.close(); - } catch (Exception e) { - logger.error("Error: ", e); - } - } - } -} diff --git a/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java b/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java new file mode 100644 index 0000000000000..054bbcf8595a6 --- /dev/null +++ b/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java @@ -0,0 +1,73 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.azure.data.cosmos; + +import com.google.common.base.Strings; +import org.testng.ITest; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; + +import java.lang.reflect.Method; + +public abstract class DocumentClientTest implements ITest { + + private final AsyncDocumentClient.Builder clientBuilder; + private String testName; + + public DocumentClientTest() { + this(new AsyncDocumentClient.Builder()); + } + + public DocumentClientTest(AsyncDocumentClient.Builder clientBuilder) { + this.clientBuilder = clientBuilder; + } + + public final AsyncDocumentClient.Builder clientBuilder() { + return this.clientBuilder; + } + + @Override + public final String getTestName() { + return this.testName; + } + + @BeforeMethod(alwaysRun = true) + public final void setTestName(Method method) { + + String connectionMode = this.clientBuilder.getConnectionPolicy().connectionMode() == ConnectionMode.DIRECT + ? "Direct " + this.clientBuilder.getConfigs().getProtocol() + : "Gateway"; + + this.testName = Strings.lenientFormat("%s::%s[%s with %s consistency]", + method.getDeclaringClass().getSimpleName(), + method.getName(), + connectionMode, + clientBuilder.getDesiredConsistencyLevel()); + } + + @AfterMethod(alwaysRun = true) + public final void unsetTestName() { + this.testName = null; + } +} diff --git a/sdk/src/test/java/com/azure/data/cosmos/SpyClientBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/SpyClientBuilder.java index 4c4f11b107dae..a463f8832964b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/SpyClientBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/SpyClientBuilder.java @@ -22,7 +22,6 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; public class SpyClientBuilder extends AsyncDocumentClient.Builder { diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java index 8de8df0a2b3d2..73b0f2fd62d24 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java @@ -23,16 +23,16 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.rx.TestConfigurations; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.RxDocumentClientImpl; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.rx.TestConfigurations; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java index 3b11d51f6206c..f71caa3df9f24 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; @@ -35,17 +36,16 @@ import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.StoredProcedure; import com.azure.data.cosmos.StoredProcedureResponse; +import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; +import com.azure.data.cosmos.internal.TestSuiteBase; import com.azure.data.cosmos.rx.DocumentServiceRequestValidator; import com.azure.data.cosmos.rx.FeedResponseListValidator; import com.azure.data.cosmos.rx.ResourceResponseValidator; import com.azure.data.cosmos.rx.TestConfigurations; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; -import com.azure.data.cosmos.internal.TestSuiteBase; import org.mockito.stubbing.Answer; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -103,7 +103,7 @@ static Builder createDCBuilder(Protocol protocol) { @Factory(dataProvider = "directClientBuilder") public DCDocumentCrudTest(Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "direct" }, timeOut = TIMEOUT) @@ -167,7 +167,7 @@ public void read() throws Exception { Document document = client.createDocument(getCollectionLink(), docDefinition, null, false).toBlocking().single().getResource(); // give times to replicas to catch up after a write - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); String pkValue = document.getString(PARTITION_KEY_FIELD_NAME); @@ -201,7 +201,7 @@ public void upsert() throws Exception { .getResource(); // give times to replicas to catch up after a write - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); String pkValue = document.getString(PARTITION_KEY_FIELD_NAME); RequestOptions options = new RequestOptions(); @@ -223,7 +223,7 @@ public void upsert() throws Exception { public void crossPartitionQuery() { truncateCollection(createdCollection); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); client.getCapturedRequests().clear(); @@ -236,7 +236,7 @@ public void crossPartitionQuery() { documentList = bulkInsert(client, getCollectionLink(), documentList).map(ResourceResponse::getResource).toList().toBlocking().single(); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); @@ -248,18 +248,10 @@ public void crossPartitionQuery() { .totalSize(documentList.size()) .exactlyContainsInAnyOrder(documentList.stream().map(Document::resourceId).collect(Collectors.toList())).build(); - try { - validateQuerySuccess(results, validator, QUERY_TIMEOUT); - validateNoDocumentQueryOperationThroughGateway(); - // validates only the first query for fetching query plan goes to gateway. - assertThat(client.getCapturedRequests().stream().filter(r -> r.getResourceType() == ResourceType.Document)).hasSize(1); - } catch (Throwable error) { - if (clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - } + validateQuerySuccess(results, validator, QUERY_TIMEOUT); + validateNoDocumentQueryOperationThroughGateway(); + // validates only the first query for fetching query plan goes to gateway. + assertThat(client.getCapturedRequests().stream().filter(r -> r.getResourceType() == ResourceType.Document)).hasSize(1); } private void validateNoStoredProcExecutionOperationThroughGateway() { @@ -318,7 +310,7 @@ public void beforeClass() { options.setOfferThroughput(10100); createdDatabase = SHARED_DATABASE; createdCollection = createCollection(createdDatabase.id(), getCollectionDefinition(), options); - client = SpyClientUnderTestFactory.createClientWithGatewaySpy(clientBuilder); + client = SpyClientUnderTestFactory.createClientWithGatewaySpy(clientBuilder()); assertThat(client.getCapturedRequests()).isNotEmpty(); } @@ -330,7 +322,6 @@ public void afterClass() { @BeforeMethod(groups = { "direct" }) public void beforeMethod(Method method) { - super.beforeMethod(method); client.getCapturedRequests().clear(); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java index b3962d3e10d72..35e6df8a426f4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java @@ -22,26 +22,26 @@ */ package com.azure.data.cosmos.directconnectivity; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; import com.azure.data.cosmos.ConfigsBuilder; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; -import com.azure.data.cosmos.rx.TestConfigurations; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpClientFactory; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentClientImpl; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.TestSuiteBase; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.rx.TestConfigurations; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import org.mockito.Matchers; @@ -77,7 +77,7 @@ public class GatewayAddressCacheTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public GatewayAddressCacheTest(Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @DataProvider(name = "targetPartitionsKeyRangeListAndCollectionLinkParams") @@ -821,7 +821,7 @@ public static void validateSuccess(Single> observable, @BeforeClass(groups = { "direct" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = SHARED_DATABASE; RequestOptions options = new RequestOptions(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java index 445edc273f271..910f373f6c40d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java @@ -23,32 +23,16 @@ package com.azure.data.cosmos.directconnectivity; -import static org.assertj.core.api.Assertions.assertThat; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.io.IOUtils; -import org.mockito.Matchers; -import org.mockito.Mockito; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.DatabaseAccount; import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; -import com.azure.data.cosmos.rx.TestConfigurations; -import com.azure.data.cosmos.internal.TestSuiteBase; import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; import com.azure.data.cosmos.internal.SpyClientUnderTestFactory.ClientUnderTest; - +import com.azure.data.cosmos.internal.TestSuiteBase; +import com.azure.data.cosmos.rx.TestConfigurations; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufUtil; @@ -62,10 +46,24 @@ import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import org.apache.commons.io.IOUtils; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import rx.Observable; import rx.Single; import rx.observers.TestSubscriber; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.net.URI; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + public class GatewayServiceConfigurationReaderTest extends TestSuiteBase { private static final int TIMEOUT = 8000; @@ -81,15 +79,15 @@ public class GatewayServiceConfigurationReaderTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public GatewayServiceConfigurationReaderTest(Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @BeforeClass(groups = "simple") public void setup() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); mockHttpClient = (CompositeHttpClient) Mockito.mock(CompositeHttpClient.class); - ClientUnderTest clientUnderTest = SpyClientUnderTestFactory.createClientUnderTest(this.clientBuilder); + ClientUnderTest clientUnderTest = SpyClientUnderTestFactory.createClientUnderTest(this.clientBuilder()); httpClient = clientUnderTest.getSpyHttpClient(); baseAuthorizationTokenProvider = new BaseAuthorizationTokenProvider(TestConfigurations.MASTER_KEY); connectionPolicy = ConnectionPolicy.defaultPolicy(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java index 61910b16193a3..67960aeebf1b6 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; @@ -34,7 +35,6 @@ import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.User; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.rx.ResourceResponseValidator; import com.azure.data.cosmos.rx.TestConfigurations; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java index 80edae86fa7a8..24ba11254e8aa 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java @@ -23,7 +23,17 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.rx.FailureValidator; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java index 9433155abbf6b..7eef6c9b585a4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java @@ -26,6 +26,7 @@ import com.azure.data.cosmos.AccessCondition; import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; @@ -43,7 +44,6 @@ import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.azure.data.cosmos.internal.routing.Range; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.rx.ResourceResponseValidator; import com.azure.data.cosmos.rx.TestConfigurations; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java index 869c24c02f64d..92ba4e0726830 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java @@ -22,35 +22,34 @@ */ package com.azure.data.cosmos.internal; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; import com.azure.data.cosmos.SpyClientBuilder; import com.azure.data.cosmos.rx.Utils; - import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.HttpClientRequest; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import rx.Observable; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + public class DocumentQuerySpyWireContentTest extends TestSuiteBase { + private Database createdDatabase; private DocumentCollection createdSinglePartitionCollection; private DocumentCollection createdMultiPartitionCollection; @@ -70,7 +69,7 @@ public String getMultiPartitionCollectionLink() { @Factory(dataProvider = "clientBuilders") public DocumentQuerySpyWireContentTest(Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @DataProvider(name = "responseContinuationTokenLimitParamProvider") @@ -160,7 +159,9 @@ public Document createDocument(AsyncDocumentClient client, String collectionLink @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = new SpyClientBuilder(clientBuilder).build(); + + client = new SpyClientBuilder(this.clientBuilder()).build(); + createdDatabase = SHARED_DATABASE; createdSinglePartitionCollection = SHARED_SINGLE_PARTITION_COLLECTION; truncateCollection(SHARED_SINGLE_PARTITION_COLLECTION); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java index 3ae77fac0f85f..3359891e1794e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.rx.FailureValidator; import org.mockito.Mockito; import org.testng.annotations.AfterClass; @@ -45,7 +45,7 @@ public class NetworkFailureTest extends TestSuiteBase { @Factory(dataProvider = "simpleClientBuildersWithDirect") public NetworkFailureTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); this.collectionDefinition = getCollectionDefinition(); } @@ -54,7 +54,7 @@ public void createCollectionWithUnreachableHost() { SpyClientUnderTestFactory.ClientWithGatewaySpy client = null; try { - client = SpyClientUnderTestFactory.createClientWithGatewaySpy(clientBuilder); + client = SpyClientUnderTestFactory.createClientWithGatewaySpy(clientBuilder()); Database database = SHARED_DATABASE; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java index c59ab2195c325..67df79c0b960f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java @@ -23,11 +23,16 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.Error; -import com.google.common.collect.ImmutableMap; +import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.rx.ResourceResponseValidator; +import com.google.common.collect.ImmutableMap; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -56,7 +61,7 @@ public class RetryCreateDocumentTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public RetryCreateDocumentTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -176,14 +181,13 @@ public Observable answer(InvocationOnMock invocation) @BeforeMethod(groups = { "simple" }) public void beforeMethod(Method method) { - super.beforeMethod(method); Mockito.reset(client.getSpyGatewayStoreModel()); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { // set up the client - client = SpyClientUnderTestFactory.createClientWithGatewaySpy(clientBuilder); + client = SpyClientUnderTestFactory.createClientWithGatewaySpy(clientBuilder()); database = SHARED_DATABASE; collection = SHARED_SINGLE_PARTITION_COLLECTION; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java index 38b4a8fd1ead5..6791bd423ea15 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java @@ -23,36 +23,34 @@ package com.azure.data.cosmos.internal; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doAnswer; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; - -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.RetryOptions; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.rx.ResourceResponseValidator; import com.azure.data.cosmos.rx.TestConfigurations; - +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; import rx.Observable; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doAnswer; + public class RetryThrottleTest extends TestSuiteBase { private final static int TIMEOUT = 10000; private final static int TOTAL_DOCS = 500; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java index 61b458a0095b2..bbad58300e595 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java @@ -26,7 +26,6 @@ import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.ISessionContainer; - import io.netty.buffer.ByteBuf; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java index af911c74c10b5..782c5f4b6fb2f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; @@ -29,12 +30,9 @@ import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.AsyncDocumentClient; - import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.protocol.http.client.HttpClientRequest; - import org.apache.commons.lang3.StringUtils; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -67,7 +65,7 @@ public class SessionTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirectSession") public SessionTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); this.subscriberValidationTimeout = TIMEOUT; } @@ -95,13 +93,13 @@ public void beforeClass() { createdCollection = createCollection(createGatewayHouseKeepingDocumentClient().build(), createdDatabase.id(), collection, null); - houseKeepingClient = clientBuilder.build(); + houseKeepingClient = clientBuilder().build(); connectionMode = houseKeepingClient.getConnectionPolicy().connectionMode(); if (connectionMode == ConnectionMode.DIRECT) { - spyClient = SpyClientUnderTestFactory.createDirectHttpsClientUnderTest(clientBuilder); + spyClient = SpyClientUnderTestFactory.createDirectHttpsClientUnderTest(clientBuilder()); } else { - spyClient = SpyClientUnderTestFactory.createClientUnderTest(clientBuilder); + spyClient = SpyClientUnderTestFactory.createClientUnderTest(clientBuilder()); } options = new RequestOptions(); options.setPartitionKey(PartitionKey.None); @@ -117,7 +115,6 @@ public void afterClass() { @BeforeMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeTest(Method method) { - super.beforeMethod(method); spyClient.clearCapturedRequests(); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java index a1e6b617966a4..49bc7dbc3b4e7 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java @@ -22,14 +22,14 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.directconnectivity.ReflectionUtils; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.SpyClientBuilder; - +import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.directconnectivity.ReflectionUtils; import io.netty.buffer.ByteBuf; import io.reactivex.netty.client.RxClient; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; @@ -50,6 +50,7 @@ import java.util.stream.Collectors; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; public class SpyClientUnderTestFactory { @@ -62,6 +63,12 @@ public SpyBaseClass(URI serviceEndpoint, String masterKeyOrResourceToken, Connec public abstract List getCapturedRequests(); public abstract void clearCapturedRequests(); + + static Configs createConfigsSpy(final Protocol protocol) { + final Configs configs = spy(new Configs()); + doAnswer((Answer)invocation -> protocol).when(configs).getProtocol(); + return configs; + } } public static class ClientWithGatewaySpy extends SpyBaseClass { @@ -97,7 +104,7 @@ RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, globalEndpointManager, rxClient); this.requests = Collections.synchronizedList(new ArrayList<>()); - this.spyRxGatewayStoreModel = Mockito.spy(this.origRxGatewayStoreModel); + this.spyRxGatewayStoreModel = spy(this.origRxGatewayStoreModel); this.initRequestCapture(); return this.spyRxGatewayStoreModel; } @@ -196,12 +203,14 @@ public static class DirectHttpsClientUnderTest extends SpyBaseClass, Future>>()); DirectHttpsClientUnderTest(URI serviceEndpoint, String masterKey, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel) { - // TODO: DANOBLE: ensure the configs instance instantiated here specifies Protocol.HTTPS - super(serviceEndpoint, masterKey, connectionPolicy, consistencyLevel, new Configs()); + + super(serviceEndpoint, masterKey, connectionPolicy, consistencyLevel, createConfigsSpy(Protocol.HTTPS)); assert connectionPolicy.connectionMode() == ConnectionMode.DIRECT; init(); + this.origHttpClient = ReflectionUtils.getDirectHttpsHttpClient(this); - this.spyHttpClient = Mockito.spy(this.origHttpClient); + this.spyHttpClient = spy(this.origHttpClient); + ReflectionUtils.setDirectHttpsHttpClient(this, this.spyHttpClient); this.initRequestCapture(this.spyHttpClient); } @@ -290,7 +299,7 @@ RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, GlobalEndpointManager globalEndpointManager, CompositeHttpClient rxClient) { - CompositeHttpClient spyClient = Mockito.spy(rxClient); + CompositeHttpClient spyClient = spy(rxClient); this.origHttpClient = rxClient; this.spyHttpClient = spyClient; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java b/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java index 386166ea381f7..9246efbc69c7f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java @@ -22,11 +22,11 @@ */ package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.AsyncDocumentClient; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -44,7 +44,7 @@ public class StoreHeaderTests extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public StoreHeaderTests(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -56,7 +56,7 @@ public void validateStoreHeader() { Document docDefinition2 = getDocumentDefinition(); RequestOptions requestOptions = new RequestOptions(); - requestOptions.setHeader("x-ms-exclude-system-item", "true"); + requestOptions.setHeader("x-ms-exclude-system-properties", "true"); Document responseDoc2 = createDocument(client, createdDatabase.id(), createdCollection.id(), docDefinition2, requestOptions); Assert.assertNull(responseDoc2.selfLink()); Assert.assertNull(responseDoc2.get("_attachments")); @@ -64,7 +64,7 @@ public void validateStoreHeader() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = SHARED_DATABASE; createdCollection = SHARED_MULTI_PARTITION_COLLECTION; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index 8234891696a5c..ede3556635cff 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -22,50 +22,71 @@ */ package com.azure.data.cosmos.internal; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.spy; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.CompositePath; +import com.azure.data.cosmos.CompositePathSortOrder; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.DataType; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.DocumentClientTest; +import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.IncludedPath; +import com.azure.data.cosmos.Index; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.RetryOptions; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.User; +import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.rx.FeedResponseListValidator; +import com.azure.data.cosmos.rx.ResourceResponseValidator; +import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.rx.Utils; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; -import com.azure.data.cosmos.directconnectivity.Protocol; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.DataProvider; - -import com.azure.data.cosmos.AsyncDocumentClient.Builder; -import com.azure.data.cosmos.rx.FailureValidator; -import com.azure.data.cosmos.rx.FeedResponseListValidator; -import com.azure.data.cosmos.rx.ResourceResponseValidator; -import com.azure.data.cosmos.rx.TestConfigurations; -import com.azure.data.cosmos.rx.Utils; - -import org.testng.annotations.Test; import rx.Observable; import rx.observers.TestSubscriber; -public class TestSuiteBase { +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; + +public class TestSuiteBase extends DocumentClientTest { + private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; private static final ObjectMapper objectMapper = new ObjectMapper(); protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); @@ -85,13 +106,15 @@ public class TestSuiteBase { private static final ImmutableList protocols; protected int subscriberValidationTimeout = TIMEOUT; - protected Builder clientBuilder; - protected static Database SHARED_DATABASE; protected static DocumentCollection SHARED_MULTI_PARTITION_COLLECTION; protected static DocumentCollection SHARED_SINGLE_PARTITION_COLLECTION; protected static DocumentCollection SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES; + private static ImmutableList immutableListOrNull(List list) { + return list != null ? ImmutableList.copyOf(list) : null; + } + static { accountConsistency = parseConsistency(TestConfigurations.CONSISTENCY); desiredConsistencies = immutableListOrNull( @@ -102,7 +125,14 @@ public class TestSuiteBase { ImmutableList.of(Protocol.HTTPS, Protocol.TCP)); } + private String testName; + protected TestSuiteBase() { + this(new AsyncDocumentClient.Builder()); + } + + protected TestSuiteBase(AsyncDocumentClient.Builder clientBuilder) { + super(clientBuilder); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); @@ -110,29 +140,6 @@ protected TestSuiteBase() { logger.debug("Initializing {} ...", this.getClass().getSimpleName()); } - private static ImmutableList immutableListOrNull(List list) { - return list != null ? ImmutableList.copyOf(list) : null; - } - - @BeforeMethod(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}) - public void beforeMethod(Method method) { - if (this.clientBuilder != null) { - logger.info("Starting {}::{} using {} {} mode with {} consistency", - method.getDeclaringClass().getSimpleName(), method.getName(), - this.clientBuilder.getConnectionPolicy().connectionMode(), - this.clientBuilder.getConfigs().getProtocol(), - this.clientBuilder.getDesiredConsistencyLevel()); - return; - } - logger.info("Starting {}::{}", method.getDeclaringClass().getSimpleName(), method.getName()); - } - - @AfterMethod(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}) - public void afterMethod(Method m) { - Test t = m.getAnnotation(Test.class); - logger.info("Finished {}:{}.", m.getDeclaringClass().getSimpleName(), m.getName()); - } - private static class DatabaseManagerImpl implements DatabaseForTest.DatabaseManager { public static DatabaseManagerImpl getInstance(AsyncDocumentClient client) { return new DatabaseManagerImpl(client); @@ -773,7 +780,7 @@ public static Object[][] clientBuildersWithSessionConsistency() { private static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { for (ConsistencyLevel consistencyLevel : ConsistencyLevel.values()) { - if (consistencyLevel.name().toLowerCase().equals(consistency.toLowerCase())) { + if (consistencyLevel.toString().toLowerCase().equals(consistency.toLowerCase())) { return consistencyLevel; } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java index a51126ca66e45..4ceb3c95315c6 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java @@ -24,20 +24,20 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.internal.GlobalEndpointManager; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.caches.RxCollectionCache; -import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.directconnectivity.GatewayAddressCache; import com.azure.data.cosmos.directconnectivity.GatewayServiceConfigurationReader; import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.GlobalEndpointManager; +import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.ResourceType; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java index 1fc211630cdcb..e46f5a3a6f8e3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java @@ -23,13 +23,13 @@ package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.internal.RxDocumentClientImpl; import com.azure.data.cosmos.directconnectivity.HttpTransportClient; import com.azure.data.cosmos.directconnectivity.ServerStoreModel; import com.azure.data.cosmos.directconnectivity.StoreClient; import com.azure.data.cosmos.directconnectivity.TransportClient; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.RxDocumentClientImpl; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import org.apache.commons.lang3.reflect.FieldUtils; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java index 65195bcaaeefb..692a9942c3688 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java @@ -22,23 +22,27 @@ */ package com.azure.data.cosmos.internal.query; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.Document; import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.internal.GlobalEndpointManager; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IRetryPolicyFactory; import com.azure.data.cosmos.internal.RetryPolicy; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; +import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; +import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import com.azure.data.cosmos.internal.routing.Range; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedListMultimap; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; -import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; -import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.internal.routing.Range; import org.apache.commons.lang3.RandomUtils; import org.mockito.Matchers; import org.mockito.Mockito; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java index d136b62fcd48c..22112ff6e8206 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos.internal.query; -import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import java.util.Arrays; import java.util.HashMap; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java index 84574f9261f54..e074fb4cc55d1 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java @@ -23,28 +23,26 @@ package com.azure.data.cosmos.internal.query; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedOptionsBase; import com.azure.data.cosmos.FeedResponse; - +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; import rx.Observable; import rx.functions.Func1; import rx.functions.Func2; import rx.observers.TestSubscriber; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + public class FetcherTest { @DataProvider(name = "queryParams") diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java index e2894511bdae4..a1edf5d50ee73 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java @@ -22,26 +22,23 @@ */ package com.azure.data.cosmos.rx; -import java.util.ArrayList; -import java.util.UUID; - +import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.directconnectivity.Protocol; - -import reactor.core.publisher.Flux; - import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedResponse; +import java.util.ArrayList; +import java.util.UUID; public class AggregateQueryTests extends TestSuiteBase { @@ -85,7 +82,7 @@ public AggregateConfig(String operator, Object expected, String condition) { @Factory(dataProvider = "clientBuildersWithDirect") public AggregateQueryTests(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @@ -114,16 +111,7 @@ public void queryDocumentsWithAggregates(boolean qmEnabled) throws Exception { .hasValidQueryMetrics(qmEnabled) .build(); - try { - validateQuerySuccess(queryObservable, validator); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable, validator); } } @@ -222,13 +210,13 @@ public void afterClass() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT * 100) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = this.clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); bulkInsert(); generateTestConfigs(); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(this.clientBuilder()); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java index ec3dc6f9038dd..f0b01803cd9e0 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java @@ -22,7 +22,15 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.ClientUnderTestBuilder; +import com.azure.data.cosmos.CosmosBridgeInternal; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.DataType; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; @@ -30,21 +38,17 @@ import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.directconnectivity.Protocol; import com.azure.data.cosmos.internal.RxDocumentClientUnderTest; - import io.reactivex.subscribers.TestSubscriber; -import reactor.core.publisher.Flux; -import reactor.core.scheduler.Schedulers; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; import reactor.util.concurrent.Queues; import rx.Observable; @@ -106,7 +110,7 @@ static protected CosmosContainerSettings getCollectionDefinition() { @Factory(dataProvider = "simpleClientBuildersWithDirectHttps") public BackPressureCrossPartitionTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } private void warmUp() { @@ -150,57 +154,39 @@ public void query(String query, int maxItemCount, int maxExpectedBufferedCountFo int i = 0; // use a test subscriber and request for more result and sleep in between - try { - while(subscriber.completions() == 0 && subscriber.errorCount() == 0) { - log.debug("loop " + i); - - TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis); - sleepTimeInMillis /= 2; - - if (sleepTimeInMillis > 4000) { - // validate that only one item is returned to subscriber in each iteration - assertThat(subscriber.valueCount() - i).isEqualTo(1); - } - - log.debug("subscriber.getValueCount(): " + subscriber.valueCount()); - log.debug("client.httpRequests.size(): " + rxClient.httpRequests.size()); - // validate that the difference between the number of requests to backend - // and the number of returned results is always less than a fixed threshold - assertThat(rxClient.httpRequests.size() - subscriber.valueCount()) - .isLessThanOrEqualTo(maxExpectedBufferedCountForBackPressure); - - log.debug("requesting more"); - subscriber.requestMore(1); - i++; - } - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + while (subscriber.completions() == 0 && subscriber.errorCount() == 0) { + log.debug("loop " + i); + + TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis); + sleepTimeInMillis /= 2; - try { - subscriber.assertNoErrors(); - subscriber.assertComplete(); - assertThat(subscriber.values().stream().mapToInt(p -> p.results().size()).sum()).isEqualTo(expectedNumberOfResults); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); + if (sleepTimeInMillis > 4000) { + // validate that only one item is returned to subscriber in each iteration + assertThat(subscriber.valueCount() - i).isEqualTo(1); } - throw error; + + log.debug("subscriber.getValueCount(): " + subscriber.valueCount()); + log.debug("client.httpRequests.size(): " + rxClient.httpRequests.size()); + // validate that the difference between the number of requests to backend + // and the number of returned results is always less than a fixed threshold + assertThat(rxClient.httpRequests.size() - subscriber.valueCount()) + .isLessThanOrEqualTo(maxExpectedBufferedCountForBackPressure); + + log.debug("requesting more"); + subscriber.requestMore(1); + i++; } + + subscriber.assertNoErrors(); + subscriber.assertComplete(); + assertThat(subscriber.values().stream().mapToInt(p -> p.results().size()).sum()).isEqualTo(expectedNumberOfResults); } @BeforeClass(groups = { "long" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); options.offerThroughput(20000); - client = new ClientUnderTestBuilder(clientBuilder).build(); + client = new ClientUnderTestBuilder(clientBuilder()).build(); createdDatabase = getSharedCosmosDatabase(client); createdCollection = createCollection(createdDatabase, getCollectionDefinition(), options); @@ -216,7 +202,7 @@ public void beforeClass() { numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client).readPartitionKeyRanges(getCollectionLink(), null) .flatMap(p -> Observable.from(p.results())).toList().toBlocking().single().size(); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); warmUp(); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java index d6b765d5e5e22..3c80a8d39a8de 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java @@ -22,22 +22,27 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.ClientUnderTestBuilder; +import com.azure.data.cosmos.CosmosBridgeInternal; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.RxDocumentClientUnderTest; - import io.reactivex.subscribers.TestSubscriber; -import reactor.core.publisher.Flux; -import reactor.core.scheduler.Schedulers; - import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; import reactor.util.concurrent.Queues; import java.util.ArrayList; @@ -74,7 +79,7 @@ private static CosmosContainerSettings getSinglePartitionCollectionDefinition() @Factory(dataProvider = "simpleClientBuildersWithDirectHttps") public BackPressureTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "long" }, timeOut = TIMEOUT) @@ -164,7 +169,7 @@ public void beforeClass() throws Exception { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); options.offerThroughput(1000); - client = new ClientUnderTestBuilder(clientBuilder).build(); + client = new ClientUnderTestBuilder(clientBuilder()).build(); createdDatabase = getSharedCosmosDatabase(client); createdCollection = createCollection(createdDatabase, getSinglePartitionCollectionDefinition(), options); @@ -188,7 +193,7 @@ public void beforeClass() throws Exception { createdDocuments = bulkInsertBlocking(createdCollection, docDefList); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); warmUp(); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java index edf677e98b7f7..a8ed82c9b2d58 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java @@ -22,16 +22,6 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.lang.reflect.Method; -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Collection; -import java.time.ZonedDateTime; -import java.util.List; -import java.util.UUID; - import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ChangeFeedOptions; @@ -44,17 +34,24 @@ import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.internal.TestSuiteBase; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimap; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import rx.Observable; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Multimap; +import java.lang.reflect.Method; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.UUID; -import rx.Observable; +import static org.assertj.core.api.Assertions.assertThat; //TODO: change to use external TestSuiteBase public class ChangeFeedTest extends TestSuiteBase { @@ -86,7 +83,7 @@ static protected DocumentCollection getCollectionDefinition() { } public ChangeFeedTest() { - clientBuilder = createGatewayRxDocumentClient(); + super(createGatewayRxDocumentClient()); subscriberValidationTimeout = TIMEOUT; } @@ -104,7 +101,7 @@ public void changeFeed_fromBeginning() throws Exception { .toList().toBlocking().single(); int count = 0; - for(int i = 0; i < changeFeedResultList.size(); i++) { + for (int i = 0; i < changeFeedResultList.size(); i++) { FeedResponse changeFeedPage = changeFeedResultList.get(i); assertThat(changeFeedPage.continuationToken()).as("Response continuation should not be null").isNotNull(); @@ -266,7 +263,7 @@ public void removeCollection() { @BeforeMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void populateDocuments(Method method) { - super.beforeMethod(method); + partitionKeyToDocuments.clear(); RequestOptions options = new RequestOptions(); @@ -291,7 +288,7 @@ public void populateDocuments(Method method) { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { // set up the client - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = SHARED_DATABASE; } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java index bb47411351686..ace4d5c9b7dcd 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java @@ -22,34 +22,44 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.UUID; - -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RetryAnalyzer; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.CompositePathSortOrder; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosContainerResponse; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.CosmosItemResponse; +import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.IndexingMode; import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.RetryAnalyzer; import com.azure.data.cosmos.SpatialSpec; import com.azure.data.cosmos.SpatialType; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Mono; +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + public class CollectionCrudTest extends TestSuiteBase { + private static final int TIMEOUT = 50000; private static final int SETUP_TIMEOUT = 20000; private static final int SHUTDOWN_TIMEOUT = 20000; @@ -60,7 +70,7 @@ public class CollectionCrudTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public CollectionCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); this.subscriberValidationTimeout = TIMEOUT; } @@ -247,8 +257,8 @@ public void replaceCollection(String collectionName) throws InterruptedException @Test(groups = { "emulator" }, timeOut = 10 * TIMEOUT, retryAnalyzer = RetryAnalyzer.class) public void sessionTokenConsistencyCollectionDeleteCreateSameName() { - CosmosClient client1 = clientBuilder.build(); - CosmosClient client2 = clientBuilder.build(); + CosmosClient client1 = clientBuilder().build(); + CosmosClient client2 = clientBuilder().build(); String dbId = CosmosDatabaseForTest.generateId(); String collectionId = "coll"; @@ -310,7 +320,7 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); database = createDatabase(client, databaseId); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java index cac8f90459c41..72244193c26fb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java @@ -22,21 +22,8 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.apache.commons.lang3.StringUtils; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosContainerSettings; import com.azure.data.cosmos.CosmosDatabase; @@ -44,9 +31,20 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; - +import org.apache.commons.lang3.StringUtils; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Flux; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + public class CollectionQueryTest extends TestSuiteBase { private final static int TIMEOUT = 30000; private final String databaseId = CosmosDatabaseForTest.generateId(); @@ -56,7 +54,7 @@ public class CollectionQueryTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public CollectionQueryTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); this.subscriberValidationTimeout = TIMEOUT; } @@ -133,7 +131,7 @@ public void queryCollections_NoResults() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = createDatabase(client, databaseId); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java index 8c1d6dbbff134..dabc68aa942ec 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java @@ -22,20 +22,18 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.CosmosDatabaseResponse; import com.azure.data.cosmos.CosmosDatabaseSettings; import com.azure.data.cosmos.CosmosResponseValidator; -import com.azure.data.cosmos.CosmosDatabaseForTest; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Mono; import java.util.ArrayList; @@ -49,7 +47,7 @@ public class DatabaseCrudTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public DatabaseCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) @@ -131,7 +129,7 @@ public void deleteDatabase_DoesntExist() throws Exception { @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = createDatabase(client, preExistingDatabaseId); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java index 52142bf840670..5c5028ed38a48 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java @@ -22,27 +22,25 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - +import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosDatabaseSettings; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosDatabase; -import com.azure.data.cosmos.CosmosDatabaseSettings; -import com.azure.data.cosmos.CosmosDatabaseForTest; -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; -import reactor.core.publisher.Flux; +import static org.assertj.core.api.Assertions.assertThat; public class DatabaseQueryTest extends TestSuiteBase { @@ -55,7 +53,7 @@ public class DatabaseQueryTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public DatabaseQueryTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -131,7 +129,7 @@ public void queryDatabases_NoResults() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabases.add(createDatabase(client, databaseId1)); createdDatabases.add(createDatabase(client, databaseId2)); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java index ef0c4bb840605..415d28143120a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java @@ -22,8 +22,13 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.directconnectivity.Protocol; +import com.google.common.base.Strings; import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -36,64 +41,66 @@ import static org.assertj.core.api.Assertions.assertThat; public class DocumentClientResourceLeakTest extends TestSuiteBase { + private static final int TIMEOUT = 2400000; private static final int MAX_NUMBER = 1000; - private CosmosClientBuilder clientBuilder; - private CosmosClient client; private CosmosDatabase createdDatabase; private CosmosContainer createdCollection; @Factory(dataProvider = "simpleClientBuildersWithDirect") public DocumentClientResourceLeakTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } - //TODO : FIX tests @Test(groups = {"emulator"}, timeOut = TIMEOUT) public void resourceLeak() throws Exception { - //TODO FIXME DANOBLE this test doesn't pass on RNTBD - if (clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - throw new SkipException("RNTBD"); - } + System.gc(); TimeUnit.SECONDS.sleep(10); long usedMemoryInBytesBefore = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); - for (int i = 0; i < MAX_NUMBER; i++) { - client = clientBuilder.build(); - logger.info("client {}", i); + logger.info("CLIENT {}", i); + CosmosClient client = this.clientBuilder().build(); try { - logger.info("creating doc..."); - createDocument(client.getDatabase(createdDatabase.id()).getContainer(createdCollection.id()), getDocumentDefinition()); + logger.info("creating document"); + createDocument(client.getDatabase(createdDatabase.id()).getContainer(createdCollection.id()), + getDocumentDefinition()); } finally { - logger.info("closing client..."); + logger.info("closing client"); client.close(); } } + System.gc(); TimeUnit.SECONDS.sleep(10); + long usedMemoryInBytesAfter = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); - assertThat(usedMemoryInBytesAfter - usedMemoryInBytesBefore).isLessThan(200 * ONE_MB); + logger.info("Memory delta: {} - {} = {} MB", + usedMemoryInBytesAfter / (double)ONE_MB, + usedMemoryInBytesBefore / (double)ONE_MB, + (usedMemoryInBytesAfter - usedMemoryInBytesBefore) / (double)ONE_MB); + + assertThat(usedMemoryInBytesAfter - usedMemoryInBytesBefore).isLessThan(125 * ONE_MB); } @BeforeClass(groups = {"emulator"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); - createdDatabase = getSharedCosmosDatabase(client); - createdCollection = getSharedMultiPartitionCosmosContainer(client); + CosmosClient client = this.clientBuilder().build(); + try { + createdDatabase = getSharedCosmosDatabase(client); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + } finally { + client.close(); + } } private CosmosItemProperties getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " - + "\"id\": \"%s\", " - + "\"mypk\": \"%s\", " - + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" - + "}" - , uuid, uuid)); - return doc; + return new CosmosItemProperties(Strings.lenientFormat( + "{\"id\":\"%s\",\"mypk\":\"%s\",\"sgmts\":[[6519456,1471916863],[2498434,1455671440]]}", uuid, uuid + )); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java index b926867c74bfc..13d40d36c6c88 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java @@ -22,14 +22,18 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.CosmosItemResponse; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.Document; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.directconnectivity.Protocol; - -import reactor.core.publisher.Mono; - import org.apache.commons.lang3.StringUtils; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -38,6 +42,7 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Mono; import java.time.Duration; import java.time.OffsetDateTime; @@ -55,7 +60,7 @@ public class DocumentCrudTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public DocumentCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @DataProvider(name = "documentCrudArgProvider") @@ -128,7 +133,7 @@ public void readDocumentWithVeryLargePartitionKey(String documentId) throws Inte CosmosItem createdDocument = TestSuiteBase.createDocument(createdCollection, docDefinition); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.partitionKey(new PartitionKey(sb.toString())); @@ -170,7 +175,7 @@ public void readDocument(String documentId) throws InterruptedException { CosmosItemProperties docDefinition = getDocumentDefinition(documentId); CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); @@ -183,13 +188,13 @@ public void readDocument(String documentId) throws InterruptedException { } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") - public void timestamp(String documentId, boolean isNameBased) throws Exception { + public void timestamp(String documentId) throws Exception { OffsetDateTime before = OffsetDateTime.now(); CosmosItemProperties docDefinition = getDocumentDefinition(documentId); Thread.sleep(1000); CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); @@ -211,7 +216,7 @@ public void readDocument_DoesntExist(String documentId) throws InterruptedExcept options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); document.delete(options).block(); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); options.partitionKey(new PartitionKey("looloo")); Mono readObservable = document.read(options); @@ -237,7 +242,7 @@ public void deleteDocument(String documentId) throws InterruptedException { validateSuccess(deleteObservable, validator); // attempt to read document which was deleted - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = document.read(options); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); @@ -246,7 +251,7 @@ public void deleteDocument(String documentId) throws InterruptedException { @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") public void deleteDocument_undefinedPK(String documentId) throws InterruptedException { - Document docDefinition = new Document(); + CosmosItemProperties docDefinition = new CosmosItemProperties(); docDefinition.id(documentId); CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); @@ -260,7 +265,7 @@ public void deleteDocument_undefinedPK(String documentId) throws InterruptedExce validateSuccess(deleteObservable, validator); // attempt to read document which was deleted - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = document.read(options); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); @@ -317,16 +322,8 @@ public void upsertDocument_CreateDocument(String documentId) throws Throwable { // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.id()).build(); - try { - validateSuccess(upsertObservable, validator); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + + validateSuccess(upsertObservable, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT * 100, dataProvider = "documentCrudArgProvider") @@ -346,21 +343,12 @@ public void upsertDocument_ReplaceDocument(String documentId) throws Throwable { // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withProperty("newProp", newPropValue).build(); - try { - validateSuccess(readObservable, validator); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateSuccess(readObservable, validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); } @@ -372,7 +360,7 @@ public void afterClass() { @BeforeMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeMethod() { safeClose(client); - client = clientBuilder.build(); + client = clientBuilder().build(); } private CosmosItemProperties getDocumentDefinition(String documentId) { @@ -385,4 +373,4 @@ private CosmosItemProperties getDocumentDefinition(String documentId) { , documentId, uuid)); return doc; } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java index 5050b5fb36b6c..290526847e061 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.rx; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.util.UUID; - -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.CosmosItemResponse; +import com.azure.data.cosmos.CosmosResponseValidator; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; @@ -40,9 +40,12 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; - import reactor.core.publisher.Mono; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.util.UUID; + import static org.assertj.core.api.Assertions.assertThat; public class LogLevelTest extends TestSuiteBase { @@ -57,12 +60,12 @@ public class LogLevelTest extends TestSuiteBase { private static CosmosClient client; public LogLevelTest() { - this.clientBuilder = createGatewayRxDocumentClient(); + super(createGatewayRxDocumentClient()); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); } @@ -79,7 +82,7 @@ public void createDocumentWithDebugLevel() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); LogManager.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - CosmosClient client = clientBuilder.build(); + CosmosClient client = clientBuilder().build(); try { CosmosItemProperties docDefinition = getDocumentDefinition(); Mono createObservable = createdCollection.createItem(docDefinition, @@ -109,7 +112,7 @@ public void createDocumentWithWarningLevel() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - CosmosClient client = clientBuilder.build(); + CosmosClient client = clientBuilder().build(); try { CosmosItemProperties docDefinition = getDocumentDefinition(); Mono createObservable = createdCollection.createItem(docDefinition, @@ -138,7 +141,7 @@ public void createDocumentWithTraceLevel() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - CosmosClient client = clientBuilder.build(); + CosmosClient client = clientBuilder().build(); try { CosmosItemProperties docDefinition = getDocumentDefinition(); Mono createObservable = createdCollection.createItem(docDefinition, @@ -165,7 +168,7 @@ public void createDocumentWithTraceLevelAtRoot() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - CosmosClient client = clientBuilder.build(); + CosmosClient client = clientBuilder().build(); try { CosmosItemProperties docDefinition = getDocumentDefinition(); Mono createObservable = createdCollection.createItem(docDefinition, @@ -191,7 +194,7 @@ public void createDocumentWithDebugLevelAtRoot() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - CosmosClient client = clientBuilder.build(); + CosmosClient client = clientBuilder().build(); try { CosmosItemProperties docDefinition = getDocumentDefinition(); Mono createObservable = createdCollection.createItem(docDefinition, @@ -220,7 +223,7 @@ public void createDocumentWithErrorClient() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - CosmosClient client = clientBuilder.build(); + CosmosClient client = clientBuilder().build(); try { CosmosItemProperties docDefinition = getDocumentDefinition(); Mono createObservable = createdCollection.createItem(docDefinition, @@ -249,7 +252,7 @@ public void createDocumentWithInfoLevel() throws Exception { WriterAppender appender = new WriterAppender(new PatternLayout(), consoleWriter); Logger.getLogger(NETWORK_LOGGING_CATEGORY).addAppender(appender); - CosmosClient client = clientBuilder.build(); + CosmosClient client = clientBuilder().build(); try { CosmosItemProperties docDefinition = getDocumentDefinition(); Mono createObservable = createdCollection.createItem(docDefinition, @@ -274,7 +277,6 @@ private CosmosItemProperties getDocumentDefinition() { @BeforeMethod(groups = { "simple" }) public void beforeMethod(Method method) { - super.beforeMethod(method); LogManager.resetConfiguration(); PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties")); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java index 10f61efa8da3e..0e9b48f325bd4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java @@ -22,16 +22,25 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.BridgeUtils; +import com.azure.data.cosmos.ConflictResolutionMode; +import com.azure.data.cosmos.ConflictResolutionPolicy; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; - -import reactor.core.publisher.Mono; - +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosContainerResponse; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.internal.Utils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.UUID; @@ -51,7 +60,7 @@ public class MultiMasterConflictResolutionTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public MultiMasterConflictResolutionTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = "multi-master", timeOut = 10 * TIMEOUT) @@ -89,7 +98,7 @@ public void conflictResolutionPolicyCRUD() { // when (e.StatusCode == HttpStatusCode.BadRequest) CosmosClientException dce = Utils.as(e.getCause(), CosmosClientException.class); if (dce != null && dce.statusCode() == 400) { - assertThat(dce.getMessage()).contains("INVALID path '\\/a\\/b' for last writer wins conflict resolution"); + assertThat(dce.getMessage()).contains("Invalid path '\\/a\\/b' for last writer wins conflict resolution"); } else { throw e; } @@ -106,7 +115,7 @@ public void conflictResolutionPolicyCRUD() { // when (e.StatusCode == HttpStatusCode.BadRequest) CosmosClientException dce = Utils.as(e.getCause(), CosmosClientException.class); if (dce != null && dce.statusCode() == 400) { - assertThat(dce.getMessage()).contains("INVALID path 'someText' for last writer wins conflict resolution"); + assertThat(dce.getMessage()).contains("Invalid path 'someText' for last writer wins conflict resolution"); } else { throw e; } @@ -158,7 +167,7 @@ public void invalidConflictResolutionPolicy_LastWriterWinsWithStoredProc() throw FailureValidator validator = new FailureValidator.Builder() .instanceOf(CosmosClientException.class) .statusCode(400) - .errorMessageContains("LAST_WRITER_WINS conflict resolution mode should not have conflict resolution procedure set.") + .errorMessageContains("LastWriterWins conflict resolution mode should not have conflict resolution procedure set.") .build(); validateFailure(createObservable, validator); } @@ -180,7 +189,7 @@ public void invalidConflictResolutionPolicy_CustomWithPath() throws Exception { FailureValidator validator = new FailureValidator.Builder() .instanceOf(CosmosClientException.class) .statusCode(400) - .errorMessageContains("CUSTOM conflict resolution mode should not have conflict resolution path set.") + .errorMessageContains("Custom conflict resolution mode should not have conflict resolution path set.") .build(); validateFailure(createObservable, validator); } @@ -189,7 +198,7 @@ public void invalidConflictResolutionPolicy_CustomWithPath() throws Exception { public void beforeClass() { // set up the client - client = clientBuilder.build(); + client = clientBuilder().build(); database = createDatabase(client, databaseId); partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java index 254f2020bade3..43ca3088fc816 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java @@ -23,6 +23,26 @@ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.CompositePath; +import com.azure.data.cosmos.CompositePathSortOrder; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.collections4.ComparatorUtils; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import reactor.core.publisher.Flux; + import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -32,19 +52,6 @@ import java.util.Random; import java.util.UUID; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.*; -import org.apache.commons.collections4.ComparatorUtils; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.azure.data.cosmos.CosmosClientException; - -import reactor.core.publisher.Flux; - public class MultiOrderByQueryTests extends TestSuiteBase { private static final int TIMEOUT = 35000; @@ -122,7 +129,7 @@ else if (doc1.getBoolean(path) == true && doc2.getBoolean(path) == false) @Factory(dataProvider = "clientBuilders") public MultiOrderByQueryTests(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) @@ -132,7 +139,7 @@ public void afterClass() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); documentCollection = getSharedMultiPartitionCosmosContainerWithCompositeAndSpatialIndexes(client); truncateCollection(documentCollection); @@ -140,7 +147,7 @@ public void beforeClass() throws Exception { Random random = new Random(); for (int i = 0; i < numberOfDocuments; ++i) { - Document multiOrderByDocument = generateMultiOrderByDocument(); + CosmosItemProperties multiOrderByDocument = generateMultiOrderByDocument(); String multiOrderByDocumentString = multiOrderByDocument.toJson(); int numberOfDuplicates = 5; @@ -179,9 +186,9 @@ public void beforeClass() throws Exception { waitIfNeededForReplicasToCatchUp(clientBuilder); } - private Document generateMultiOrderByDocument() { + private CosmosItemProperties generateMultiOrderByDocument() { Random random = new Random(); - Document document = new Document(); + CosmosItemProperties document = new CosmosItemProperties(); document.id(UUID.randomUUID().toString()); document.set(NUMBER_FIELD, random.nextInt(5)); document.set(NUMBER_FIELD_2, random.nextInt(5)); @@ -272,7 +279,7 @@ public void queryDocumentsWithMultiOrder() throws CosmosClientException, Interru // CREATE document with numberField not set. // This query would then be invalid. - Document documentWithEmptyField = generateMultiOrderByDocument(); + CosmosItemProperties documentWithEmptyField = generateMultiOrderByDocument(); documentWithEmptyField.remove(NUMBER_FIELD); documentCollection.createItem(documentWithEmptyField, new CosmosItemRequestOptions()).block(); String query = "SELECT [root." + NUMBER_FIELD + ",root." + STRING_FIELD + "] FROM root ORDER BY root." + NUMBER_FIELD + " ASC ,root." + STRING_FIELD + " DESC"; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java index f0048141f4740..f728a30a75ab4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java @@ -22,20 +22,8 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - import com.azure.data.cosmos.AsyncDocumentClient; -import org.assertj.core.util.Strings; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - +import com.azure.data.cosmos.AsyncDocumentClient.Builder; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.DocumentCollection; @@ -43,11 +31,21 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; import com.azure.data.cosmos.internal.TestSuiteBase; - +import org.assertj.core.util.Strings; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import rx.Observable; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + //TODO: change to use external TestSuiteBase public class OfferQueryTest extends TestSuiteBase { @@ -64,7 +62,7 @@ private String getDatabaseLink() { @Factory(dataProvider = "clientBuilders") public OfferQueryTest(Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) @@ -142,7 +140,7 @@ public void queryCollections_NoResults() throws Exception { @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); Database d1 = new Database(); d1.id(databaseId); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java index eb6daed6b3a13..050bd7af6723e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java @@ -22,23 +22,21 @@ */ package com.azure.data.cosmos.rx; -import java.util.List; - import com.azure.data.cosmos.AsyncDocumentClient; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.Offer; import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.internal.TestSuiteBase; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import rx.Observable; +import java.util.List; + //TODO: change to use external TestSuiteBase public class OfferReadReplaceTest extends TestSuiteBase { @@ -51,7 +49,7 @@ public class OfferReadReplaceTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public OfferReadReplaceTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) @@ -102,7 +100,7 @@ public void readAndReplaceOffer() { @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = createDatabase(client, databaseId); createdCollection = createCollection(client, createdDatabase.id(), getCollectionDefinition()); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java index f096e671e2d5e..2ba3c95a5459c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java @@ -22,7 +22,34 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; +import com.azure.data.cosmos.CosmosBridgeInternal; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.RetryAnalyzer; +import com.azure.data.cosmos.internal.Utils.ValueHolder; +import com.azure.data.cosmos.internal.query.CompositeContinuationToken; +import com.azure.data.cosmos.internal.query.OrderByContinuationToken; +import com.azure.data.cosmos.internal.query.QueryItem; +import com.azure.data.cosmos.internal.routing.Range; +import com.fasterxml.jackson.core.JsonProcessingException; +import io.reactivex.subscribers.TestSubscriber; +import org.apache.commons.lang3.StringUtils; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import reactor.core.publisher.Flux; +import rx.Observable; import java.util.ArrayList; import java.util.Collections; @@ -35,28 +62,7 @@ import java.util.function.Function; import java.util.stream.Collectors; -import com.azure.data.cosmos.*; -import com.azure.data.cosmos.*; -import org.apache.commons.lang3.StringUtils; - -import com.fasterxml.jackson.core.JsonProcessingException; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.query.QueryItem; -import com.azure.data.cosmos.internal.routing.Range; -import com.azure.data.cosmos.internal.Utils.ValueHolder; -import com.azure.data.cosmos.internal.query.CompositeContinuationToken; -import com.azure.data.cosmos.internal.query.OrderByContinuationToken; - -import io.reactivex.subscribers.TestSubscriber; -import reactor.core.publisher.Flux; -import rx.Observable; +import static org.assertj.core.api.Assertions.assertThat; public class OrderbyDocumentQueryTest extends TestSuiteBase { private final double minQueryRequestChargePerPartition = 2.0; @@ -70,7 +76,7 @@ public class OrderbyDocumentQueryTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public OrderbyDocumentQueryTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") @@ -104,17 +110,7 @@ public void queryDocumentsValidateContent(boolean qmEnabled) throws Exception { .hasValidQueryMetrics(qmEnabled) .build(); - try { - validateQuerySuccess(queryObservable, validator); - } catch (Throwable error) { - // TODO: DANOBLE: report this detailed information in all failures produced by TestSuiteBase classes - // work item: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/370015 - String message = String.format("%s %s mode with %s consistency test failure", - this.clientBuilder.getConnectionPolicy().connectionMode(), - this.clientBuilder.getConfigs().getProtocol(), - this.clientBuilder.getDesiredConsistencyLevel()); - throw new AssertionError(message, error); - } + validateQuerySuccess(queryObservable, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -427,7 +423,7 @@ public void beforeMethod() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = getSharedCosmosDatabase(client); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -462,7 +458,7 @@ public void beforeClass() throws Exception { .readPartitionKeyRanges("dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(), null) .flatMap(p -> Observable.from(p.results())).toList().toBlocking().single().size(); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java index 4cfc00a75d5e2..ecc2da547cb94 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java @@ -22,35 +22,37 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.*; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosBridgeInternal; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.directconnectivity.Protocol; - -import org.testng.SkipException; -import org.testng.annotations.DataProvider; -import com.azure.data.cosmos.internal.routing.Range; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.QueryMetrics; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.CompositeContinuationToken; - +import com.azure.data.cosmos.internal.routing.Range; import io.reactivex.subscribers.TestSubscriber; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Flux; import rx.Observable; +import java.util.ArrayList; +import java.util.List; import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; public class ParallelDocumentQueryTest extends TestSuiteBase { private CosmosDatabase createdDatabase; @@ -65,7 +67,7 @@ public String getCollectionLink() { @Factory(dataProvider = "clientBuildersWithDirect") public ParallelDocumentQueryTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @DataProvider(name = "queryMetricsArgProvider") @@ -97,16 +99,7 @@ public void queryDocuments(boolean qmEnabled) { .hasValidQueryMetrics(qmEnabled) .build(); - try { - validateQuerySuccess(queryObservable, validator, TIMEOUT); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format(String.format("DIRECT TCP test failure: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel())); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable, validator, TIMEOUT); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -189,16 +182,7 @@ public void queryDocumentsWithPageSize() { .pageSizeIsLessThanOrEqualTo(pageSize) .build()) .build(); - try { - validateQuerySuccess(queryObservable, validator, 2 * subscriberValidationTimeout); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable, validator, 2 * subscriberValidationTimeout); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -236,26 +220,19 @@ public void crossPartitionQueryNotEnabled() { @Test(groups = { "simple" }, timeOut = 2 * TIMEOUT) public void partitionKeyRangeId() { int sum = 0; - try { - for (String partitionKeyRangeId : CosmosBridgeInternal.getAsyncDocumentClient(client).readPartitionKeyRanges(getCollectionLink(), null) - .flatMap(p -> Observable.from(p.results())) - .map(pkr -> pkr.id()).toList().toBlocking().single()) { - String query = "SELECT * from root"; - FeedOptions options = new FeedOptions(); - options.partitionKeyRangeIdInternal(partitionKeyRangeId); - int queryResultCount = createdCollection.queryItems(query, options) - .flatMap(p -> Flux.fromIterable(p.results())) - .collectList().block().size(); - - sum += queryResultCount; - } - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; + + for (String partitionKeyRangeId : + CosmosBridgeInternal.getAsyncDocumentClient(client).readPartitionKeyRanges(getCollectionLink(), null) + .flatMap(p -> Observable.from(p.results())) + .map(pkr -> pkr.id()).toList().toBlocking().single()) { + String query = "SELECT * from root"; + FeedOptions options = new FeedOptions(); + options.partitionKeyRangeIdInternal(partitionKeyRangeId); + int queryResultCount = createdCollection.queryItems(query, options) + .flatMap(p -> Flux.fromIterable(p.results())) + .collectList().block().size(); + + sum += queryResultCount; } assertThat(sum).isEqualTo(createdDocuments.size()); @@ -321,7 +298,7 @@ public void queryDocumentsWithCompositeContinuationTokens() throws Exception { @BeforeClass(groups = { "simple", "non-emulator" }, timeOut = 2 * SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = getSharedCosmosDatabase(client); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -336,7 +313,7 @@ public void beforeClass() { createdDocuments = bulkInsertBlocking(createdCollection, docDefList); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple", "non-emulator" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java index 4c72653b8f015..5b9509c79d1d9 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java @@ -22,23 +22,21 @@ */ package com.azure.data.cosmos.rx; -import java.util.UUID; - import com.azure.data.cosmos.AsyncDocumentClient; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Permission; import com.azure.data.cosmos.PermissionMode; import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.User; import com.azure.data.cosmos.internal.TestSuiteBase; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import rx.Observable; +import java.util.UUID; + //TODO: change to use external TestSuiteBase public class PermissionCrudTest extends TestSuiteBase { @@ -49,7 +47,7 @@ public class PermissionCrudTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public PermissionCrudTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -120,7 +118,7 @@ public void deletePermission() throws Exception { .build(); validateSuccess(deleteObservable, validator); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); // attempt to read the permission which was deleted Observable> readObservable = client.readPermission(readBackPermission.selfLink(), null); @@ -208,7 +206,7 @@ public void replacePermission() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = SHARED_DATABASE; } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java index c80f91265f294..75abe8275169f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java @@ -22,22 +22,10 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - import com.azure.data.cosmos.AsyncDocumentClient; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - +import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DatabaseForTest; -import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; @@ -45,9 +33,19 @@ import com.azure.data.cosmos.PermissionMode; import com.azure.data.cosmos.User; import com.azure.data.cosmos.internal.TestSuiteBase; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import rx.Observable; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + //TODO: change to use external TestSuiteBase public class PermissionQueryTest extends TestSuiteBase { @@ -61,7 +59,7 @@ public class PermissionQueryTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public PermissionQueryTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -151,7 +149,7 @@ public void invalidQuerySytax() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); Database d = new Database(); d.id(databaseId); createdDatabase = createDatabase(client, d); @@ -161,7 +159,7 @@ public void beforeClass() { createdPermissions.add(createPermissions(client, i)); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java index 3f482593ce335..2c4b90a64aacf 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java @@ -22,11 +22,16 @@ */ package com.azure.data.cosmos.rx; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.CosmosItemResponse; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.rx.proxy.HttpProxyServer; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; @@ -38,20 +43,12 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; - -import com.azure.data.cosmos.rx.proxy.HttpProxyServer; - import reactor.core.publisher.Mono; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosDatabase; -import com.azure.data.cosmos.CosmosItemRequestOptions; -import com.azure.data.cosmos.CosmosItemResponse; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.CosmosResponseValidator; -import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.ConsistencyLevel; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; @@ -72,12 +69,12 @@ public class ProxyHostTest extends TestSuiteBase { private HttpProxyServer httpProxyServer; public ProxyHostTest() { - this.clientBuilder = createGatewayRxDocumentClient(); + super(createGatewayRxDocumentClient()); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = getSharedCosmosDatabase(client); createdCollection = getSharedMultiPartitionCosmosContainer(client); httpProxyServer = new HttpProxyServer(); @@ -169,7 +166,6 @@ public void beforeMethod() { @AfterMethod(groups = { "simple" }) public void afterMethod(Method method) { - super.beforeMethod(method); LogManager.resetConfiguration(); PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties")); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java index a4ef1c38ce56d..06c488f0721e9 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java @@ -22,18 +22,8 @@ */ package com.azure.data.cosmos.rx; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerSettings; @@ -42,9 +32,17 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Flux; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + public class ReadFeedCollectionsTest extends TestSuiteBase { protected static final int FEED_TIMEOUT = 60000; @@ -60,7 +58,7 @@ public class ReadFeedCollectionsTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public ReadFeedCollectionsTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @@ -87,7 +85,7 @@ public void readCollections() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 3; i++) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java index 07f4cd2eabbfe..469a9e99686bb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java @@ -22,26 +22,24 @@ */ package com.azure.data.cosmos.rx; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.CosmosDatabaseSettings; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Flux; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + public class ReadFeedDatabasesTest extends TestSuiteBase { private List createdDatabases = new ArrayList<>(); @@ -51,7 +49,7 @@ public class ReadFeedDatabasesTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public ReadFeedDatabasesTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @@ -76,7 +74,7 @@ public void readDatabases() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws URISyntaxException { - client = clientBuilder.build(); + client = clientBuilder().build(); allDatabases = client.listDatabases(null) .map(frp -> frp.results()) .collectList() diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java index 61a6e47a90813..c06cff2f77054 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java @@ -24,19 +24,17 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; - -import reactor.core.publisher.Flux; - import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; @@ -53,7 +51,7 @@ public class ReadFeedDocumentsTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public ReadFeedDocumentsTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @@ -93,7 +91,7 @@ public void readDocuments_withoutEnableCrossPartitionQuery() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT, alwaysRun = true) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -104,7 +102,7 @@ public void beforeClass() { } createdDocuments = bulkInsertBlocking(createdCollection, docDefList); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java index 8eb0026e59835..36b232b376c9d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java @@ -22,25 +22,23 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; - +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosDatabaseSettings; +import com.azure.data.cosmos.FeedResponse; +import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosDatabaseSettings; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.FeedResponse; +import java.util.ArrayList; -import io.reactivex.subscribers.TestSubscriber; -import reactor.core.publisher.Flux; +import static org.assertj.core.api.Assertions.assertThat; public class ReadFeedExceptionHandlingTest extends TestSuiteBase { @@ -48,7 +46,7 @@ public class ReadFeedExceptionHandlingTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public ReadFeedExceptionHandlingTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -78,7 +76,7 @@ public void readFeedException() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java index d22d38a16d53d..7fa24e154a6de 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java @@ -22,17 +22,7 @@ */ package com.azure.data.cosmos.rx; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - import com.azure.data.cosmos.AsyncDocumentClient; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.DocumentCollection; @@ -41,9 +31,17 @@ import com.azure.data.cosmos.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.TestSuiteBase; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import rx.Observable; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + //TODO: change to use external TestSuiteBase public class ReadFeedOffersTest extends TestSuiteBase { @@ -60,7 +58,7 @@ public class ReadFeedOffersTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public ReadFeedOffersTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "emulator" }, timeOut = FEED_TIMEOUT) @@ -85,7 +83,7 @@ public void readOffers() throws Exception { @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 3; i++) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java index 7500611e3d8f8..b9db20bbd03c8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java @@ -22,17 +22,7 @@ */ package com.azure.data.cosmos.rx; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - import com.azure.data.cosmos.AsyncDocumentClient; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.FeedOptions; @@ -41,9 +31,17 @@ import com.azure.data.cosmos.PermissionMode; import com.azure.data.cosmos.User; import com.azure.data.cosmos.internal.TestSuiteBase; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import rx.Observable; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + //TODO: change to use external TestSuiteBase public class ReadFeedPermissionsTest extends TestSuiteBase { @@ -57,7 +55,7 @@ public class ReadFeedPermissionsTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public ReadFeedPermissionsTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @@ -82,7 +80,7 @@ public void readPermissions() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); Database d = new Database(); d.id(databaseId); createdDatabase = createDatabase(client, d); @@ -92,7 +90,7 @@ public void beforeClass() { createdPermissions.add(createPermissions(client, i)); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java index 65227ef707a37..ee92587679c76 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java @@ -22,16 +22,19 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.CosmosBridgeInternal; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKeyRange; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; - -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; - import rx.Observable; public class ReadFeedPkrTests extends TestSuiteBase { @@ -43,7 +46,7 @@ public class ReadFeedPkrTests extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public ReadFeedPkrTests(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "emulator" }, timeOut = FEED_TIMEOUT) @@ -63,8 +66,8 @@ public void readPartitionKeyRanges() throws Exception { @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = CosmosBridgeInternal.getAsyncDocumentClient(clientBuilder.build()); - createdDatabase = getSharedCosmosDatabase(clientBuilder.build()); + client = CosmosBridgeInternal.getAsyncDocumentClient(clientBuilder().build()); + createdDatabase = getSharedCosmosDatabase(clientBuilder().build()); createdCollection = createCollection(createdDatabase, getCollectionDefinition(), new CosmosContainerRequestOptions()); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java index f15380f41bc60..4dc2d72556455 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java @@ -22,26 +22,24 @@ */ package com.azure.data.cosmos.rx; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; import com.azure.data.cosmos.CosmosStoredProcedureSettings; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Flux; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + public class ReadFeedStoredProceduresTest extends TestSuiteBase { private CosmosContainer createdCollection; @@ -51,7 +49,7 @@ public class ReadFeedStoredProceduresTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public ReadFeedStoredProceduresTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @@ -80,7 +78,7 @@ public void readStoredProcedures() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -88,7 +86,7 @@ public void beforeClass() { createdStoredProcedures.add(createStoredProcedures(createdCollection)); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java index 6b596689bc247..eeeb32bb095c8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java @@ -22,18 +22,8 @@ */ package com.azure.data.cosmos.rx; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosTriggerSettings; @@ -41,9 +31,17 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Flux; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + public class ReadFeedTriggersTest extends TestSuiteBase { private CosmosContainer createdCollection; @@ -53,7 +51,7 @@ public class ReadFeedTriggersTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public ReadFeedTriggersTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @@ -82,7 +80,7 @@ public void readTriggers() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -90,7 +88,7 @@ public void beforeClass() { this.createdTriggers.add(this.createTriggers(createdCollection)); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java index 2930a6360001f..7f7e1e177d000 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java @@ -22,27 +22,25 @@ */ package com.azure.data.cosmos.rx; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Flux; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + public class ReadFeedUdfsTest extends TestSuiteBase { private Database createdDatabase; @@ -53,7 +51,7 @@ public class ReadFeedUdfsTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public ReadFeedUdfsTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @@ -82,7 +80,7 @@ public void readUserDefinedFunctions() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -90,7 +88,7 @@ public void beforeClass() { createdUserDefinedFunctions.add(createUserDefinedFunctions(createdCollection)); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java index bacf6f95fd08d..57e037ff7a423 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java @@ -22,27 +22,25 @@ */ package com.azure.data.cosmos.rx; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosDatabase; -import com.azure.data.cosmos.CosmosUserSettings; import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosUserSettings; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.RequestOptions; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Flux; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + public class ReadFeedUsersTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); @@ -53,7 +51,7 @@ public class ReadFeedUsersTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public ReadFeedUsersTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @@ -78,14 +76,14 @@ public void readUsers() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { createdUsers.add(createUsers(createdDatabase)); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java index aa66f6d61c12e..af43751145d93 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java @@ -22,23 +22,11 @@ */ package com.azure.data.cosmos.rx; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.DatabaseForTest; -import org.apache.commons.lang3.StringUtils; - -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKey; @@ -49,9 +37,18 @@ import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.User; import com.azure.data.cosmos.internal.TestSuiteBase; - +import org.apache.commons.lang3.StringUtils; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import rx.Observable; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + /** * This class try to test different scenario related to fetching various * resources from resource token directly or via permission feed . @@ -105,12 +102,12 @@ public class ResourceTokenTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public ResourceTokenTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); Database d = new Database(); d.id(databaseId); createdDatabase = createDatabase(client, d); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java index c3f2dba117a3e..613568e747a86 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java @@ -22,16 +22,15 @@ */ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosClientBuilder; -import com.azure.data.cosmos.CosmosContainer; - import org.apache.commons.lang3.NotImplementedException; import org.testng.Assert; import org.testng.annotations.AfterClass; @@ -69,7 +68,7 @@ public void serialize(String value, JsonGenerator gen, SerializerProvider serial @Factory(dataProvider = "clientBuildersWithDirect") public SimpleSerializationTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = {"simple"}, timeOut = TIMEOUT) @@ -91,7 +90,7 @@ public void createDocument() throws InterruptedException { @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java index fd0f10abb6de8..dbde24ce377a2 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java @@ -22,26 +22,33 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.SqlParameter; +import com.azure.data.cosmos.SqlParameterCollection; +import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.directconnectivity.Protocol; - import io.reactivex.subscribers.TestSubscriber; -import reactor.core.publisher.Flux; - import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; -import com.azure.data.cosmos.CosmosClientException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; public class SinglePartitionDocumentQueryTest extends TestSuiteBase { @@ -57,7 +64,7 @@ public String getCollectionLink() { @Factory(dataProvider = "clientBuildersWithDirect") public SinglePartitionDocumentQueryTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider") @@ -85,16 +92,7 @@ public void queryDocuments(boolean queryMetricsEnabled) throws Exception { .hasValidQueryMetrics(queryMetricsEnabled) .build(); - try { - validateQuerySuccess(queryObservable, validator, 10000); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable, validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -121,16 +119,7 @@ public void queryDocuments_ParameterizedQueryWithInClause() throws Exception { .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); - try { - validateQuerySuccess(queryObservable, validator, 10000); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable, validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -157,16 +146,7 @@ public void queryDocuments_ParameterizedQuery() throws Exception { .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); - try { - validateQuerySuccess(queryObservable, validator, 10000); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable, validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -209,16 +189,7 @@ public void queryDocumentsWithPageSize() throws Exception { .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); - try { - validateQuerySuccess(queryObservable, validator); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -242,16 +213,7 @@ public void queryOrderBy() throws Exception { .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); - try { - validateQuerySuccess(queryObservable, validator); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT * 1000) @@ -316,7 +278,7 @@ public CosmosItemProperties createDocument(CosmosContainer cosmosContainer, int @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedSinglePartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -328,7 +290,7 @@ public void beforeClass() throws Exception { createdDocuments.add(createDocument(createdCollection, 99)); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java index 6ce5cdec20a58..6467119c56a46 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java @@ -28,13 +28,11 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; - -import reactor.core.publisher.Flux; - import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; @@ -50,7 +48,7 @@ public class SinglePartitionReadFeedDocumentsTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public SinglePartitionReadFeedDocumentsTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = FEED_TIMEOUT) @@ -73,7 +71,7 @@ public void readDocuments() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedSinglePartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -84,7 +82,7 @@ public void beforeClass() { } createdDocuments = bulkInsertBlocking(createdCollection, docDefList); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java index df45db1efb007..91d98c5ea4a02 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java @@ -22,15 +22,8 @@ */ package com.azure.data.cosmos.rx; -import java.util.UUID; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosResponse; import com.azure.data.cosmos.CosmosResponseValidator; @@ -38,9 +31,14 @@ import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; import com.azure.data.cosmos.CosmosStoredProcedureResponse; import com.azure.data.cosmos.CosmosStoredProcedureSettings; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Mono; +import java.util.UUID; + public class StoredProcedureCrudTest extends TestSuiteBase { private CosmosContainer createdCollection; @@ -49,7 +47,7 @@ public class StoredProcedureCrudTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public StoredProcedureCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -81,7 +79,7 @@ public void readStoredProcedure() throws Exception { .block().storedProcedure(); // read stored procedure - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = storedProcedure.read(null); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -111,7 +109,7 @@ public void deleteStoredProcedure() throws Exception { validateSuccess(deleteObservable, validator); // attempt to read stored procedure which was deleted - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = storedProcedure.read(null); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); @@ -120,7 +118,7 @@ public void deleteStoredProcedure() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java index 84900152f62db..a01e6132c7d7c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java @@ -22,30 +22,27 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - +import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosStoredProcedureSettings; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.directconnectivity.Protocol; - -import reactor.core.publisher.Flux; - import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosStoredProcedureSettings; -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; public class StoredProcedureQueryTest extends TestSuiteBase { @@ -56,7 +53,7 @@ public class StoredProcedureQueryTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public StoredProcedureQueryTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -82,16 +79,7 @@ public void queryWithFilter() throws Exception { .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); - try { - validateQuerySuccess(queryObservable, validator, 10000); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable, validator, 10000); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -135,16 +123,7 @@ public void queryAll() throws Exception { .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); - try { - validateQuerySuccess(queryObservable, validator); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -169,7 +148,7 @@ public CosmosStoredProcedureSettings createStoredProc(CosmosContainer cosmosCont @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -177,7 +156,7 @@ public void beforeClass() throws Exception { createdStoredProcs.add(createStoredProc(createdCollection)); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java index e30089fd1c7e1..25416f688251a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java @@ -22,22 +22,8 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.UUID; - -import com.azure.data.cosmos.CosmosClientBuilder; -import com.azure.data.cosmos.directconnectivity.Protocol; - -import reactor.core.publisher.Mono; - -import org.testng.SkipException; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosStoredProcedure; @@ -46,6 +32,15 @@ import com.azure.data.cosmos.CosmosStoredProcedureSettings; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.RequestOptions; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import reactor.core.publisher.Mono; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; public class StoredProcedureUpsertReplaceTest extends TestSuiteBase { @@ -55,7 +50,7 @@ public class StoredProcedureUpsertReplaceTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public StoredProcedureUpsertReplaceTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -68,7 +63,7 @@ public void replaceStoredProcedure() throws Exception { CosmosStoredProcedureSettings readBackSp = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().settings(); // read stored procedure to validate creation - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = createdCollection.getStoredProcedure(readBackSp.id()).read(null); // validate stored procedure creation @@ -97,50 +92,33 @@ public void replaceStoredProcedure() throws Exception { public void executeStoredProcedure() throws Exception { // create a stored procedure CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings( - "{" + - " 'id': '" +UUID.randomUUID().toString() + "'," + - " 'body':" + - " 'function () {" + - " for (var i = 0; i < 10; i++) {" + - " getContext().getResponse().appendValue(\"Body\", i);" + - " }" + - " }'" + - "}"); + "{" + + " 'id': '" + UUID.randomUUID().toString() + "'," + + " 'body':" + + " 'function () {" + + " for (var i = 0; i < 10; i++) {" + + " getContext().getResponse().appendValue(\"Body\", i);" + + " }" + + " }'" + + "}"); CosmosStoredProcedure storedProcedure = null; - try { - storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, + new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); String result = null; - try { - RequestOptions options = new RequestOptions(); - options.setPartitionKey(PartitionKey.None); - result = storedProcedure.execute(null, options).block().responseAsString(); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + RequestOptions options = new RequestOptions(); + options.setPartitionKey(PartitionKey.None); + result = storedProcedure.execute(null, options).block().responseAsString(); assertThat(result).isEqualTo("\"0123456789\""); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index 17374b62bc9a9..4447edb1625b7 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -22,37 +22,51 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.spy; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.CompositePath; +import com.azure.data.cosmos.CompositePathSortOrder; +import com.azure.data.cosmos.ConnectionMode; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosBridgeInternal; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosClientTest; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosDatabaseResponse; +import com.azure.data.cosmos.CosmosDatabaseSettings; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosRequestOptions; +import com.azure.data.cosmos.CosmosResponse; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosUser; +import com.azure.data.cosmos.CosmosUserSettings; +import com.azure.data.cosmos.DataType; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.IncludedPath; +import com.azure.data.cosmos.Index; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.RetryOptions; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.PathParser; import com.azure.data.cosmos.internal.Utils; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.PathParser; -import com.azure.data.cosmos.directconnectivity.Protocol; -import com.azure.data.cosmos.internal.Configs; - import io.reactivex.subscribers.TestSubscriber; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import rx.Observable; - import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.mockito.stubbing.Answer; @@ -63,12 +77,30 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.DataProvider; - import org.testng.annotations.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import rx.Observable; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; + +public class TestSuiteBase extends CosmosClientTest { -public class TestSuiteBase { private static final int DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL = 500; private static final ObjectMapper objectMapper = new ObjectMapper(); + protected static Logger logger = LoggerFactory.getLogger(TestSuiteBase.class.getSimpleName()); protected static final int TIMEOUT = 40000; protected static final int FEED_TIMEOUT = 40000; @@ -86,13 +118,16 @@ public class TestSuiteBase { private static final ImmutableList protocols; protected int subscriberValidationTimeout = TIMEOUT; - protected CosmosClientBuilder clientBuilder; private static CosmosDatabase SHARED_DATABASE; private static CosmosContainer SHARED_MULTI_PARTITION_COLLECTION; private static CosmosContainer SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES; private static CosmosContainer SHARED_SINGLE_PARTITION_COLLECTION; + public TestSuiteBase(CosmosClientBuilder clientBuilder) { + super(clientBuilder); + } + protected static CosmosDatabase getSharedCosmosDatabase(CosmosClient client) { return CosmosBridgeInternal.getCosmosDatabaseWithNewClient(SHARED_DATABASE, client); } @@ -131,25 +166,6 @@ private static ImmutableList immutableListOrNull(List list) { return list != null ? ImmutableList.copyOf(list) : null; } - @BeforeMethod(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}) - public void beforeMethod(Method method) { - if (this.clientBuilder != null) { - logger.info("Starting {}::{} using {} {} mode with {} consistency", - method.getDeclaringClass().getSimpleName(), method.getName(), - this.clientBuilder.getConnectionPolicy().connectionMode(), - this.clientBuilder.getConfigs().getProtocol(), - this.clientBuilder.getDesiredConsistencyLevel()); - return; - } - logger.info("Starting {}::{}", method.getDeclaringClass().getSimpleName(), method.getName()); - } - - @AfterMethod(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}) - public void afterMethod(Method m) { - Test t = m.getAnnotation(Test.class); - logger.info("Finished {}:{}.", m.getDeclaringClass().getSimpleName(), m.getName()); - } - private static class DatabaseManagerImpl implements CosmosDatabaseForTest.DatabaseManager { public static DatabaseManagerImpl getInstance(CosmosClient client) { return new DatabaseManagerImpl(client); @@ -671,42 +687,6 @@ static protected void safeClose(CosmosClient client) { } } - public void validateSuccess(Observable> observable, - ResourceResponseValidator validator) { - validateSuccess(observable, validator, subscriberValidationTimeout); - } - - public static void validateSuccess(Observable> observable, - ResourceResponseValidator validator, long timeout) { - - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - - observable.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); - testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); - } - - public void validateFailure(Observable> observable, - FailureValidator validator) { - validateFailure(observable, validator, subscriberValidationTimeout); - } - - public static void validateFailure(Observable> observable, - FailureValidator validator, long timeout) { - - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - - observable.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); - } - public void validateQuerySuccess(Observable> observable, FeedResponseListValidator validator) { validateQuerySuccess(observable, validator, subscriberValidationTimeout); @@ -724,24 +704,6 @@ public static void validateQuerySuccess(Observable void validateQueryFailure(Observable> observable, - FailureValidator validator) { - validateQueryFailure(observable, validator, subscriberValidationTimeout); - } - - public static void validateQueryFailure(Observable> observable, - FailureValidator validator, long timeout) { - - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - - observable.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); - } - public void validateSuccess(Mono single, CosmosResponseValidator validator) throws InterruptedException { validateSuccess(single.flux(), validator, subscriberValidationTimeout); @@ -830,7 +792,7 @@ public static Object[][] clientBuildersWithSessionConsistency() { private static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { for (ConsistencyLevel consistencyLevel : ConsistencyLevel.values()) { - if (consistencyLevel.name().toLowerCase().equals(consistency.toLowerCase())) { + if (consistencyLevel.toString().toLowerCase().equals(consistency.toLowerCase())) { return consistencyLevel; } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java index 76facad3c1254..fdab59e72fc63 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java @@ -47,7 +47,6 @@ import com.azure.data.cosmos.User; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.TestSuiteBase; - import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -56,15 +55,14 @@ import org.testng.annotations.Test; import rx.Observable; -import static org.assertj.core.api.Assertions.assertThat; - import java.time.OffsetDateTime; -import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.UUID; import java.util.Map; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; //TODO: change to use external TestSuiteBase public class TokenResolverTest extends TestSuiteBase { @@ -92,7 +90,7 @@ public UserClass(String userName, int userId) { @Factory(dataProvider = "clientBuilders") public TokenResolverTest(AsyncDocumentClient.Builder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @DataProvider(name = "connectionMode") @@ -108,7 +106,7 @@ public void beforeClass() { createdDatabase = SHARED_DATABASE; createdCollection = SHARED_SINGLE_PARTITION_COLLECTION; - client = clientBuilder.build(); + client = clientBuilder().build(); userWithReadPermission = createUser(client, createdDatabase.id(), getUserDefinition()); readPermission = client.createPermission(userWithReadPermission.selfLink(), getPermission(createdCollection, "ReadPermissionOnColl", PermissionMode.READ), null).toBlocking().single() @@ -315,10 +313,10 @@ public void createAndExecuteSprocWithWritePermission(ConnectionMode connectionMo " var mytext = \"x\";" + " var myval = 1;" + " try {" + - " getContext().getResponse().body(\"Success!\");" + + " getContext().getResponse().setBody(\"Success!\");" + " }" + " catch(err) {" + - " getContext().getResponse().body(\"inline err: [\" + err.number + \"] \" + err);" + + " getContext().getResponse().setBody(\"inline err: [\" + err.number + \"] \" + err);" + " }" + " }'" + "}"); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java index 507f422ac706b..fececb58063b2 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java @@ -22,34 +22,32 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; - +import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.RetryAnalyzer; import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.Utils.ValueHolder; +import com.azure.data.cosmos.internal.query.TakeContinuationToken; +import io.reactivex.subscribers.TestSubscriber; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.internal.Utils.ValueHolder; -import com.azure.data.cosmos.internal.query.TakeContinuationToken; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; -import io.reactivex.subscribers.TestSubscriber; -import reactor.core.publisher.Flux; +import static org.assertj.core.api.Assertions.assertThat; public class TopQueryTests extends TestSuiteBase { private CosmosContainer createdCollection; @@ -64,7 +62,7 @@ public class TopQueryTests extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public TopQueryTests(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "queryMetricsArgProvider", retryAnalyzer = RetryAnalyzer.class) @@ -86,17 +84,7 @@ public void queryDocumentsWithTop(boolean qmEnabled) throws Exception { FeedResponseListValidator validator1 = new FeedResponseListValidator.Builder() .totalSize(0).build(); - try { - validateQuerySuccess(queryObservable1, validator1, TIMEOUT); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", - this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + validateQuerySuccess(queryObservable1, validator1, TIMEOUT); Flux> queryObservable2 = createdCollection.queryItems("SELECT TOP 1 value AVG(c.field) from c", options); @@ -230,12 +218,12 @@ public void afterClass() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedSinglePartitionCosmosContainer(client); truncateCollection(createdCollection); bulkInsert(client); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java index 1e5674b7bb5ab..a2cfa078b19e5 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java @@ -22,15 +22,8 @@ */ package com.azure.data.cosmos.rx; -import java.util.UUID; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponse; @@ -41,9 +34,14 @@ import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Mono; +import java.util.UUID; + public class TriggerCrudTest extends TestSuiteBase { private CosmosContainer createdCollection; @@ -51,7 +49,7 @@ public class TriggerCrudTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public TriggerCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT * 100) @@ -87,7 +85,7 @@ public void readTrigger() throws Exception { CosmosTrigger readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().trigger(); // read trigger - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = readBackTrigger.read(new RequestOptions()); // validate read trigger @@ -122,7 +120,7 @@ public void deleteTrigger() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java index 4b2f9104bb382..23d1e60a60686 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java @@ -22,20 +22,28 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosRequestOptions; +import com.azure.data.cosmos.CosmosTriggerSettings; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.TriggerOperation; +import com.azure.data.cosmos.TriggerType; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; -import com.azure.data.cosmos.*; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import reactor.core.publisher.Flux; +import static org.assertj.core.api.Assertions.assertThat; public class TriggerQueryTest extends TestSuiteBase { @@ -46,7 +54,7 @@ public class TriggerQueryTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public TriggerQueryTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -143,7 +151,7 @@ public CosmosTriggerSettings createTrigger(CosmosContainer cosmosContainer) { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -151,7 +159,7 @@ public void beforeClass() throws Exception { createdTriggers.add(createTrigger(createdCollection)); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java index d764dbc6c6aa0..1b4ab9062182b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java @@ -22,15 +22,8 @@ */ package com.azure.data.cosmos.rx; -import java.util.UUID; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponseValidator; @@ -39,9 +32,14 @@ import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Mono; +import java.util.UUID; + public class TriggerUpsertReplaceTest extends TestSuiteBase { private CosmosContainer createdCollection; @@ -50,7 +48,7 @@ public class TriggerUpsertReplaceTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public TriggerUpsertReplaceTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -65,7 +63,7 @@ public void replaceTrigger() throws Exception { CosmosTriggerSettings readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().settings(); // read trigger to validate creation - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = createdCollection.getTrigger(readBackTrigger.id()).read(new RequestOptions()); // validate trigger creation @@ -94,7 +92,7 @@ public void replaceTrigger() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java index 368045bb2bf25..b97adacc9bd8a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java @@ -22,28 +22,44 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.UUID; -import java.util.stream.Collectors; - -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.DataType; +import com.azure.data.cosmos.ExcludedPath; +import com.azure.data.cosmos.HashIndex; +import com.azure.data.cosmos.IncludedPath; +import com.azure.data.cosmos.IndexingMode; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.UniqueKey; +import com.azure.data.cosmos.UniqueKeyPolicy; +import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Utils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; - -import com.azure.data.cosmos.*; +import com.google.common.collect.ImmutableList; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableList; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.HttpConstants; +import java.util.ArrayList; +import java.util.Collections; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; public class UniqueIndexTest extends TestSuiteBase { protected static final int TIMEOUT = 30000; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java index 58bd41650a280..bce4c3db08865 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java @@ -23,24 +23,22 @@ package com.azure.data.cosmos.rx; -import java.util.UUID; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosUser; import com.azure.data.cosmos.CosmosUserResponse; import com.azure.data.cosmos.CosmosUserSettings; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Mono; +import java.util.UUID; + public class UserCrudTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); @@ -51,7 +49,7 @@ public class UserCrudTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public UserCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "emulator" }, timeOut = TIMEOUT) @@ -169,7 +167,7 @@ public void replaceUser() throws Exception { @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = createDatabase(client, databaseId); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java index 49f6f9c99e379..93d2d3748fbe8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java @@ -22,15 +22,8 @@ */ package com.azure.data.cosmos.rx; -import java.util.UUID; - -import com.azure.data.cosmos.CosmosClientBuilder; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponse; @@ -38,9 +31,14 @@ import com.azure.data.cosmos.CosmosUserDefinedFunction; import com.azure.data.cosmos.CosmosUserDefinedFunctionResponse; import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Mono; +import java.util.UUID; + public class UserDefinedFunctionCrudTest extends TestSuiteBase { private CosmosContainer createdCollection; @@ -48,7 +46,7 @@ public class UserDefinedFunctionCrudTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public UserDefinedFunctionCrudTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -78,7 +76,7 @@ public void readUserDefinedFunction() throws Exception { CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); // read udf - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = readBackUdf.read(null); //validate udf read @@ -110,7 +108,7 @@ public void deleteUserDefinedFunction() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java index ca86d0ed408da..9e83d3474fd10 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java @@ -22,30 +22,28 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - +import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - -import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; - +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Flux; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + public class UserDefinedFunctionQueryTest extends TestSuiteBase { private Database createdDatabase; @@ -60,7 +58,7 @@ public String getCollectionLink() { @Factory(dataProvider = "clientBuildersWithDirect") public UserDefinedFunctionQueryTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -154,7 +152,7 @@ public CosmosUserDefinedFunctionSettings createUserDefinedFunction(CosmosContain @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -162,7 +160,7 @@ public void beforeClass() throws Exception { createdUDF.add(createUserDefinedFunction(createdCollection)); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java index 3b2c62aa66025..896ca3a76df09 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java @@ -22,26 +22,24 @@ */ package com.azure.data.cosmos.rx; -import java.util.UUID; - -import com.azure.data.cosmos.CosmosClientBuilder; -import com.azure.data.cosmos.directconnectivity.Protocol; -import org.testng.SkipException; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; - import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosUserDefinedFunctionResponse; import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; import com.azure.data.cosmos.RequestOptions; - +import com.azure.data.cosmos.directconnectivity.Protocol; +import org.testng.SkipException; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; import reactor.core.publisher.Mono; +import java.util.UUID; + public class UserDefinedFunctionUpsertReplaceTest extends TestSuiteBase { private CosmosContainer createdCollection; @@ -50,7 +48,7 @@ public class UserDefinedFunctionUpsertReplaceTest extends TestSuiteBase { @Factory(dataProvider = "clientBuildersWithDirect") public UserDefinedFunctionUpsertReplaceTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -63,19 +61,10 @@ public void replaceUserDefinedFunction() throws Exception { CosmosUserDefinedFunctionSettings readBackUdf = null; - try { readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().settings(); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } - + // read udf to validate creation - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = createdCollection.getUserDefinedFunction(readBackUdf.id()).read(new RequestOptions()); // validate udf creation @@ -102,7 +91,7 @@ public void replaceUserDefinedFunction() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java index 2f45a51463818..e748b14d95001 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java @@ -22,28 +22,26 @@ */ package com.azure.data.cosmos.rx; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - +import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosUserSettings; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; -import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.CosmosDatabase; -import com.azure.data.cosmos.CosmosDatabaseForTest; -import com.azure.data.cosmos.CosmosUserSettings; -import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; -import reactor.core.publisher.Flux; +import static org.assertj.core.api.Assertions.assertThat; public class UserQueryTest extends TestSuiteBase { @@ -56,7 +54,7 @@ public class UserQueryTest extends TestSuiteBase { @Factory(dataProvider = "clientBuilders") public UserQueryTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -132,7 +130,7 @@ public void queryUsers_NoResults() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdDatabase = createDatabase(client, databaseId); @@ -142,7 +140,7 @@ public void beforeClass() throws Exception { createdUsers.add(createUser(client, databaseId, user).read().block().settings()); } - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java index 5cdd86ecbce70..03b2a3ed8e9c1 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java @@ -25,29 +25,28 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.RetryAnalyzer; import com.azure.data.cosmos.directconnectivity.Protocol; - -import reactor.core.publisher.Mono; - import org.apache.commons.lang3.StringUtils; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Mono; import java.util.UUID; import static org.apache.commons.io.FileUtils.ONE_MB; public class VeryLargeDocumentQueryTest extends TestSuiteBase { + private final static int TIMEOUT = 60000; private final static int SETUP_TIMEOUT = 60000; private Database createdDatabase; @@ -57,33 +56,27 @@ public class VeryLargeDocumentQueryTest extends TestSuiteBase { @Factory(dataProvider = "simpleClientBuildersWithDirect") public VeryLargeDocumentQueryTest(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @Test(groups = { "emulator" }, timeOut = TIMEOUT, retryAnalyzer = RetryAnalyzer.class) public void queryLargeDocuments() throws InterruptedException { + int cnt = 5; + for(int i = 0; i < cnt; i++) { createLargeDocument(); } - try { - FeedOptions options = new FeedOptions(); - options.enableCrossPartitionQuery(true); - validateQuerySuccess(createdCollection.queryItems("SELECT * FROM r", options), - new FeedResponseListValidator.Builder().totalSize(cnt).build()); - } catch (Throwable error) { - if (this.clientBuilder.getConfigs().getProtocol() == Protocol.TCP) { - String message = String.format("DIRECT TCP test failure ignored: desiredConsistencyLevel=%s", this.clientBuilder.getDesiredConsistencyLevel()); - logger.info(message, error); - throw new SkipException(message, error); - } - throw error; - } + FeedOptions options = new FeedOptions(); + options.enableCrossPartitionQuery(true); + + validateQuerySuccess(createdCollection.queryItems("SELECT * FROM r", options), + new FeedResponseListValidator.Builder().totalSize(cnt).build()); } private void createLargeDocument() throws InterruptedException { - Document docDefinition = getDocumentDefinition(); + CosmosItemProperties docDefinition = getDocumentDefinition(); //Keep size as ~ 1.999MB to account for size of other props int size = (int) (ONE_MB * 1.999); @@ -100,7 +93,7 @@ private void createLargeDocument() throws InterruptedException { @BeforeClass(groups = { "emulator" }, timeOut = 2 * SETUP_TIMEOUT) public void beforeClass() throws Exception { - client = clientBuilder.build(); + client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); } @@ -110,9 +103,9 @@ public void afterClass() { safeClose(client); } - private static Document getDocumentDefinition() { + private static CosmosItemProperties getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "}" diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java index 93a6eefef7687..bb3973d0ab3d3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java @@ -22,13 +22,12 @@ */ package com.azure.data.cosmos.rx.proxy; -import java.util.concurrent.atomic.AtomicLong; - +import io.netty.channel.ChannelInitializer; +import io.netty.channel.socket.SocketChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.socket.SocketChannel; +import java.util.concurrent.atomic.AtomicLong; /** * The channel initializer. diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java index 40d71b34997c8..a1edfb573dadb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java @@ -22,9 +22,6 @@ */ package com.azure.data.cosmos.rx.proxy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -33,6 +30,8 @@ import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Handle data from client. diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java index 7a0bb6833feeb..7424ae3c25a2a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java @@ -22,14 +22,13 @@ */ package com.azure.data.cosmos.rx.proxy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Handle data from remote. diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java index 575c738dc8948..be33ef88ffce4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java @@ -22,13 +22,12 @@ */ package com.azure.data.cosmos.rx.proxy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * A http proxy server. From d186d786cd5ac669a158597e0a08f7d7bb1a4521 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Thu, 13 Jun 2019 14:04:35 -0700 Subject: [PATCH 38/85] Fixing parse protocols and desired consistency to work for new upper case enum types. Optimized imports --- .../src/main/java/com/azure/data/cosmos/PermissionMode.java | 1 - .../data/cosmos/directconnectivity/DCDocumentCrudTest.java | 1 - .../java/com/azure/data/cosmos/internal/TestSuiteBase.java | 3 +++ .../java/com/azure/data/cosmos/rx/AggregateQueryTests.java | 2 -- .../azure/data/cosmos/rx/DocumentClientResourceLeakTest.java | 2 -- .../test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java | 3 --- .../java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java | 1 - .../data/cosmos/rx/SinglePartitionDocumentQueryTest.java | 2 -- .../com/azure/data/cosmos/rx/StoredProcedureQueryTest.java | 2 -- sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java | 4 ---- sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java | 2 -- .../data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java | 2 -- .../com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java | 2 -- 13 files changed, 3 insertions(+), 24 deletions(-) diff --git a/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java b/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java index 6c9cd7bef86bf..33b40d376f280 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java +++ b/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; /** diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java index f71caa3df9f24..cd90b80b4fba4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java @@ -47,7 +47,6 @@ import com.azure.data.cosmos.rx.ResourceResponseValidator; import com.azure.data.cosmos.rx.TestConfigurations; import org.mockito.stubbing.Answer; -import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index ede3556635cff..56fdd54d29ccc 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -809,6 +809,8 @@ static List parseProtocols(String protocols) { return null; } + protocols = protocols.toUpperCase(); + try { return objectMapper.readValue(protocols, new TypeReference>() { }); @@ -888,6 +890,7 @@ static List parseDesiredConsistencies(String consistencies) { return null; } + consistencies = consistencies.toUpperCase(); try { return objectMapper.readValue(consistencies, new TypeReference>() { }); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java index a1edf5d50ee73..c28ab466d11ed 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java @@ -29,8 +29,6 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.directconnectivity.Protocol; -import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java index 415d28143120a..957413c4c660e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java @@ -27,9 +27,7 @@ import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.directconnectivity.Protocol; import com.google.common.base.Strings; -import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java index 13d40d36c6c88..e007f30f66da5 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java @@ -31,11 +31,8 @@ import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.CosmosResponseValidator; -import com.azure.data.cosmos.Document; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.directconnectivity.Protocol; import org.apache.commons.lang3.StringUtils; -import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java index 43ca3088fc816..0828566f4841e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java @@ -32,7 +32,6 @@ import com.azure.data.cosmos.CosmosContainerSettings; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemRequestOptions; -import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java index dbde24ce377a2..ad21c0e824b69 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java @@ -34,9 +34,7 @@ import com.azure.data.cosmos.SqlParameter; import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.directconnectivity.Protocol; import io.reactivex.subscribers.TestSubscriber; -import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java index a01e6132c7d7c..f1555493f2d0e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java @@ -29,8 +29,6 @@ import com.azure.data.cosmos.CosmosStoredProcedureSettings; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.directconnectivity.Protocol; -import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index 4447edb1625b7..87b2f44db8d35 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -72,19 +72,15 @@ import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import rx.Observable; import java.io.PrintWriter; import java.io.StringWriter; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.List; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java index fececb58063b2..b8db0be7977ec 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java @@ -30,11 +30,9 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.RetryAnalyzer; -import com.azure.data.cosmos.directconnectivity.Protocol; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.TakeContinuationToken; import io.reactivex.subscribers.TestSubscriber; -import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java index 896ca3a76df09..8fcaf50b9228a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java @@ -30,8 +30,6 @@ import com.azure.data.cosmos.CosmosUserDefinedFunctionResponse; import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.directconnectivity.Protocol; -import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java index 03b2a3ed8e9c1..769731568cf86 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java @@ -32,9 +32,7 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.RetryAnalyzer; -import com.azure.data.cosmos.directconnectivity.Protocol; import org.apache.commons.lang3.StringUtils; -import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; From ff9f3e587ad9404c464a9b163bb6c8c56286c4e9 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Thu, 13 Jun 2019 14:11:58 -0700 Subject: [PATCH 39/85] Removed unncessary lines --- .../java/com/azure/data/cosmos/internal/TestSuiteBase.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index 56fdd54d29ccc..3b8fd0d674239 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -808,9 +808,7 @@ static List parseProtocols(String protocols) { if (StringUtils.isEmpty(protocols)) { return null; } - protocols = protocols.toUpperCase(); - try { return objectMapper.readValue(protocols, new TypeReference>() { }); @@ -889,7 +887,6 @@ static List parseDesiredConsistencies(String consistencies) { if (StringUtils.isEmpty(consistencies)) { return null; } - consistencies = consistencies.toUpperCase(); try { return objectMapper.readValue(consistencies, new TypeReference>() { From 585e994e46ad74da6af882ad78edd10fa7fd6da0 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Thu, 13 Jun 2019 14:19:07 -0700 Subject: [PATCH 40/85] Made the consistency upper case change to other test suite base --- sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index 87b2f44db8d35..049f87ae84625 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -816,7 +816,7 @@ static List parseProtocols(String protocols) { if (StringUtils.isEmpty(protocols)) { return null; } - + protocols = protocols.toUpperCase(); try { return objectMapper.readValue(protocols, new TypeReference>() { }); @@ -895,7 +895,7 @@ static List parseDesiredConsistencies(String consistencies) { if (StringUtils.isEmpty(consistencies)) { return null; } - + consistencies = consistencies.toUpperCase(); try { return objectMapper.readValue(consistencies, new TypeReference>() { }); From d325e433036b73af234a41c59f8d930d5558963f Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Thu, 13 Jun 2019 14:37:06 -0700 Subject: [PATCH 41/85] Upper casing desired consistency in Read my writes test --- .../data/cosmos/benchmark/ReadMyWritesConsistencyTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java index a7a744451fd72..ff763598b4406 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java @@ -96,7 +96,7 @@ public void readMyWrites(boolean useNameLink) throws Exception { TestConfigurations.MASTER_KEY, database.id(), collection.id(), - desiredConsistency, + desiredConsistency.toUpperCase(), concurrency, numberOfOperationsAsString, maxRunningTime) From e50a4c1da05fc3defb1043089f45fe9750aae0d6 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Thu, 13 Jun 2019 16:06:41 -0700 Subject: [PATCH 42/85] Fixed Consistency and protocol parsing bugs related to test configurations --- .../ReadMyWritesConsistencyTest.java | 5 +-- .../data/cosmos/rx/TestConfigurations.java | 2 +- .../azure/data/cosmos/DocumentClientTest.java | 2 +- .../rx/examples/DocumentCRUDAsyncAPITest.java | 1 + .../data/cosmos/internal/TestSuiteBase.java | 34 +++++++++++-------- .../azure/data/cosmos/rx/ParsingEnvTest.java | 4 +-- .../azure/data/cosmos/rx/TestSuiteBase.java | 31 ++++++++++------- 7 files changed, 47 insertions(+), 32 deletions(-) diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java index ff763598b4406..0ee1942d0ac05 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java @@ -34,6 +34,7 @@ import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.rx.TestConfigurations; import com.beust.jcommander.JCommander; +import com.google.common.base.CaseFormat; import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -70,7 +71,7 @@ public class ReadMyWritesConsistencyTest { private final String desiredConsistency = System.getProperty("DESIRED_CONSISTENCY", StringUtils.defaultString(Strings.emptyToNull( - System.getenv().get("DESIRED_CONSISTENCY")), "SESSION")); + System.getenv().get("DESIRED_CONSISTENCY")), "Session")); private final String numberOfOperationsAsString = System.getProperty("NUMBER_OF_OPERATIONS", @@ -96,7 +97,7 @@ public void readMyWrites(boolean useNameLink) throws Exception { TestConfigurations.MASTER_KEY, database.id(), collection.id(), - desiredConsistency.toUpperCase(), + CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, desiredConsistency), concurrency, numberOfOperationsAsString, maxRunningTime) diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java index 744b154c575aa..81ca2a45bb4a9 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java @@ -57,7 +57,7 @@ public final class TestConfigurations { public static String CONSISTENCY = System.getProperty("ACCOUNT_CONSISTENCY", StringUtils.defaultString(Strings.emptyToNull( - System.getenv().get("ACCOUNT_CONSISTENCY")), "STRONG")); + System.getenv().get("ACCOUNT_CONSISTENCY")), "Strong")); public static String PREFERRED_LOCATIONS = System.getProperty("PREFERRED_LOCATIONS", diff --git a/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java b/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java index 2cf4d67cd8d37..054bbcf8595a6 100644 --- a/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java @@ -32,7 +32,7 @@ public abstract class DocumentClientTest implements ITest { - private final AsyncDocumentClient.Builder clientBuilder;; + private final AsyncDocumentClient.Builder clientBuilder; private String testName; public DocumentClientTest() { diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java index 9ed6519cdb42f..4ce611474f8ae 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java @@ -102,6 +102,7 @@ public void setUp() { ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); this.clientBuilder() + .withServiceEndpoint(TestConfigurations.HOST) .withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY) .withConnectionPolicy(connectionPolicy) .withConsistencyLevel(ConsistencyLevel.SESSION); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index 3b8fd0d674239..073763d0764bf 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -60,6 +60,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.CaseFormat; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; @@ -123,6 +124,11 @@ private static ImmutableList immutableListOrNull(List list) { preferredLocations = immutableListOrNull(parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS)); protocols = ObjectUtils.defaultIfNull(immutableListOrNull(parseProtocols(TestConfigurations.PROTOCOLS)), ImmutableList.of(Protocol.HTTPS, Protocol.TCP)); + // Object mapper configuration + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); + objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); + objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); } private String testName; @@ -133,10 +139,6 @@ protected TestSuiteBase() { protected TestSuiteBase(AsyncDocumentClient.Builder clientBuilder) { super(clientBuilder); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); - objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); - objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); logger.debug("Initializing {} ...", this.getClass().getSimpleName()); } @@ -779,11 +781,8 @@ public static Object[][] clientBuildersWithSessionConsistency() { private static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { - for (ConsistencyLevel consistencyLevel : ConsistencyLevel.values()) { - if (consistencyLevel.toString().toLowerCase().equals(consistency.toLowerCase())) { - return consistencyLevel; - } - } + consistency = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency).trim(); + return ConsistencyLevel.valueOf(consistency); } logger.error("INVALID configured test consistency [{}].", consistency); @@ -808,10 +807,14 @@ static List parseProtocols(String protocols) { if (StringUtils.isEmpty(protocols)) { return null; } - protocols = protocols.toUpperCase(); + List protocolList = new ArrayList<>(); try { - return objectMapper.readValue(protocols, new TypeReference>() { + List protocolStrings = objectMapper.readValue(protocols, new TypeReference>() { }); + for(String protocol : protocolStrings) { + protocolList.add(Protocol.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, protocol))); + } + return protocolList; } catch (Exception e) { logger.error("INVALID configured test protocols [{}].", protocols); throw new IllegalStateException("INVALID configured test protocols " + protocols); @@ -887,10 +890,13 @@ static List parseDesiredConsistencies(String consistencies) { if (StringUtils.isEmpty(consistencies)) { return null; } - consistencies = consistencies.toUpperCase(); + List consistencyLevels = new ArrayList<>(); try { - return objectMapper.readValue(consistencies, new TypeReference>() { - }); + List consistencyStrings = objectMapper.readValue(consistencies, new TypeReference>() {}); + for(String consistency : consistencyStrings) { + consistencyLevels.add(ConsistencyLevel.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency))); + } + return consistencyLevels; } catch (Exception e) { logger.error("INVALID consistency test desiredConsistencies [{}].", consistencies); throw new IllegalStateException("INVALID configured test desiredConsistencies " + consistencies); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java index 0c6b64c4a20cc..2b19bb49b3efc 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java @@ -33,7 +33,7 @@ public class ParsingEnvTest { @Test(groups = "unit") public void parseDesiredConsistencies() { - assertThat(TestSuiteBase.parseDesiredConsistencies("[ \"SESSION\" , \"STRONG\" ]")).containsExactly( + assertThat(TestSuiteBase.parseDesiredConsistencies("[ \"Session\" , \"Strong\" ]")).containsExactly( ConsistencyLevel.SESSION, ConsistencyLevel.STRONG); } @@ -61,6 +61,6 @@ public void parsePreferredLocation_null() { @Test(groups = "unit") public void protocols() { - assertThat(TestSuiteBase.parseProtocols("[ \"TCP\" , \"HTTPS\" ]")).containsExactly(Protocol.TCP, Protocol.HTTPS); + assertThat(TestSuiteBase.parseProtocols("[ \"Tcp\" , \"Https\" ]")).containsExactly(Protocol.TCP, Protocol.HTTPS); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index 049f87ae84625..810a56c11b8d1 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -65,6 +65,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.CaseFormat; import com.google.common.collect.ImmutableList; import io.reactivex.subscribers.TestSubscriber; import org.apache.commons.lang3.ObjectUtils; @@ -148,13 +149,15 @@ protected static CosmosContainer getSharedSinglePartitionCosmosContainer(CosmosC preferredLocations = immutableListOrNull(parsePreferredLocation(TestConfigurations.PREFERRED_LOCATIONS)); protocols = ObjectUtils.defaultIfNull(immutableListOrNull(parseProtocols(TestConfigurations.PROTOCOLS)), ImmutableList.of(Protocol.HTTPS, Protocol.TCP)); - } - protected TestSuiteBase() { + // Object mapper configurations objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); + } + + protected TestSuiteBase() { logger.debug("Initializing {} ...", this.getClass().getSimpleName()); } @@ -787,11 +790,8 @@ public static Object[][] clientBuildersWithSessionConsistency() { private static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { - for (ConsistencyLevel consistencyLevel : ConsistencyLevel.values()) { - if (consistencyLevel.toString().toLowerCase().equals(consistency.toLowerCase())) { - return consistencyLevel; - } - } + consistency = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency).trim(); + return ConsistencyLevel.valueOf(consistency); } logger.error("INVALID configured test consistency [{}].", consistency); @@ -816,10 +816,14 @@ static List parseProtocols(String protocols) { if (StringUtils.isEmpty(protocols)) { return null; } - protocols = protocols.toUpperCase(); + List protocolList = new ArrayList<>(); try { - return objectMapper.readValue(protocols, new TypeReference>() { + List protocolStrings = objectMapper.readValue(protocols, new TypeReference>() { }); + for(String protocol : protocolStrings) { + protocolList.add(Protocol.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, protocol))); + } + return protocolList; } catch (Exception e) { logger.error("INVALID configured test protocols [{}].", protocols); throw new IllegalStateException("INVALID configured test protocols " + protocols); @@ -895,10 +899,13 @@ static List parseDesiredConsistencies(String consistencies) { if (StringUtils.isEmpty(consistencies)) { return null; } - consistencies = consistencies.toUpperCase(); + List consistencyLevels = new ArrayList<>(); try { - return objectMapper.readValue(consistencies, new TypeReference>() { - }); + List consistencyStrings = objectMapper.readValue(consistencies, new TypeReference>() {}); + for(String consistency : consistencyStrings) { + consistencyLevels.add(ConsistencyLevel.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency))); + } + return consistencyLevels; } catch (Exception e) { logger.error("INVALID consistency test desiredConsistencies [{}].", consistencies); throw new IllegalStateException("INVALID configured test desiredConsistencies " + consistencies); From 389c53f57e49ec373b62cb34d7f8c9260c99add2 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Thu, 13 Jun 2019 16:17:14 -0700 Subject: [PATCH 43/85] Added few more test cases for Parsing env variables --- .../java/com/azure/data/cosmos/rx/ParsingEnvTest.java | 10 ++++++++++ .../java/com/azure/data/cosmos/rx/TestSuiteBase.java | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java index 2b19bb49b3efc..b6416e5371c37 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java @@ -33,6 +33,7 @@ public class ParsingEnvTest { @Test(groups = "unit") public void parseDesiredConsistencies() { + assertThat(TestSuiteBase.parseDesiredConsistencies("[ \"BoundedStaleness\" ]")).containsExactly(ConsistencyLevel.BOUNDED_STALENESS); assertThat(TestSuiteBase.parseDesiredConsistencies("[ \"Session\" , \"Strong\" ]")).containsExactly( ConsistencyLevel.SESSION, ConsistencyLevel.STRONG); } @@ -48,6 +49,15 @@ public void lowerConsistencies() { .containsExactly(ConsistencyLevel.SESSION, ConsistencyLevel.CONSISTENT_PREFIX, ConsistencyLevel.EVENTUAL); } + @Test(groups = "unit") + public void parseAccountConsistency() { + assertThat(TestSuiteBase.parseConsistency("Strong")).isEqualTo(ConsistencyLevel.STRONG); + assertThat(TestSuiteBase.parseConsistency("Session")).isEqualTo(ConsistencyLevel.SESSION); + assertThat(TestSuiteBase.parseConsistency("BoundedStaleness")).isEqualTo(ConsistencyLevel.BOUNDED_STALENESS); + assertThat(TestSuiteBase.parseConsistency("ConsistentPrefix")).isEqualTo(ConsistencyLevel.CONSISTENT_PREFIX); + assertThat(TestSuiteBase.parseConsistency("Eventual")).isEqualTo(ConsistencyLevel.EVENTUAL); + } + @Test(groups = "unit") public void parsePreferredLocation() { assertThat(TestSuiteBase.parsePreferredLocation("[ \"central us\" , \"central us2\" ]")) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index 810a56c11b8d1..bda9d574de7fd 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -788,7 +788,7 @@ public static Object[][] clientBuildersWithSessionConsistency() { }; } - private static ConsistencyLevel parseConsistency(String consistency) { + static ConsistencyLevel parseConsistency(String consistency) { if (consistency != null) { consistency = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, consistency).trim(); return ConsistencyLevel.valueOf(consistency); From b5d2dc17bc1746ec65e0c487e61cf1cd341eeb0e Mon Sep 17 00:00:00 2001 From: mbhaskar Date: Fri, 14 Jun 2019 13:46:18 -0700 Subject: [PATCH 44/85] Mbhaskar/conflict api (#186) * Conflict API * Changing test to reflect new changes in testsuitebase --- .../com/azure/data/cosmos/CosmosConflict.java | 98 +++++++++++++++++ .../data/cosmos/CosmosConflictProperties.java | 101 ++++++++++++++++++ .../cosmos/CosmosConflictRequestOptions.java | 31 ++++++ .../data/cosmos/CosmosConflictResponse.java | 58 ++++++++++ .../azure/data/cosmos/CosmosContainer.java | 38 +++++++ .../data/cosmos/rx/CosmosConflictTest.java | 99 +++++++++++++++++ 6 files changed, 425 insertions(+) create mode 100644 sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java create mode 100644 sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java create mode 100644 sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java create mode 100644 sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java create mode 100644 sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java new file mode 100644 index 0000000000000..9665be3ece196 --- /dev/null +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java @@ -0,0 +1,98 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +import com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper; +import hu.akarnokd.rxjava.interop.RxJavaInterop; +import reactor.adapter.rxjava.RxJava2Adapter; +import reactor.core.publisher.Mono; + +public class CosmosConflict extends CosmosResource { + + private CosmosContainer container; + + /** + * Constructor + * @param id the conflict id + * @param container the container + */ + CosmosConflict(String id, CosmosContainer container) { + super(id); + this.container = container; + } + + /** + * Reads a conflict. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the read conflict. + * In case of failure the {@link Mono} will error. + * + * @param options the request options. + * @return a {@link Mono} containing the single resource response with the read conflict or an error. + */ + public Mono read(CosmosConflictRequestOptions options){ + if(options == null){ + options = new CosmosConflictRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.container.getDatabase() + .getDocClientWrapper() + .readConflict(getLink(), requestOptions) + .map(response -> new CosmosConflictResponse(response, container)) + .toSingle())); + + } + + /** + * Reads all conflicts in a document collection. + *

+ * After subscription the operation will be performed. + * The {@link Mono} will contain one or several feed response pages of the read conflicts. + * In case of failure the {@link Mono} will error. + * + * @param options the feed options. + * @return an {@link Mono} containing one or several feed response pages of the read conflicts or an error. + */ + public Mono delete(CosmosConflictRequestOptions options){ + if(options == null){ + options = new CosmosConflictRequestOptions(); + } + RequestOptions requestOptions = options.toRequestOptions(); + return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.container.getDatabase() + .getDocClientWrapper() + .deleteConflict(getLink(), requestOptions) + .map(response -> new CosmosConflictResponse(response, container)) + .toSingle())); + } + + @Override + protected String URIPathSegment() { + return ChangeFeedHelper.Paths.CONFLICTS_PATH_SEGMENT; + } + + @Override + protected String parentLink() { + return this.container.getLink(); + } +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java new file mode 100644 index 0000000000000..fc12eaf29d9cf --- /dev/null +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java @@ -0,0 +1,101 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.Strings; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.stream.Collectors; + +public class CosmosConflictProperties extends Resource { + + /** + * Initialize a conflict object. + */ + CosmosConflictProperties() { + super(); + } + + /** + * Initialize a conflict object from json string. + * + * @param jsonString the json string that represents the conflict. + */ + CosmosConflictProperties(String jsonString) { + super(jsonString); + } + + /** + * Gets the operation kind. + * + * @return the operation kind. + */ + public String getOperationKind() { + return super.getString(Constants.Properties.OPERATION_TYPE); + } + + /** + * Gets the type of the conflicting resource. + * + * @return the resource type. + */ + public String getResouceType() { + return super.getString(Constants.Properties.RESOURCE_TYPE); + } + + /** + * Gets the resource ID for the conflict in the Azure Cosmos DB service. + * @return resource Id for the conflict. + */ + public String getSourceResourceId() { + return super.getString(Constants.Properties.SOURCE_RESOURCE_ID); + } + + /** + * Gets the conflicting resource in the Azure Cosmos DB service. + * @param the type of the object. + * @param klass The returned type of conflicting resource. + * @return The conflicting resource. + */ + public T getResource(Class klass) { + String resourceAsString = super.getString(Constants.Properties.CONTENT); + + if (!Strings.isNullOrEmpty(resourceAsString)) { + try { + return klass.getConstructor(String.class).newInstance(resourceAsString); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException | NoSuchMethodException | SecurityException e) { + throw new IllegalStateException("Failed to instantiate class object.", e); + } + } else { + return null; + } + } + + static List getFromV2Results(List results) { + return results.stream().map(conflict -> new CosmosConflictProperties(conflict.toJson())) + .collect(Collectors.toList()); + } +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java new file mode 100644 index 0000000000000..cf969dac2ea2d --- /dev/null +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java @@ -0,0 +1,31 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +public class CosmosConflictRequestOptions extends CosmosRequestOptions{ + + @Override + protected RequestOptions toRequestOptions() { + return super.toRequestOptions(); + } +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java new file mode 100644 index 0000000000000..daa2d69278fbd --- /dev/null +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java @@ -0,0 +1,58 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +public class CosmosConflictResponse extends CosmosResponse { + private CosmosContainer container; + private CosmosConflict conflictClient; + + public CosmosConflictResponse(ResourceResponse response, CosmosContainer container) { + super(response); + if(response.getResource() == null){ + super.resourceSettings(null); + }else{ + super.resourceSettings(new CosmosConflictProperties(response.getResource().toJson())); + conflictClient = new CosmosConflict(response.getResource().id(), container); + } + } + + CosmosContainer getContainer() { + return container; + } + + /** + * Get conflict client + * @return the cosmos conflict client + */ + public CosmosConflict getConflict() { + return conflictClient; + } + + /** + * Get conflict properties object representing the resource on the server + * @return the conflict properties + */ + public CosmosConflictProperties getConflictProperties() { + return resourceSettings(); + } +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index 1e067bfaada93..39dbad4052aae 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -669,6 +669,44 @@ public CosmosTrigger getTrigger(String id){ return new CosmosTrigger(id, this); } + /** + * Lists all the conflicts in the container + * + * @param options the feed options + * @return a {@link Flux} containing one or several feed response pages of the obtained conflicts or an error. + */ + public Flux> listConflicts(FeedOptions options) { + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + .readConflicts(getLink(), options) + .map(response -> BridgeInternal.createFeedResponse(CosmosConflictProperties.getFromV2Results(response.results()), + response.responseHeaders())))); + } + + /** + * Queries all the conflicts in the container + * + * @param query the query + * @param options the feed options + * @return a {@link Flux} containing one or several feed response pages of the obtained conflicts or an error. + */ + public Flux> queryConflicts(String query, FeedOptions options) { + return RxJava2Adapter.flowableToFlux( + RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + .queryConflicts(getLink(), query, options) + .map(response -> BridgeInternal.createFeedResponse(CosmosConflictProperties.getFromV2Results(response.results()), + response.responseHeaders())))); + } + + /** + * Gets a CosmosConflict object without making a service call + * @param id id of the cosmos conflict + * @return a cosmos conflict + */ + public CosmosTrigger getConflict(String id){ + return new CosmosTrigger(id, this); + } + /** * Gets the throughput of the container * diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java new file mode 100644 index 0000000000000..2f42a575e7038 --- /dev/null +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java @@ -0,0 +1,99 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.rx; + +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosConflictProperties; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.rx.TestSuiteBase; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import reactor.core.publisher.Flux; + +import java.util.Iterator; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CosmosConflictTest extends TestSuiteBase { + + private CosmosContainer createdCollection; + + private CosmosClient client; + + @Factory(dataProvider = "clientBuilders") + public CosmosConflictTest(CosmosClientBuilder clientBuilder) { + super(clientBuilder); + } + + @Test(groups = {"simple"}, timeOut = TIMEOUT) + public void readConflicts_toBlocking_toIterator() { + + int requestPageSize = 3; + FeedOptions options = new FeedOptions(); + options.maxItemCount(requestPageSize); + + Flux> conflictReadFeedFlux = createdCollection.listConflicts(options); + + Iterator> it = conflictReadFeedFlux.toIterable().iterator(); + + int expectedNumberOfConflicts = 0; + + int numberOfResults = 0; + while (it.hasNext()) { + FeedResponse page = it.next(); + String pageSizeAsString = page.responseHeaders().get(HttpConstants.HttpHeaders.ITEM_COUNT); + assertThat(pageSizeAsString).isNotNull(); + // assertThat("header item count must be present", pageSizeAsString, notNullValue()); + int pageSize = Integer.valueOf(pageSizeAsString); + // Assert that Result size must match header item count + assertThat(page.results().size()).isEqualTo(pageSize); + numberOfResults += pageSize; + } + assertThat(numberOfResults).isEqualTo(expectedNumberOfConflicts); + } + + + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) + public void beforeClass() { + client = clientBuilder().build(); + createdCollection = getSharedMultiPartitionCosmosContainer(client); + } + + @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { + safeClose(client); + } + + @BeforeMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) + public void beforeMethod() { + safeClose(client); + client = clientBuilder().build(); + } +} From 7b0dc3c0239e2af2ca769c4a700687b64deeb162 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Fri, 21 Jun 2019 15:58:37 -0700 Subject: [PATCH 45/85] V3 store consistency layer (#194) * inital commit for V3 port from vsts to github * Hash v2 for SDK v3 bumped version to 3.0.0-beta-3 for release * Modified Pom file to copy jar files to required location * updated sdk-version property * removed additions to pom * Removing unused code Changing version to 3.0.0-SNAPSHOT * Initial check in with reactor netty library * Initial commit for Non partitioned collection support for V3 async Java SDK * updated git ignore * updated git ignore * removed conflict markers in comments * removed unnecessary files * Removed public constructor that took PartitionKeyInternal * fixed javadoc errors * Work In Progress * Work in progress * Work In Progress, Added Reactor Netty Client and other interfaces for Reactor HTTP Client * Reverted test configuration: * Fixed Gateway Store Model Test * Removed unused classes, added headers to new classes. Added configuration to Reactor Netty Http Client * Implemented Reactor HTTP Client for HttpTransportClient * Fixed HttpTransportClient store response subscribe * Removed unused code, removed some rxnetty usages * Fixed Proxy Tests with correct log level for reactor netty client * Fixed Gateaway Address Cache Tests * Fixed test cases, optimized imports, and other refactoring changes * Removed propogating error, instead just throw the error * Storing Connection provider to close resources later * Fixed empty body issue with Flux not allowing null values * Disposing just connection provider on http client shutdown * increased used memory limit for document leak resource test. Fix it later * Incorporated port in Http Request * Replacing read and write time out handlers with idle state handlers * Removing experimental feature of pooled connection timeout * initial commit for fixing tetss (will break) * Removed timeout feature * Calling http client shutdown in HttpTransportClient * Fixed Document resource leak test by closing the channel when done * Experimenting changes * Commenting out old ssl provider * Setting ssl timeout explicitly * Trying out default ssl * Trying out default ssl * Trying out ssl config * Trying out default ssl * Using vanila ssl * fixed testsuitebase * Improving the configuration for http client * Merging v3_reactor_netty_client_experiment changes * Reverting Test Configurations change * Implemented code review suggestions as well as some optimizations and refactoring * Handling delete operation * Fixing Delete operation * Refactoring CosmosClient adding a Builder Removed cosmos configuration Adding getters for scripts Adding CosmosUser Changing Options to composition * WIP: Work in progress * - Added CosmosUser, get APIs for scripts - Removed CosmosConfiguration and moved builder to CosmosClient * Added retry utility for Backoff retry utility * - Ported Cosmos item changes * fixed more tests * Minor refactoring Adding listUsers and queryUsers * Compilation work. Work in progress * Refactoring in Reactor Netty Client: * fixed database tests * Fixed RxGatewayStoreModelTests * Fixed Store reader, consistency reader, writer, address selector test cases * fixed more tests * Replaced Func1 with java Function * - Fixed more tests - rx.internal tests run using asyncDocumentClient * Updated store and consistency reader writers, Collection caches, partition caches, helpers, address resolvers, global endpoint managers, retry policies with reactor-core changes * Updated query contexts, document service requests, cosmos client changes * Fixed bechmarks, and some tests in commons * fixed more tests * fixed more tests. commented out some tests for compilation * Implementing PR comments * Fixed Direct Implementation test cases * Refactoring internal tests to Reactor * Work in progress, fixing location cache test * Fixing Async benchmark after Mo's changes * Fixed Examples source code and test cases * Fixing javadoc warnings * Refactoring internal query tests to Reactor * Refactoring gateway tests to Reactor * Removed unused code, refactored to use internal test suite base * Fixed concurrency issue with internal test suite base, imported internal test suite base in rx.internal tests * Minor changes, removed invalid usage of TransportClient * Fixed gateway tests, removed verbose test subscriber, using basic test subscriber for now * Handling IO Exception for create attachment and media. Fixing Consistency and Retry Create Document tests * Fixing typo in doc * Work in progress * reverted changes to examples utils * Added paginator prototype code * Merging V3 * Code-complete draft port to reactor. The Direct TCP-related code compiles and is not yet testable because other significant portions of the code do not currently compile. * Code-complete draft port to reactor. The Direct TCP-related code compiles and is not yet testable because other significant portions of the code do not currently compile. * Renamed Reactor Transport Client to Transport Client, removed rx.Observable and rx.Single usages completely * fixed more tests made shared resources private * Addressed some error handling ommissions in RntbdRequestManager and verified locally on the V2 branch that the long test suite passes. * Fixed more tests to use getSharedDatabase and similar methods * Addressed some error handling ommissions in RntbdRequestManager and verified locally on the V2 branch that the long test suite passes. * Fixed buffer size issue * Added Cosmos Request options * Renamed COSMOS.PROTOCOL as cosmos.directModeProtocol and move ConfigsTests to the package that Configs is defined * Fixing tests and refactored the way to get values * Icreased Ssl handshake timeout for reactor netty client * Ensured that our dependency on org.hamcreate:hamcrest-all:1.3 is respected by mockito which brings in hacrest-all:1.1. Also: sorted dependency version properties and dependency lists. * Addressed RntbdTransportClient test faiures * Minor test fixes * We no longer skip the DocumentClientResourceLeakTest when Direct TCP is in use * We no longer permit VeryLargeDocumentQueryTest to fail when Direct TCP is in use. Also improved logger.info messages in DocumentClientResourceLeakTest * We no longer permit DCDocumentCrudTest.crossPartitionQuery to fail when Direct TCP is in use. * We no longer permit BackPressureCrossPartition.query to fail when Direct TCP is in use. * skipped tcp tests * removed unused imports * Resolves a long-standing TODO: Ensure that the Configs instance created by DirectHttpsClientUnderTest specifies Protocol.Https (now that Direct TCP is the default connection mode) * changes to ConsistencyLevel * TestSuiteBase.beforeMethod correctly logs the connection mode: Direct Tcp, Direct Https, or Gateway Https * Merged enable TCP default protocol changes * Fixed Address Resolver Tests * Disabling connection pool exhausted tests * Fixing Config Tests * removed changes to DocumentCrudTests edited manner in which ConsistencyLevel.toString is implemented * removed unused import * reverted changes to documentcrud tests * fixed failing test * made more ConsistencyLevel.name -> toString changes * changed line endings * Removed rx Composite Exception and used reactor Exceptions utility class to handle multiple exceptions * Made more changes to enums removed cosmos tests * more enum fixes * more enum changes * Test tweaks * Made more enum changes * fixed line endings in includepathtest * Fixed pagination and order by utils bugs * Swapped rx Http Client with Reactor Http Client in Cosmos Partition Key Tests * Removed rx java dependency * Fixing tests * Removed throws Exception and unused imports * Optimized imports in Microsoft style * Added parallel run code for bulk insert blocking method in Test Suite Base * Minor test fixes * Trying default Http Client * re-using https client * Disabling document resource leak test * Fixing up schedulers * fixed CosmosPartitionKeyTests and ConsistencyTests null pointer issues * Added logging to netty client and fixed logger category * Fixing spy wire test * fixed failing tests * Removing unused imports * Minor test changes * Removed usages of bodyAsString method from http response as its not working correctly, implemented toString to convert byteBuf flux to Mono string * Increased timeout * Replaced flux with mono across consistency layer to avoid confusion * Reverting test configurations changes * Fixed Parallel Document Query Context * Fixed Protocol tests * Replaced exceptions by Mono / Flux Error * Incresaed wait to capture requests * Added block instead of subscribe to capture response * Fixed ReadMyWrites test with emitting just one value * Modified the order of client builders and reverted flux / mono change for consistency stack * Fixed Read my writes workflow * Removed unnecessary stack trace * Fixed Benchmarks to use BaseSubscriber * Adding conflict api (#192) Fixing Permission tests Making id method of Resource package private and adding id on individual resource classes to enable fluent composition * Removed unused ConfigsTests.java class * Fixed Read latency and write latency benchmarks * Fixed metrics version in parent pom.xml * Revised DocumentCrudTest and TestSuiteBase to address test breaks * Using Step Verifier, removed RetryAnalyzer * POM + test tweaks. * Eliminating some tests to test fast integration tests * Reverting the experiment * Fixed test break (see changes to CosmosPartitionKeyTests), tidied some test code (see changes to StoredProcedureCrudTest) and deleted two extraneous files * Removed unnecessary call * Code review comments --- benchmark/pom.xml | 11 +- .../data/cosmos/benchmark/AsyncBenchmark.java | 68 +- .../cosmos/benchmark/AsyncMixedBenchmark.java | 12 +- .../cosmos/benchmark/AsyncQueryBenchmark.java | 27 +- .../AsyncQuerySinglePartitionMultiple.java | 12 +- .../cosmos/benchmark/AsyncReadBenchmark.java | 47 +- .../cosmos/benchmark/AsyncWriteBenchmark.java | 47 +- .../data/cosmos/benchmark/DocDBUtils.java | 4 +- .../cosmos/benchmark/ReadMyWriteWorkflow.java | 42 +- .../ReadMyWritesConsistencyTest.java | 15 +- .../azure/data/cosmos/benchmark/Utils.java | 12 +- .../data/cosmos/benchmark/WorkflowTest.java | 6 +- .../azure/data/cosmos/DatabaseForTest.java | 16 +- .../HttpClientUnderTestWrapper.java | 37 +- .../cosmos/rx/FeedResponseListValidator.java | 2 +- commons/pom.xml | 49 +- .../data/cosmos/CosmosItemProperties.java | 11 + .../cosmos/CosmosStoredProcedureSettings.java | 10 + .../data/cosmos/CosmosTriggerSettings.java | 11 + .../CosmosUserDefinedFunctionSettings.java | 10 + .../java/com/azure/data/cosmos/Database.java | 10 + .../java/com/azure/data/cosmos/Document.java | 10 + .../azure/data/cosmos/DocumentCollection.java | 10 + .../azure/data/cosmos/PartitionKeyRange.java | 10 + .../com/azure/data/cosmos/Permission.java | 10 + .../java/com/azure/data/cosmos/Resource.java | 2 +- .../azure/data/cosmos/StoredProcedure.java | 10 + .../main/java/com/azure/data/cosmos/User.java | 10 + .../directconnectivity/GoneException.java | 28 +- .../cosmos/directconnectivity/HttpUtils.java | 28 +- .../RequestTimeoutException.java | 22 +- .../cosmos/internal/BadRequestException.java | 16 +- .../azure/data/cosmos/internal/Configs.java | 6 + .../cosmos/internal/HttpClientFactory.java | 172 ---- .../InternalServerErrorException.java | 28 +- .../internal/RxDocumentServiceRequest.java | 33 +- .../internal/http/BufferedHttpResponse.java | 92 ++ .../data/cosmos/internal/http/HttpClient.java | 61 ++ .../internal/http/HttpClientConfig.java | 85 ++ .../data/cosmos/internal/http/HttpHeader.java | 85 ++ .../cosmos/internal/http/HttpHeaders.java | 154 ++++ .../cosmos/internal/http/HttpRequest.java | 225 +++++ .../cosmos/internal/http/HttpResponse.java | 154 ++++ .../internal/http/ReactorNettyClient.java | 198 ++++ .../directconnectivity/HttpUtilsTest.java | 27 +- .../data/cosmos/internal/ConfigsTests.java | 2 +- .../RxDocumentServiceRequestTest.java | 6 +- .../directconnectivity/AddressResolver.java | 245 +++-- .../directconnectivity/AddressSelector.java | 26 +- .../BarrierRequestHelper.java | 10 +- .../directconnectivity/ConflictException.java | 12 +- .../directconnectivity/ConsistencyReader.java | 144 ++- .../directconnectivity/ConsistencyWriter.java | 269 +++--- .../cosmos/directconnectivity/ErrorUtils.java | 30 +- .../ForbiddenException.java | 20 +- .../GatewayAddressCache.java | 119 +-- .../GatewayServiceConfigurationReader.java | 71 +- .../GoneAndRetryWithRetryPolicy.java | 14 +- .../directconnectivity/HttpClientUtils.java | 36 +- .../HttpTransportClient.java | 526 ++++++----- .../directconnectivity/IAddressCache.java | 4 +- .../directconnectivity/IAddressResolver.java | 4 +- .../directconnectivity/IStoreClient.java | 17 +- .../directconnectivity/LockedException.java | 12 +- .../MethodNotAllowedException.java | 16 +- .../PartitionKeyRangeGoneException.java | 16 +- .../PreconditionFailedException.java | 12 +- .../directconnectivity/QuorumReader.java | 846 +++++++++--------- .../ReplicatedResourceClient.java | 32 +- .../RequestEntityTooLargeException.java | 12 +- .../RequestRateTooLargeException.java | 16 +- .../directconnectivity/ResponseUtils.java | 90 +- .../RetryWithException.java | 14 +- .../RntbdTransportClient.java | 39 +- .../directconnectivity/ServerStoreModel.java | 12 +- .../ServiceUnavailableException.java | 16 +- .../directconnectivity/StoreClient.java | 25 +- .../directconnectivity/StoreReader.java | 164 ++-- .../directconnectivity/TransportClient.java | 9 +- .../UnauthorizedException.java | 14 +- .../AddressResolverTest.java | 186 ++-- .../AddressSelectorTest.java | 18 +- .../AddressSelectorWrapper.java | 26 +- .../ConsistencyReaderTest.java | 52 +- .../ConsistencyWriterTest.java | 52 +- .../GatewayServiceConfiguratorReaderMock.java | 4 +- .../GoneAndRetryWithRetryPolicyTest.java | 31 +- .../HttpClientMockWrapper.java | 117 +-- .../HttpTransportClientTest.java | 71 +- .../PartitionKeyInternalTest.java | 28 +- .../directconnectivity/QuorumReaderTest.java | 34 +- ...catedResourceClientPartitionSplitTest.java | 42 +- .../ReplicatedResourceClientTest.java | 20 +- .../RntbdTransportClientTest.java | 62 +- .../StoreReaderDotNetTest.java | 172 ++-- .../directconnectivity/StoreReaderTest.java | 108 +-- .../StoreReaderUnderTest.java | 8 +- .../TransportClientWrapper.java | 20 +- .../WebExceptionUtilityTest.java | 4 - .../data/cosmos/internal/RetryUtilsTest.java | 70 +- examples/pom.xml | 7 - .../azure/data/cosmos/examples/BasicDemo.java | 2 +- .../rx/examples/multimaster/Helpers.java | 28 +- .../multimaster/samples/ConflictWorker.java | 114 +-- .../samples/MultiMasterScenario.java | 8 +- .../examples/multimaster/samples/Worker.java | 32 +- .../examples/CollectionCRUDAsyncAPITest.java | 69 +- .../cosmos/rx/examples/ConflictAPITest.java | 36 +- .../rx/examples/DatabaseCRUDAsyncAPITest.java | 62 +- .../rx/examples/DocumentCRUDAsyncAPITest.java | 106 ++- .../examples/DocumentQueryAsyncAPITest.java | 106 +-- .../rx/examples/InMemoryGroupbyTest.java | 37 +- .../rx/examples/OfferCRUDAsyncAPITest.java | 2 +- .../examples/StoredProcedureAsyncAPITest.java | 8 +- .../cosmos/rx/examples/TokenResolverTest.java | 36 +- .../rx/examples/UniqueIndexAsyncAPITest.java | 18 +- .../azure/data/cosmos/rx/examples/Utils.java | 10 +- gateway/pom.xml | 13 + .../DatabaseAccountManagerInternal.java | 4 +- .../WebExceptionUtility.java | 4 - .../cosmos/internal/BackoffRetryUtility.java | 81 +- ...ringSessionContainerClientRetryPolicy.java | 8 +- .../cosmos/internal/ClientRetryPolicy.java | 20 +- .../ConnectionPoolExhaustedRetry.java | 87 -- .../internal/GlobalEndpointManager.java | 89 +- .../internal/ICollectionRoutingMapCache.java | 6 +- .../internal/IDocumentClientRetryPolicy.java | 6 +- .../data/cosmos/internal/IRetryPolicy.java | 4 +- .../cosmos/internal/IRoutingMapProvider.java | 8 +- .../internal/InvalidPartitionException.java | 6 +- .../InvalidPartitionExceptionRetryPolicy.java | 8 +- .../cosmos/internal/NotFoundException.java | 10 +- .../cosmos/internal/ObservableHelper.java | 27 +- .../PartitionIsMigratingException.java | 6 +- .../PartitionKeyMismatchRetryPolicy.java | 8 +- .../PartitionKeyRangeGoneRetryPolicy.java | 40 +- ...PartitionKeyRangeIsSplittingException.java | 6 +- ...enameCollectionAwareClientRetryPolicy.java | 27 +- .../internal/ResourceThrottleRetryPolicy.java | 8 +- .../data/cosmos/internal/RetryUtils.java | 161 ++-- .../cosmos/internal/RxGatewayStoreModel.java | 357 ++++---- .../data/cosmos/internal/RxStoreModel.java | 4 +- .../internal/WebExceptionRetryPolicy.java | 10 +- .../cosmos/internal/caches/AsyncCache.java | 43 +- .../cosmos/internal/caches/AsyncLazy.java | 26 +- .../caches/IPartitionKeyRangeCache.java | 10 +- .../caches/RxClientCollectionCache.java | 18 +- .../internal/caches/RxCollectionCache.java | 87 +- ...ggregateDocumentQueryExecutionContext.java | 12 +- .../DefaultDocumentQueryExecutionContext.java | 26 +- .../internal/query/DocumentProducer.java | 66 +- .../DocumentQueryExecutionContextBase.java | 16 +- .../DocumentQueryExecutionContextFactory.java | 29 +- .../data/cosmos/internal/query/Fetcher.java | 23 +- .../internal/query/IDocumentQueryClient.java | 6 +- .../IDocumentQueryExecutionComponent.java | 4 +- .../query/IDocumentQueryExecutionContext.java | 4 +- .../query/OrderByDocumentProducer.java | 19 +- .../OrderByDocumentQueryExecutionContext.java | 46 +- .../cosmos/internal/query/OrderByUtils.java | 53 +- .../data/cosmos/internal/query/Paginator.java | 70 +- ...ParallelDocumentQueryExecutionContext.java | 66 +- ...llelDocumentQueryExecutionContextBase.java | 21 +- ...ipelinedDocumentQueryExecutionContext.java | 12 +- .../ProxyDocumentQueryExecutionContext.java | 60 +- .../TopDocumentQueryExecutionContext.java | 28 +- .../cosmos/internal/query/TriFunction.java | 23 + .../orderbyquery/OrderbyRowComparer.java | 3 +- .../routing/CollectionRoutingMap.java | 4 +- .../routing/InMemoryCollectionRoutingMap.java | 6 +- .../internal/ClientRetryPolicyTest.java | 27 +- ...eCollectionAwareClientRetryPolicyTest.java | 24 +- .../internal/RxGatewayStoreModelTest.java | 34 +- .../internal/caches/AsyncCacheTest.java | 36 +- .../internal/routing/LocationCacheTest.java | 16 +- pom.xml | 10 +- sdk/CosmosConflict | 0 sdk/pom.xml | 37 - .../data/cosmos/AsyncDocumentClient.java | 625 +++++++------ .../com/azure/data/cosmos/CosmosClient.java | 19 +- .../com/azure/data/cosmos/CosmosConflict.java | 14 +- .../data/cosmos/CosmosConflictProperties.java | 10 +- .../cosmos/CosmosConflictRequestOptions.java | 2 +- .../data/cosmos/CosmosConflictResponse.java | 6 +- .../azure/data/cosmos/CosmosContainer.java | 120 +-- .../com/azure/data/cosmos/CosmosDatabase.java | 64 +- .../com/azure/data/cosmos/CosmosItem.java | 15 +- .../azure/data/cosmos/CosmosPermission.java | 14 +- .../data/cosmos/CosmosPermissionResponse.java | 4 +- .../data/cosmos/CosmosPermissionSettings.java | 31 +- .../data/cosmos/CosmosStoredProcedure.java | 59 +- .../com/azure/data/cosmos/CosmosTrigger.java | 49 +- .../com/azure/data/cosmos/CosmosUser.java | 41 +- .../cosmos/CosmosUserDefinedFunction.java | 49 +- .../azure/data/cosmos/CosmosUserSettings.java | 9 + .../internal/ChangeFeedContextClientImpl.java | 6 +- .../cosmos/internal/ChangeFeedQueryImpl.java | 18 +- .../cosmos/internal/RxDocumentClientImpl.java | 490 +++++----- .../caches/RxPartitionKeyRangeCache.java | 84 +- .../GlobalAddressResolver.java | 35 +- .../azure/data/cosmos/CosmosClientTest.java | 22 +- .../data/cosmos/CosmosPartitionKeyTests.java | 85 +- .../data/cosmos/CosmosResponseValidator.java | 25 + .../azure/data/cosmos/DocumentClientTest.java | 22 +- .../BarrierRequestHelperTest.java | 12 +- .../DCDocumentCrudTest.java | 16 +- .../GatewayAddressCacheTest.java | 151 ++-- ...GatewayServiceConfigurationReaderTest.java | 121 +-- .../ConnectionPoolExhaustedRetryTest.java | 85 -- .../cosmos/internal/ConsistencyTests1.java | 11 +- .../cosmos/internal/ConsistencyTests2.java | 101 ++- .../cosmos/internal/ConsistencyTestsBase.java | 127 +-- .../DocumentQuerySpyWireContentTest.java | 35 +- .../cosmos/internal/NetworkFailureTest.java | 6 +- .../data/cosmos/internal/ParallelAsync.java | 16 +- .../internal/RetryCreateDocumentTest.java | 120 ++- .../cosmos/internal/RetryThrottleTest.java | 29 +- .../internal/RxDocumentClientUnderTest.java | 41 +- .../data/cosmos/internal/SessionTest.java | 41 +- .../internal/SpyClientUnderTestFactory.java | 119 +-- .../data/cosmos/internal/TestSuiteBase.java | 173 ++-- .../GlobalAddressResolverTest.java | 26 +- .../directconnectivity/ReflectionUtils.java | 14 +- .../internal/query/DocumentProducerTest.java | 569 +++++------- .../cosmos/internal/query/FetcherTest.java | 28 +- .../data/cosmos/rx/AggregateQueryTests.java | 14 +- .../rx/BackPressureCrossPartitionTest.java | 5 +- .../data/cosmos/rx/BackPressureTest.java | 22 +- .../azure/data/cosmos/rx/ChangeFeedTest.java | 47 +- .../data/cosmos/rx/CosmosConflictTest.java | 7 +- .../rx/DocumentClientResourceLeakTest.java | 2 +- .../data/cosmos/rx/DocumentCrudTest.java | 104 +-- .../cosmos/rx/MultiOrderByQueryTests.java | 5 +- .../azure/data/cosmos/rx/OfferQueryTest.java | 16 +- .../data/cosmos/rx/OfferReadReplaceTest.java | 12 +- .../cosmos/rx/OrderbyDocumentQueryTest.java | 10 +- .../cosmos/rx/ParallelDocumentQueryTest.java | 26 +- .../data/cosmos/rx/PermissionCrudTest.java | 154 ++-- .../data/cosmos/rx/PermissionQueryTest.java | 14 +- .../data/cosmos/rx/ReadFeedOffersTest.java | 19 +- .../cosmos/rx/ReadFeedPermissionsTest.java | 11 +- .../data/cosmos/rx/ReadFeedPkrTests.java | 5 +- .../data/cosmos/rx/ResourceTokenTest.java | 38 +- .../cosmos/rx/StoredProcedureCrudTest.java | 60 +- .../azure/data/cosmos/rx/TestSuiteBase.java | 211 ++--- .../data/cosmos/rx/TokenResolverTest.java | 61 +- .../data/cosmos/rx/TriggerQueryTest.java | 12 +- .../cosmos/rx/VeryLargeDocumentQueryTest.java | 45 +- 248 files changed, 6673 insertions(+), 6600 deletions(-) delete mode 100644 commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java create mode 100644 commons/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java create mode 100644 commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java create mode 100644 commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java create mode 100644 commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java create mode 100644 commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java create mode 100644 commons/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java create mode 100644 commons/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java create mode 100644 commons/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java delete mode 100644 gateway/src/main/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetry.java create mode 100644 gateway/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java create mode 100644 sdk/CosmosConflict delete mode 100644 sdk/src/test/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetryTest.java diff --git a/benchmark/pom.xml b/benchmark/pom.xml index 0625c7d4c60ac..a4edcd0e7a072 100644 --- a/benchmark/pom.xml +++ b/benchmark/pom.xml @@ -150,11 +150,6 @@ ${netty-tcnative.version} linux-x86_64 - - io.reactivex - rxjava-guava - ${rxjava-guava.version} - log4j log4j @@ -181,6 +176,12 @@ ${assertj.version} test + + org.hamcrest + hamcrest-all + ${hamcrest.version} + test + org.testng testng diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java index c6cc58fa2625b..a8a22a5e548b6 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java @@ -1,17 +1,17 @@ /* * The MIT License (MIT) * Copyright (c) 2018 Microsoft Corporation - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -41,10 +41,11 @@ import com.codahale.metrics.jvm.GarbageCollectorMetricSet; import com.codahale.metrics.jvm.MemoryUsageGaugeSet; import org.apache.commons.lang3.RandomStringUtils; +import org.reactivestreams.Subscription; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Subscriber; +import reactor.core.publisher.BaseSubscriber; +import reactor.core.publisher.Flux; import java.net.InetSocketAddress; import java.time.Duration; @@ -74,11 +75,11 @@ abstract class AsyncBenchmark { AsyncBenchmark(Configuration cfg) { client = new AsyncDocumentClient.Builder() - .withServiceEndpoint(cfg.getServiceEndpoint()) - .withMasterKeyOrResourceToken(cfg.getMasterKey()) - .withConnectionPolicy(cfg.getConnectionPolicy()) - .withConsistencyLevel(cfg.getConsistencyLevel()) - .build(); + .withServiceEndpoint(cfg.getServiceEndpoint()) + .withMasterKeyOrResourceToken(cfg.getMasterKey()) + .withConnectionPolicy(cfg.getConnectionPolicy()) + .withConsistencyLevel(cfg.getConsistencyLevel()) + .build(); logger = LoggerFactory.getLogger(this.getClass()); @@ -89,7 +90,7 @@ abstract class AsyncBenchmark { concurrencyControlSemaphore = new Semaphore(cfg.getConcurrency()); configuration = cfg; - ArrayList> createDocumentObservables = new ArrayList<>(); + ArrayList> createDocumentObservables = new ArrayList<>(); if (configuration.getOperationType() != Operation.WriteLatency && configuration.getOperationType() != Operation.WriteThroughput @@ -105,13 +106,13 @@ abstract class AsyncBenchmark { newDoc.set("dataField3", dataFieldValue); newDoc.set("dataField4", dataFieldValue); newDoc.set("dataField5", dataFieldValue); - Observable obs = client.createDocument(collection.selfLink(), newDoc, null, false) - .map(ResourceResponse::getResource); + Flux obs = client.createDocument(collection.selfLink(), newDoc, null, false) + .map(ResourceResponse::getResource); createDocumentObservables.add(obs); } } - docsToRead = Observable.merge(createDocumentObservables, 100).toList().toBlocking().single(); + docsToRead = Flux.merge(Flux.fromIterable(createDocumentObservables), 100).collectList().block(); init(); if (configuration.isEnableJvmStats()) { @@ -123,14 +124,14 @@ abstract class AsyncBenchmark { if (configuration.getGraphiteEndpoint() != null) { final Graphite graphite = new Graphite(new InetSocketAddress(configuration.getGraphiteEndpoint(), configuration.getGraphiteEndpointPort())); reporter = GraphiteReporter.forRegistry(metricsRegistry) - .prefixedWith(configuration.getOperationType().name()) - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .filter(MetricFilter.ALL) - .build(graphite); + .prefixedWith(configuration.getOperationType().name()) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) + .build(graphite); } else { reporter = ConsoleReporter.forRegistry(metricsRegistry).convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS).build(); + .convertDurationsTo(TimeUnit.MILLISECONDS).build(); } } @@ -163,7 +164,7 @@ protected String getDocumentLink(Document doc) { } } - protected abstract void performWorkload(Subscriber subs, long i) throws Exception; + protected abstract void performWorkload(BaseSubscriber baseSubscriber, long i) throws Exception; private boolean shouldContinue(long startTimeMillis, long iterationCount) { Duration maxDurationTime = configuration.getMaxRunningTimeDuration(); @@ -199,14 +200,19 @@ void run() throws Exception { long i; for ( i = 0; shouldContinue(startTime, i); i++) { - Subscriber subs = new Subscriber() { + BaseSubscriber baseSubscriber = new BaseSubscriber() { + @Override + protected void hookOnSubscribe(Subscription subscription) { + super.hookOnSubscribe(subscription); + } @Override - public void onStart() { + protected void hookOnNext(T value) { + } @Override - public void onCompleted() { + protected void hookOnComplete() { successMeter.mark(); concurrencyControlSemaphore.release(); AsyncBenchmark.this.onSuccess(); @@ -218,25 +224,21 @@ public void onCompleted() { } @Override - public void onError(Throwable e) { + protected void hookOnError(Throwable throwable) { failureMeter.mark(); logger.error("Encountered failure {} on thread {}" , - e.getMessage(), Thread.currentThread().getName(), e); + throwable.getMessage(), Thread.currentThread().getName(), throwable); concurrencyControlSemaphore.release(); - AsyncBenchmark.this.onError(e); + AsyncBenchmark.this.onError(throwable); synchronized (count) { count.incrementAndGet(); count.notify(); } } - - @Override - public void onNext(T value) { - } }; - performWorkload(subs, i); + performWorkload(baseSubscriber, i); } synchronized (count) { @@ -247,7 +249,7 @@ public void onNext(T value) { long endTime = System.currentTimeMillis(); logger.info("[{}] operations performed in [{}] seconds.", - configuration.getNumberOfOperations(), (int) ((endTime - startTime) / 1000)); + configuration.getNumberOfOperations(), (int) ((endTime - startTime) / 1000)); reporter.report(); reporter.close(); diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java index df184c7ffa474..21c7809f2a859 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java @@ -29,9 +29,9 @@ import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.ResourceResponse; import org.apache.commons.lang3.RandomStringUtils; -import rx.Observable; -import rx.Subscriber; -import rx.schedulers.Schedulers; +import reactor.core.publisher.BaseSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; import java.util.Random; import java.util.UUID; @@ -50,8 +50,8 @@ class AsyncMixedBenchmark extends AsyncBenchmark { } @Override - protected void performWorkload(Subscriber subs, long i) throws InterruptedException { - Observable obs; + protected void performWorkload(BaseSubscriber documentBaseSubscriber, long i) throws InterruptedException { + Flux obs; if (i % 10 == 0 && i % 100 != 0) { String idString = uuid + i; @@ -86,6 +86,6 @@ protected void performWorkload(Subscriber subs, long i) throws Interru concurrencyControlSemaphore.acquire(); - obs.subscribeOn(Schedulers.computation()).subscribe(subs); + obs.subscribeOn(Schedulers.parallel()).subscribe(documentBaseSubscriber); } } diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java index 7fef7ef37a2d0..50132efdabc7c 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java @@ -27,10 +27,9 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.benchmark.Configuration.Operation; -import rx.Observable; -import rx.Subscriber; -import rx.schedulers.Schedulers; +import reactor.core.publisher.BaseSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; import java.util.Random; @@ -54,49 +53,49 @@ protected void onSuccess() { } @Override - protected void performWorkload(Subscriber> subs, long i) throws InterruptedException { + protected void performWorkload(BaseSubscriber> baseSubscriber, long i) throws InterruptedException { - Observable> obs; + Flux> obs; Random r = new Random(); FeedOptions options = new FeedOptions(); - if (configuration.getOperationType() == Operation.QueryCross) { + if (configuration.getOperationType() == Configuration.Operation.QueryCross) { int index = r.nextInt(1000); options.enableCrossPartitionQuery(true); String sqlQuery = "Select * from c where c._rid = \"" + docsToRead.get(index).resourceId() + "\""; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); - } else if (configuration.getOperationType() == Operation.QuerySingle) { + } else if (configuration.getOperationType() == Configuration.Operation.QuerySingle) { int index = r.nextInt(1000); String pk = docsToRead.get(index).getString("pk"); options.partitionKey(new PartitionKey(pk)); String sqlQuery = "Select * from c where c.pk = \"" + pk + "\""; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); - } else if (configuration.getOperationType() == Operation.QueryParallel) { + } else if (configuration.getOperationType() == Configuration.Operation.QueryParallel) { options.maxItemCount(10); options.enableCrossPartitionQuery(true); String sqlQuery = "Select * from c"; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); - } else if (configuration.getOperationType() == Operation.QueryOrderby) { + } else if (configuration.getOperationType() == Configuration.Operation.QueryOrderby) { options.maxItemCount(10); options.enableCrossPartitionQuery(true); String sqlQuery = "Select * from c order by c._ts"; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); - } else if (configuration.getOperationType() == Operation.QueryAggregate) { + } else if (configuration.getOperationType() == Configuration.Operation.QueryAggregate) { options.maxItemCount(10); options.enableCrossPartitionQuery(true); String sqlQuery = "Select value max(c._ts) from c"; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); - } else if (configuration.getOperationType() == Operation.QueryAggregateTopOrderby) { + } else if (configuration.getOperationType() == Configuration.Operation.QueryAggregateTopOrderby) { options.enableCrossPartitionQuery(true); String sqlQuery = "Select top 1 value count(c) from c order by c._ts"; obs = client.queryDocuments(getCollectionLink(), sqlQuery, options); - } else if (configuration.getOperationType() == Operation.QueryTopOrderby) { + } else if (configuration.getOperationType() == Configuration.Operation.QueryTopOrderby) { options.enableCrossPartitionQuery(true); String sqlQuery = "Select top 1000 * from c order by c._ts"; @@ -106,6 +105,6 @@ protected void performWorkload(Subscriber> subs, long i) } concurrencyControlSemaphore.acquire(); - obs.subscribeOn(Schedulers.computation()).subscribe(subs); + obs.subscribeOn(Schedulers.parallel()).subscribe(baseSubscriber); } } diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java index 5a7a3b703fdb0..665e55877a572 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java @@ -27,9 +27,9 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; -import rx.Observable; -import rx.Subscriber; -import rx.schedulers.Schedulers; +import reactor.core.publisher.BaseSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; class AsyncQuerySinglePartitionMultiple extends AsyncBenchmark> { @@ -56,11 +56,11 @@ protected void onSuccess() { } @Override - protected void performWorkload(Subscriber> subs, long i) throws InterruptedException { - Observable> obs = client.queryDocuments(getCollectionLink(), SQL_QUERY, options); + protected void performWorkload(BaseSubscriber> baseSubscriber, long i) throws InterruptedException { + Flux> obs = client.queryDocuments(getCollectionLink(), SQL_QUERY, options); concurrencyControlSemaphore.acquire(); - obs.subscribeOn(Schedulers.computation()).subscribe(subs); + obs.subscribeOn(Schedulers.parallel()).subscribe(baseSubscriber); } } diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java index 128e7e895a67a..90882abef8fb4 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java @@ -27,38 +27,42 @@ import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.benchmark.Configuration.Operation; import com.codahale.metrics.Timer; -import rx.Observable; -import rx.Subscriber; -import rx.schedulers.Schedulers; +import org.reactivestreams.Subscription; +import reactor.core.publisher.BaseSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; class AsyncReadBenchmark extends AsyncBenchmark> { - class LatencySubscriber extends Subscriber { + class LatencySubscriber extends BaseSubscriber { Timer.Context context; - Subscriber subscriber; + BaseSubscriber> baseSubscriber; - LatencySubscriber(Subscriber subscriber) { - this.subscriber = subscriber; + LatencySubscriber(BaseSubscriber> baseSubscriber) { + this.baseSubscriber = baseSubscriber; } @Override - public void onCompleted() { - context.stop(); - subscriber.onCompleted(); + protected void hookOnSubscribe(Subscription subscription) { + super.hookOnSubscribe(subscription); } @Override - public void onError(Throwable e) { + protected void hookOnNext(T value) { + } + + @Override + protected void hookOnComplete() { context.stop(); - subscriber.onError(e); + baseSubscriber.onComplete(); } @Override - public void onNext(T t) { - subscriber.onNext(t); + protected void hookOnError(Throwable throwable) { + context.stop(); + baseSubscriber.onError(throwable); } } @@ -67,22 +71,21 @@ public void onNext(T t) { } @Override - protected void performWorkload(Subscriber> subs, long i) throws InterruptedException { + protected void performWorkload(BaseSubscriber> baseSubscriber, long i) throws InterruptedException { int index = (int) (i % docsToRead.size()); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(docsToRead.get(index).id())); - Observable> obs = client.readDocument(getDocumentLink(docsToRead.get(index)), options); + Flux> obs = client.readDocument(getDocumentLink(docsToRead.get(index)), options); concurrencyControlSemaphore.acquire(); - if (configuration.getOperationType() == Operation.ReadThroughput) { - obs.subscribeOn(Schedulers.computation()).subscribe(subs); + if (configuration.getOperationType() == Configuration.Operation.ReadThroughput) { + obs.subscribeOn(Schedulers.parallel()).subscribe(baseSubscriber); } else { - LatencySubscriber> latencySubscriber = new LatencySubscriber<>( - subs); + LatencySubscriber> latencySubscriber = new LatencySubscriber<>(baseSubscriber); latencySubscriber.context = latency.time(); - obs.subscribeOn(Schedulers.computation()).subscribe(latencySubscriber); + obs.subscribeOn(Schedulers.parallel()).subscribe(latencySubscriber); } } } diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java index e723b4f1a0aad..a267c6f946566 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java @@ -25,12 +25,12 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.benchmark.Configuration.Operation; import com.codahale.metrics.Timer; import org.apache.commons.lang3.RandomStringUtils; -import rx.Observable; -import rx.Subscriber; -import rx.schedulers.Schedulers; +import org.reactivestreams.Subscription; +import reactor.core.publisher.BaseSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; import java.util.UUID; @@ -39,30 +39,34 @@ class AsyncWriteBenchmark extends AsyncBenchmark> { private final String uuid; private final String dataFieldValue; - class LatencySubscriber extends Subscriber { + class LatencySubscriber extends BaseSubscriber { Timer.Context context; - Subscriber subscriber; + BaseSubscriber> baseSubscriber; - LatencySubscriber(Subscriber subscriber) { - this.subscriber = subscriber; + LatencySubscriber(BaseSubscriber> baseSubscriber) { + this.baseSubscriber = baseSubscriber; } @Override - public void onCompleted() { - context.stop(); - subscriber.onCompleted(); + protected void hookOnSubscribe(Subscription subscription) { + super.hookOnSubscribe(subscription); } @Override - public void onError(Throwable e) { + protected void hookOnNext(T value) { + } + + @Override + protected void hookOnComplete() { context.stop(); - subscriber.onError(e); + baseSubscriber.onComplete(); } @Override - public void onNext(T t) { - subscriber.onNext(t); + protected void hookOnError(Throwable throwable) { + context.stop(); + baseSubscriber.onError(throwable); } } @@ -73,7 +77,7 @@ public void onNext(T t) { } @Override - protected void performWorkload(Subscriber> subs, long i) throws InterruptedException { + protected void performWorkload(BaseSubscriber> baseSubscriber, long i) throws InterruptedException { String idString = uuid + i; Document newDoc = new Document(); @@ -84,18 +88,17 @@ protected void performWorkload(Subscriber> subs, long newDoc.set("dataField3", dataFieldValue); newDoc.set("dataField4", dataFieldValue); newDoc.set("dataField5", dataFieldValue); - Observable> obs = client.createDocument(getCollectionLink(), newDoc, null, + Flux> obs = client.createDocument(getCollectionLink(), newDoc, null, false); concurrencyControlSemaphore.acquire(); - if (configuration.getOperationType() == Operation.WriteThroughput) { - obs.subscribeOn(Schedulers.computation()).subscribe(subs); + if (configuration.getOperationType() == Configuration.Operation.WriteThroughput) { + obs.subscribeOn(Schedulers.parallel()).subscribe(baseSubscriber); } else { - LatencySubscriber> latencySubscriber = new LatencySubscriber<>( - subs); + LatencySubscriber> latencySubscriber = new LatencySubscriber<>(baseSubscriber); latencySubscriber.context = latency.time(); - obs.subscribeOn(Schedulers.computation()).subscribe(latencySubscriber); + obs.subscribeOn(Schedulers.parallel()).subscribe(latencySubscriber); } } } diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java index 99b6a71ee9f80..f232625048cfa 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java @@ -40,7 +40,7 @@ static Database getDatabase(AsyncDocumentClient client, String databaseId) { FeedResponse feedResponsePages = client .queryDatabases(new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", databaseId))), null) - .toBlocking().single(); + .single().block(); if (feedResponsePages.results().isEmpty()) { throw new RuntimeException("cannot find datatbase " + databaseId); @@ -55,7 +55,7 @@ static DocumentCollection getCollection(AsyncDocumentClient client, String datab new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", new SqlParameterCollection(new SqlParameter("@id", collectionId))), null) - .toBlocking().single(); + .single().block(); if (feedResponsePages.results().isEmpty()) { throw new RuntimeException("cannot find collection " + collectionId); diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java index 132ee238a2b3d..97144ca747ffb 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java @@ -34,9 +34,9 @@ import com.azure.data.cosmos.internal.NotFoundException; import com.azure.data.cosmos.internal.Utils; import org.apache.commons.lang3.RandomUtils; -import rx.Observable; -import rx.Subscriber; -import rx.schedulers.Schedulers; +import reactor.core.publisher.BaseSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; import java.util.ArrayList; import java.util.Arrays; @@ -72,8 +72,8 @@ protected void init() { } @Override - protected void performWorkload(Subscriber subs, long i) throws Exception { - Observable obs; + protected void performWorkload(BaseSubscriber baseSubscriber, long i) throws Exception { + Flux obs; boolean readyMyWrite = RandomUtils.nextBoolean(); if (readyMyWrite) { // will do a write and immediately upon success will either @@ -86,14 +86,14 @@ protected void performWorkload(Subscriber subs, long i) throws Excepti // write a random document to cosmodb and update the cache. // then try to read the document which just was written obs = writeDocument() - .flatMap(d -> readDocument(d)); + .flatMap(this::readDocument); break; case 1: // write a random document to cosmodb and update the cache. // then try to query for the document which just was written obs = writeDocument() .flatMap(d -> singlePartitionQuery(d) - .switchIfEmpty(Observable.error(new NotFoundException( + .switchIfEmpty(Flux.error(new NotFoundException( "couldn't find my write in a single partition query!")))); break; case 2: @@ -101,7 +101,7 @@ protected void performWorkload(Subscriber subs, long i) throws Excepti // then try to query for the document which just was written obs = writeDocument() .flatMap(d -> xPartitionQuery(generateQuery(d)) - .switchIfEmpty(Observable.error(new NotFoundException( + .switchIfEmpty(Flux.error(new NotFoundException( "couldn't find my write in a cross partition query!")))); break; default: @@ -127,13 +127,13 @@ protected void performWorkload(Subscriber subs, long i) throws Excepti case 2: // randomly choose a document from the cache and do a single partition query obs = singlePartitionQuery(cache.get(cacheKey())) - .switchIfEmpty(Observable.error(new NotFoundException( + .switchIfEmpty(Flux.error(new NotFoundException( "couldn't find my cached write in a single partition query!"))); break; case 3: // randomly choose a document from the cache and do a cross partition query obs = xPartitionQuery(generateRandomQuery()) - .switchIfEmpty(Observable.error(new NotFoundException( + .switchIfEmpty(Flux.error(new NotFoundException( "couldn't find my cached write in a cross partition query!"))); break; default: @@ -144,18 +144,18 @@ protected void performWorkload(Subscriber subs, long i) throws Excepti concurrencyControlSemaphore.acquire(); - obs.subscribeOn(Schedulers.computation()).subscribe(subs); + obs.subscribeOn(Schedulers.parallel()).subscribe(baseSubscriber); } private void populateCache() { - ArrayList> list = new ArrayList<>(); + ArrayList> list = new ArrayList<>(); for (int i = 0; i < cacheSize; i++) { - Observable observable = writeDocument(i); + Flux observable = writeDocument(i); list.add(observable); } logger.info("PRE-populating {} documents ....", cacheSize); - Observable.merge(list, configuration.getConcurrency()).toCompletable().await(); + Flux.merge(Flux.fromIterable(list), configuration.getConcurrency()).then().block(); logger.info("Finished pre-populating {} documents", cacheSize); } @@ -164,7 +164,7 @@ private void populateCache() { * * @return Observable of document */ - private Observable writeDocument() { + private Flux writeDocument() { return writeDocument(null); } @@ -173,7 +173,7 @@ private Observable writeDocument() { * * @return Observable of document */ - private Observable writeDocument(Integer i) { + private Flux writeDocument(Integer i) { String idString = Utils.randomUUID().toString(); String randomVal = Utils.randomUUID().toString(); Document document = new Document(); @@ -197,7 +197,7 @@ private Observable writeDocument(Integer i) { * @param d document to be read * @return Observable of document */ - private Observable readDocument(Document d) { + private Flux readDocument(Document d) { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(d.getString(partitionKey))); @@ -234,13 +234,13 @@ private SqlQuerySpec generateRandomQuery() { * @param query to find document * @return Observable document */ - private Observable xPartitionQuery(SqlQuerySpec query) { + private Flux xPartitionQuery(SqlQuerySpec query) { FeedOptions options = new FeedOptions(); options.maxDegreeOfParallelism(-1); options.enableCrossPartitionQuery(true); return client.queryDocuments(getCollectionLink(), query, options) - .flatMap(p -> Observable.from(p.results())); + .flatMap(p -> Flux.fromIterable(p.results())); } /** @@ -250,7 +250,7 @@ private Observable xPartitionQuery(SqlQuerySpec query) { * @param d document to be queried for. * @return Observable document */ - private Observable singlePartitionQuery(Document d) { + private Flux singlePartitionQuery(Document d) { FeedOptions options = new FeedOptions(); options.partitionKey(new PartitionKey(d.get(partitionKey))); @@ -258,7 +258,7 @@ private Observable singlePartitionQuery(Document d) { QUERY_FIELD_NAME, d.getString(QUERY_FIELD_NAME))); return client.queryDocuments(getCollectionLink(), sqlQuerySpec, options) - .flatMap(p -> Observable.from(p.results())); + .flatMap(p -> Flux.fromIterable(p.results())); } /** diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java index 0ee1942d0ac05..ae2f758aeffcb 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java @@ -43,14 +43,13 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Observable; -import rx.schedulers.Schedulers; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -146,7 +145,7 @@ public void beforeClass() { collection = housekeepingClient.createCollection("dbs/" + database.id(), getCollectionDefinitionWithRangeRangeIndex(), options) - .toBlocking().single().getResource(); + .single().block().getResource(); housekeepingClient.close(); } @@ -197,20 +196,20 @@ DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { private void scheduleScaleUp(int delayStartInSeconds, int newThroughput) { AsyncDocumentClient housekeepingClient = Utils.housekeepingClient(); - Observable.timer(delayStartInSeconds, TimeUnit.SECONDS, Schedulers.newThread()).flatMap(aVoid -> { + Flux.just(0L).delayElements(Duration.ofSeconds(delayStartInSeconds), Schedulers.newSingle("ScaleUpThread")).flatMap(aVoid -> { // increase throughput to max for a single partition collection to avoid throttling // for bulk insert and later queries. return housekeepingClient.queryOffers( String.format("SELECT * FROM r WHERE r.offerResourceId = '%s'", collection.resourceId()) - , null).flatMap(page -> Observable.from(page.results())) - .first().flatMap(offer -> { + , null).flatMap(page -> Flux.fromIterable(page.results())) + .take(1).flatMap(offer -> { logger.info("going to scale up collection, newThroughput {}", newThroughput); offer.setThroughput(newThroughput); return housekeepingClient.replaceOffer(offer); }); - }).doOnTerminate(() -> housekeepingClient.close()) + }).doOnTerminate(housekeepingClient::close) .subscribe(aVoid -> { }, e -> { logger.error("collectionScaleUpFailed to scale up collection", e); diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java index 1bf1693183dc7..37d69d31b833b 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java @@ -57,7 +57,7 @@ import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.rx.TestConfigurations; -import rx.Observable; +import reactor.core.publisher.Flux; public class Utils { public static AsyncDocumentClient housekeepingClient() { @@ -96,7 +96,7 @@ public static void safeClean(AsyncDocumentClient client, String databaseId) { if (client != null) { if (databaseId != null) { try { - client.deleteDatabase("/dbs/" + databaseId, null).toBlocking().single(); + client.deleteDatabase("/dbs/" + databaseId, null).then().block(); } catch (Exception e) { } } @@ -125,19 +125,19 @@ private DatabaseManagerImpl(AsyncDocumentClient client) { } @Override - public Observable> queryDatabases(SqlQuerySpec query) { + public Flux> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override - public Observable> createDatabase(Database databaseDefinition) { + public Flux> createDatabase(Database databaseDefinition) { return client.createDatabase(databaseDefinition, null); } @Override - public Observable> deleteDatabase(String id) { + public Flux> deleteDatabase(String id) { return client.deleteDatabase("dbs/" + id, null); } } -} +} \ No newline at end of file diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java index 8219238ec17ae..8f57b84bea21f 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java @@ -48,7 +48,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class WorkflowTest { - private static final int TIMEOUT = 120000; + private static final int TIMEOUT = 120_000; // 2 minutes private Database database; private DocumentCollection collection; @@ -296,7 +296,7 @@ public void beforeClass() { collection = housekeepingClient.createCollection("dbs/"+ database.id(), getCollectionDefinitionWithRangeRangeIndex(), options) - .toBlocking().single().getResource(); + .single().block().getResource(); housekeepingClient.close(); } @@ -345,4 +345,4 @@ DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { return collectionDefinition; } -} +} \ No newline at end of file diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java index f8cd30f025ad9..75d9cd02065e4 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java @@ -27,7 +27,7 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; +import reactor.core.publisher.Flux; import java.time.Duration; import java.time.LocalDateTime; @@ -93,7 +93,7 @@ public static DatabaseForTest create(DatabaseManager client) { Database dbDef = new Database(); dbDef.id(generateId()); - Database db = client.createDatabase(dbDef).toBlocking().single().getResource(); + Database db = client.createDatabase(dbDef).single().block().getResource(); DatabaseForTest dbForTest = DatabaseForTest.from(db); assertThat(dbForTest).isNotNull(); return dbForTest; @@ -104,7 +104,7 @@ public static void cleanupStaleTestDatabases(DatabaseManager client) { List dbs = client.queryDatabases( new SqlQuerySpec("SELECT * FROM c WHERE STARTSWITH(c.id, @PREFIX)", new SqlParameterCollection(new SqlParameter("@PREFIX", DatabaseForTest.SHARED_DB_ID_PREFIX)))) - .flatMap(page -> Observable.from(page.results())).toList().toBlocking().single(); + .flatMap(page -> Flux.fromIterable(page.results())).collectList().block(); for (Database db : dbs) { assertThat(db.id()).startsWith(DatabaseForTest.SHARED_DB_ID_PREFIX); @@ -113,14 +113,14 @@ public static void cleanupStaleTestDatabases(DatabaseManager client) { if (db != null && dbForTest.isStale()) { logger.info("Deleting database {}", db.id()); - client.deleteDatabase(db.id()).toBlocking().single(); + client.deleteDatabase(db.id()).single().block(); } } } public interface DatabaseManager { - Observable> queryDatabases(SqlQuerySpec query); - Observable> createDatabase(Database databaseDefinition); - Observable> deleteDatabase(String id); + Flux> queryDatabases(SqlQuerySpec query); + Flux> createDatabase(Database databaseDefinition); + Flux> deleteDatabase(String id); } -} +} \ No newline at end of file diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUnderTestWrapper.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUnderTestWrapper.java index 4f6a30ca7e643..6a50b555bafe0 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUnderTestWrapper.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUnderTestWrapper.java @@ -23,13 +23,9 @@ package com.azure.data.cosmos.directconnectivity; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpRequest; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.util.ArrayList; import java.util.Collections; @@ -41,32 +37,27 @@ * This is a helper class for capturing requests sent over a httpClient. */ public class HttpClientUnderTestWrapper { - final private CompositeHttpClient origHttpClient; - final private CompositeHttpClient spyHttpClient; - public final List> capturedRequest = Collections.synchronizedList(new ArrayList<>()); + final private HttpClient origHttpClient; + final private HttpClient spyHttpClient; - public HttpClientUnderTestWrapper(CompositeHttpClient origHttpClient) { + public final List capturedRequests = Collections.synchronizedList(new ArrayList<>()); + + public HttpClientUnderTestWrapper(HttpClient origHttpClient) { this.origHttpClient = origHttpClient; this.spyHttpClient = Mockito.spy(origHttpClient); - initRequestCapture(spyHttpClient); } - public CompositeHttpClient getSpyHttpClient() { + public HttpClient getSpyHttpClient() { return spyHttpClient; } - void initRequestCapture(CompositeHttpClient spyClient) { - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { - RxClient.ServerInfo serverInfo = invocationOnMock.getArgumentAt(0, RxClient.ServerInfo.class); - HttpClientRequest httpReq = invocationOnMock.getArgumentAt(1, HttpClientRequest.class); - capturedRequest.add(httpReq); - return origHttpClient.submit(serverInfo, httpReq); - } - }).when(spyClient).submit(Mockito.any(RxClient.ServerInfo.class), Mockito.any(HttpClientRequest.class)); + private void initRequestCapture(HttpClient spyClient) { + doAnswer(invocationOnMock -> { + HttpRequest httpRequest = invocationOnMock.getArgumentAt(0, HttpRequest.class); + capturedRequests.add(httpRequest); + return origHttpClient.send(httpRequest); + }).when(spyClient).send(Mockito.any(HttpRequest.class)); } } diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java index ede2b5b14ebfc..05e1178f05088 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java @@ -132,7 +132,7 @@ public void validate(List> feedList) { List actualIds = feedList .stream() .flatMap(f -> f.results().stream()) - .map(r -> r.resourceId()) + .map(Resource::resourceId) .collect(Collectors.toList()); assertThat(actualIds) .describedAs("Resource IDs of results") diff --git a/commons/pom.xml b/commons/pom.xml index 831a7e85676fc..8b9ce774a5b31 100644 --- a/commons/pom.xml +++ b/commons/pom.xml @@ -113,32 +113,6 @@ SOFTWARE. commons-validator ${commons-validator.version} - - com.github.davidmoten - rxjava-extras - ${rxjava-extras.version} - - - io.reactivex - rxjava - ${rxjava.version} - - - io.reactivex - rxjava-string - ${rxjava-string.version} - - - io.reactivex - rxnetty - ${rxnetty.version} - - - io.netty - netty-transport-native-epoll - - - io.netty netty-codec-http @@ -191,6 +165,18 @@ SOFTWARE. ${assertj.version} test + + org.hamcrest + hamcrest-core + ${hamcrest.version} + test + + + org.mockito + mockito-core + ${mockito.version} + test + org.slf4j slf4j-log4j12 @@ -218,11 +204,6 @@ SOFTWARE. reactor-test test - - com.github.akarnokd - rxjava2-interop - ${rxjava2interop.verison} - io.reactivex.rxjava2 rxjava @@ -233,6 +214,10 @@ SOFTWARE. guava ${guava.version} test - + + + io.projectreactor.netty + reactor-netty + diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java b/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java index 5ade63c37d69e..a4741d3c9e54b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java @@ -39,6 +39,17 @@ public class CosmosItemProperties extends Resource { public CosmosItemProperties() { } + /** + * Sets the id + * + * @param id the name of the resource. + * @return the cosmos item properties with id set + */ + public CosmosItemProperties id(String id) { + super.id(id); + return this; + } + /** * Initialize a CosmosItemProperties object from json string. * diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureSettings.java index 1df8bf20f89a7..df8236fa194f0 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureSettings.java @@ -37,6 +37,16 @@ public CosmosStoredProcedureSettings() { super(); } + /** + * Sets the id + * @param id the name of the resource. + * @return return the Cosmos stored procedure settings with id set + */ + public CosmosStoredProcedureSettings id(String id){ + super.id(id); + return this; + } + /** * Constructor. * diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java index 7dd8123d89840..93025d425c770 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java @@ -50,6 +50,17 @@ public CosmosTriggerSettings(String jsonString){ super(response.getResource().toJson()); } + /** + * Sets the id + * + * @param id the name of the resource. + * @return the current cosmos trigger settings instance + */ + public CosmosTriggerSettings id(String id) { + super.id(id); + return this; + } + /** * Get the body of the trigger. * diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java index c1bb0fee7db21..9513a4d7246f8 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java @@ -49,6 +49,16 @@ public CosmosUserDefinedFunctionSettings(String jsonString) { super(jsonString); } + /** + * Sets the id + * @param id the name of the resource. + * @return the current instance of cosmos user defined function settings + */ + public CosmosUserDefinedFunctionSettings id(String id) { + super.id(id); + return this; + } + /** * Get the body of the user defined function. * diff --git a/commons/src/main/java/com/azure/data/cosmos/Database.java b/commons/src/main/java/com/azure/data/cosmos/Database.java index ab3c01d47dad5..b5ca302a0b1ba 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Database.java +++ b/commons/src/main/java/com/azure/data/cosmos/Database.java @@ -43,6 +43,16 @@ public Database() { super(); } + /** + * Sets the id + * @param id the name of the resource. + * @return the current instance of Database + */ + public Database id(String id){ + super.id(id); + return this; + } + /** * Initialize a database object from json string. * diff --git a/commons/src/main/java/com/azure/data/cosmos/Document.java b/commons/src/main/java/com/azure/data/cosmos/Document.java index d01a0e4e04cc1..87a07417451c0 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Document.java +++ b/commons/src/main/java/com/azure/data/cosmos/Document.java @@ -44,6 +44,16 @@ public Document() { super(); } + /** + * Sets the id + * @param id the name of the resource. + * @return the current instance of the Document + */ + public Document id(String id){ + super.id(id); + return this; + } + /** * Initialize a document object from json string. * diff --git a/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java b/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java index a352b0184e457..0bb720a87eee3 100644 --- a/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java +++ b/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java @@ -46,6 +46,16 @@ public DocumentCollection() { super(); } + /** + * Sets the id and returns the document collection + * @param id the name of the resource. + * @return + */ + public DocumentCollection id(String id){ + super.id(id); + return this; + } + /** * Initialize a document collection object from json string. * diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java index 5b065f72ac93b..7eba8f627f99f 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java +++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java @@ -54,6 +54,16 @@ public PartitionKeyRange(String jsonString) { super(jsonString); } + /** + * Set id of partition key range + * @param id the name of the resource. + * @return the partition key range + */ + public PartitionKeyRange id(String id) { + super.id(id); + return this; + } + public PartitionKeyRange(String id, String minInclusive, String maxExclusive) { super(); this.id(id); diff --git a/commons/src/main/java/com/azure/data/cosmos/Permission.java b/commons/src/main/java/com/azure/data/cosmos/Permission.java index d62aea6ba728d..27125e7e34024 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Permission.java +++ b/commons/src/main/java/com/azure/data/cosmos/Permission.java @@ -47,6 +47,16 @@ public Permission(String jsonString) { super(jsonString); } + /** + * Sets the id + * @param id the name of the resource. + * @return the current instance of permission + */ + public Permission id(String id){ + super.id(id); + return this; + } + /** * Gets the self-link of resource to which the permission applies. * diff --git a/commons/src/main/java/com/azure/data/cosmos/Resource.java b/commons/src/main/java/com/azure/data/cosmos/Resource.java index e8ea3e1bc173c..dd2f445afcbdb 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Resource.java +++ b/commons/src/main/java/com/azure/data/cosmos/Resource.java @@ -103,7 +103,7 @@ public String id() { * @param id the name of the resource. * @return the resource. */ - public Resource id(String id) { + Resource id(String id) { super.set(Constants.Properties.ID, id); return this; } diff --git a/commons/src/main/java/com/azure/data/cosmos/StoredProcedure.java b/commons/src/main/java/com/azure/data/cosmos/StoredProcedure.java index 51fde631af21a..52dd6324b476b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/StoredProcedure.java +++ b/commons/src/main/java/com/azure/data/cosmos/StoredProcedure.java @@ -50,6 +50,16 @@ public StoredProcedure(String jsonString) { super(jsonString); } + /** + * Sets the id + * @param id the name of the resource. + * @return the current stored procedure + */ + public StoredProcedure id(String id){ + super.id(id); + return this; + } + /** * Get the body of the stored procedure. * diff --git a/commons/src/main/java/com/azure/data/cosmos/User.java b/commons/src/main/java/com/azure/data/cosmos/User.java index a841aaeaedd76..637cb5496af7c 100644 --- a/commons/src/main/java/com/azure/data/cosmos/User.java +++ b/commons/src/main/java/com/azure/data/cosmos/User.java @@ -46,6 +46,16 @@ public User(String jsonString) { super(jsonString); } + /** + * Sets the id + * @param id the name of the resource. + * @return the current instance of User + */ + public User id(String id){ + super.id(id); + return this; + } + /** * Gets the self-link of the permissions associated with the user. * diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java index f22da6227ea2c..69bc12a787e36 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.Strings; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.util.HashMap; @@ -41,7 +41,7 @@ public GoneException(String msg) { this(msg, null); } public GoneException() { - this(RMResources.Gone, (String) null); + this(RMResources.Gone, null); } public GoneException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { @@ -51,40 +51,40 @@ public GoneException(Error error, long lsn, String partitionKeyRangeId, Map(), requestUri); + this(message, null, new HashMap<>(), requestUri); } public GoneException(String message, Exception innerException, URI requestUri, String localIpAddress) { - this(message(localIpAddress, message), innerException, (HttpResponseHeaders) null, requestUri); + this(message(localIpAddress, message), innerException, null, requestUri); } public GoneException(Exception innerException) { - this(RMResources.Gone, innerException, new HashMap<>(), (String) null); + this(RMResources.Gone, innerException, new HashMap<>(), null); } - public GoneException(String message, HttpResponseHeaders headers, URI requestUri) { - super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUri != null ? requestUri.toString() : null); + public GoneException(String message, HttpHeaders headers, URI requestUrl) { + super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUrl != null ? requestUrl.toString() : null); } - public GoneException(String message, HttpResponseHeaders headers, String requestUri) { - super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUri); + public GoneException(String message, HttpHeaders headers, String requestUriString) { + super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUriString); } public GoneException(String message, Exception innerException, - HttpResponseHeaders headers, - URI requestUri) { - super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUri != null ? requestUri.toString() : null); + HttpHeaders headers, + URI requestUrl) { + super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUrl != null ? requestUrl.toString() : null); } public GoneException(String message, Exception innerException, Map headers, - String requestUri) { - super(message, innerException, headers, HttpConstants.StatusCodes.GONE, requestUri); + String requestUriString) { + super(message, innerException, headers, HttpConstants.StatusCodes.GONE, requestUriString); } public GoneException(Error error, Map headers) { diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/HttpUtils.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/HttpUtils.java index 08464546286d4..39966eedadf34 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/HttpUtils.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/HttpUtils.java @@ -26,8 +26,7 @@ import com.azure.data.cosmos.internal.Constants.UrlEncodingInfo; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Strings; -import io.reactivex.netty.protocol.http.client.HttpRequestHeaders; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,6 +41,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; public class HttpUtils { @@ -74,13 +74,12 @@ public static URI toURI(String uri) { } } - public static Map asMap(HttpResponseHeaders headers) { + public static Map asMap(HttpHeaders headers) { if (headers == null) { return new HashMap<>(); } - - HashMap map = new HashMap<>(headers.names().size()); - for (Entry entry : headers.entries()) { + HashMap map = new HashMap<>(headers.size()); + for (Entry entry : headers.toMap().entrySet()) { if (entry.getKey().equals(HttpConstants.HttpHeaders.OWNER_FULL_NAME)) { map.put(entry.getKey(), HttpUtils.urlDecode(entry.getValue())); } else { @@ -90,17 +89,6 @@ public static Map asMap(HttpResponseHeaders headers) { return map; } - public static Map asMap(HttpRequestHeaders headers) { - HashMap map = new HashMap<>(); - if (headers == null) { - return map; - } - for (Entry entry : headers.entries()) { - map.put(entry.getKey(), entry.getValue()); - } - return map; - } - public static String getDateHeader(Map headerValues) { if (headerValues == null) { return StringUtils.EMPTY; @@ -116,12 +104,12 @@ public static String getDateHeader(Map headerValues) { return date != null ? date : StringUtils.EMPTY; } - public static List> unescape(List> headers) { - List> result = new ArrayList>(); + public static List> unescape(Set> headers) { + List> result = new ArrayList<>(headers.size()); for (Entry entry : headers) { if (entry.getKey().equals(HttpConstants.HttpHeaders.OWNER_FULL_NAME)) { String unescapedUrl = HttpUtils.urlDecode(entry.getValue()); - entry = new AbstractMap.SimpleEntry(entry.getKey(), unescapedUrl); + entry = new AbstractMap.SimpleEntry<>(entry.getKey(), unescapedUrl); } result.add(entry); } diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java index d1a1c3f56102a..f29f9dbf48ca2 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.Strings; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.util.Map; @@ -47,33 +47,33 @@ public RequestTimeoutException(Error error, long lsn, String partitionKeyRangeId } public RequestTimeoutException(String message, URI requestUri) { - this(message, (Exception) null, (HttpResponseHeaders) null, requestUri); + this(message, null, null, requestUri); } public RequestTimeoutException(String message, Exception innerException, URI requestUri, String localIpAddress) { - this(message(localIpAddress, message), innerException, (HttpResponseHeaders) null, requestUri); + this(message(localIpAddress, message), innerException, null, requestUri); } public RequestTimeoutException(Exception innerException) { - this(RMResources.Gone, innerException, (HttpResponseHeaders) null, null); + this(RMResources.Gone, innerException, (HttpHeaders) null, null); } - public RequestTimeoutException(String message, HttpResponseHeaders headers, URI requestUri) { - super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUri != null ? requestUri.toString() : null); + public RequestTimeoutException(String message, HttpHeaders headers, URI requestUrl) { + super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUrl != null ? requestUrl.toString() : null); } - public RequestTimeoutException(String message, HttpResponseHeaders headers, String requestUri) { - super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUri); + public RequestTimeoutException(String message, HttpHeaders headers, String requestUriString) { + super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUriString); } public RequestTimeoutException(String message, Exception innerException, - HttpResponseHeaders headers, - URI requestUri) { - super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUri != null ? requestUri.toString() : null); + HttpHeaders headers, + URI requestUrl) { + super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUrl != null ? requestUrl.toString() : null); } private static String message(String localIP, String baseMessage) { diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java b/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java index 5a2304aeacd81..036289bfa37f1 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Error; import com.azure.data.cosmos.directconnectivity.HttpUtils; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.util.HashMap; @@ -54,14 +54,14 @@ public BadRequestException(Error error, long lsn, String partitionKeyRangeId, Ma } public BadRequestException(String message) { - this(message, (Exception) null, (HttpResponseHeaders) null, null); + this(message, null, null, null); } - public BadRequestException(String message, HttpResponseHeaders headers, String requestUri) { - this(message, null, headers, requestUri); + public BadRequestException(String message, HttpHeaders headers, String requestUrlString) { + this(message, null, headers, requestUrlString); } - public BadRequestException(String message, HttpResponseHeaders headers, URI requestUri) { + public BadRequestException(String message, HttpHeaders headers, URI requestUri) { this(message, headers, requestUri != null ? requestUri.toString() : null); } @@ -71,12 +71,12 @@ public BadRequestException(Exception innerException) { public BadRequestException(String message, Exception innerException, - HttpResponseHeaders headers, - String requestUri) { + HttpHeaders headers, + String requestUrlString) { super(String.format("%s: %s", RMResources.BadRequest, message), innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.BADREQUEST, - requestUri != null ? requestUri.toString() : null); + requestUrlString); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java b/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java index bc19112bbf423..4f32c496e2732 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java @@ -67,6 +67,8 @@ public class Configs { private static final int CPU_CNT = Runtime.getRuntime().availableProcessors(); private static final int DEFAULT_DIRECT_HTTPS_POOL_SIZE = CPU_CNT * 500; + private static final String REACTOR_NETTY_CONNECTION_POOL_NAME = "reactor-netty-connection-pool"; + public Configs() { this.sslContext = sslContextInit(); } @@ -151,6 +153,10 @@ public int getUnavailableLocationsExpirationTimeInSeconds() { return getJVMConfigAsInt(UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS, DEFAULT_UNAVAILABLE_LOCATIONS_EXPIRATION_TIME_IN_SECONDS); } + public String getReactorNettyConnectionPoolName() { + return REACTOR_NETTY_CONNECTION_POOL_NAME; + } + private static String getJVMConfigAsString(String propName, String defaultValue) { String propValue = System.getProperty(propName); return StringUtils.defaultString(propValue, defaultValue); diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java b/commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java deleted file mode 100644 index 3c4bd698e4656..0000000000000 --- a/commons/src/main/java/com/azure/data/cosmos/internal/HttpClientFactory.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.azure.data.cosmos.internal; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufAllocator; -import io.netty.channel.ChannelPipeline; -import io.netty.handler.logging.LogLevel; -import io.netty.handler.logging.LoggingHandler; -import io.netty.handler.proxy.HttpProxyHandler; -import io.netty.handler.ssl.SslContext; -import io.netty.handler.ssl.SslHandler; -import io.reactivex.netty.pipeline.PipelineConfigurator; -import io.reactivex.netty.pipeline.PipelineConfiguratorComposite; -import io.reactivex.netty.pipeline.ssl.SSLEngineFactory; -import io.reactivex.netty.pipeline.ssl.SslCompletionHandler; -import io.reactivex.netty.protocol.http.HttpObjectAggregationConfigurator; -import io.reactivex.netty.protocol.http.client.CompositeHttpClientBuilder; -import io.reactivex.netty.protocol.http.client.HttpClient.HttpClientConfig; -import io.reactivex.netty.protocol.http.client.HttpClientPipelineConfigurator; -import org.slf4j.LoggerFactory; - -import javax.net.ssl.SSLEngine; -import java.net.InetSocketAddress; -import java.util.concurrent.TimeUnit; - -/** - * Helper class internally used for instantiating rx http client. - */ -public class HttpClientFactory { - private final static String NETWORK_LOG_CATEGORY = "com.azure.data.cosmos.netty-network"; - - private final Configs configs; - private Integer maxPoolSize; - private Integer maxIdleConnectionTimeoutInMillis; - private Integer requestTimeoutInMillis; - private InetSocketAddress proxy; - - public HttpClientFactory(Configs configs) { - this.configs = configs; - } - - public HttpClientFactory withPoolSize(int maxPoolSize) { - this.maxPoolSize = maxPoolSize; - return this; - } - - public HttpClientFactory withHttpProxy(InetSocketAddress proxy) { - this.proxy = proxy; - return this; - } - - public HttpClientFactory withMaxIdleConnectionTimeoutInMillis(int maxIdleConnectionTimeoutInMillis) { - this.maxIdleConnectionTimeoutInMillis = maxIdleConnectionTimeoutInMillis; - return this; - } - - public HttpClientFactory withRequestTimeoutInMillis(int requestTimeoutInMillis) { - this.requestTimeoutInMillis = requestTimeoutInMillis; - return this; - } - - class DefaultSSLEngineFactory implements SSLEngineFactory { - private final SslContext sslContext; - - private DefaultSSLEngineFactory() { - this.sslContext = configs.getSslContext(); - } - - @Override - public SSLEngine createSSLEngine(ByteBufAllocator allocator) { - return sslContext.newEngine(allocator); - } - } - - class SslPipelineConfiguratorUsedWithProxy implements PipelineConfigurator { - - private final SSLEngineFactory sslEngineFactory; - - private SslPipelineConfiguratorUsedWithProxy(SSLEngineFactory sslEngineFactory) { - this.sslEngineFactory = sslEngineFactory; - } - - @Override - public void configureNewPipeline(ChannelPipeline pipeline) { - final SslHandler sslHandler = new SslHandler(sslEngineFactory.createSSLEngine(pipeline.channel().alloc())); - if (proxy != null) { - pipeline.addAfter(Constants.Properties.HTTP_PROXY_HANDLER_NAME, Constants.Properties.SSL_HANDLER_NAME, - sslHandler); - } else { - pipeline.addFirst(Constants.Properties.SSL_HANDLER_NAME, sslHandler); - } - pipeline.addAfter(Constants.Properties.SSL_HANDLER_NAME, Constants.Properties.SSL_COMPLETION_HANDLER_NAME, - new SslCompletionHandler(sslHandler.handshakeFuture())); - } - } - - public CompositeHttpClientBuilder toHttpClientBuilder() { - - if (configs == null) { - throw new IllegalArgumentException("configs is null"); - } - - DefaultSSLEngineFactory defaultSSLEngineFactory = new DefaultSSLEngineFactory(); - CompositeHttpClientBuilder builder = new CompositeHttpClientBuilder(); - if (maxPoolSize != null) { - builder = builder.withMaxConnections(maxPoolSize); - } - - if (maxIdleConnectionTimeoutInMillis != null) { - builder = builder.withIdleConnectionsTimeoutMillis(maxIdleConnectionTimeoutInMillis); - } - - builder = builder.pipelineConfigurator(pipeline -> { - LoggingHandler loggingHandler = getLoggingHandler(); - - if (loggingHandler != null) { - pipeline.addFirst(Constants.Properties.LOGGING_HANDLER_NAME, loggingHandler); - } - - if (proxy != null) { - pipeline.addFirst(Constants.Properties.HTTP_PROXY_HANDLER_NAME, new HttpProxyHandler(proxy)); - } - }).appendPipelineConfigurator(new SslPipelineConfiguratorUsedWithProxy<>(defaultSSLEngineFactory)) - .appendPipelineConfigurator(createClientPipelineConfigurator(configs)); - - if (requestTimeoutInMillis != null) { - HttpClientConfig.Builder clientConfigBuilder = new HttpClientConfig.Builder(); - clientConfigBuilder.readTimeout(requestTimeoutInMillis, TimeUnit.MILLISECONDS); - return builder.config(clientConfigBuilder.build()); - } - - return builder; - } - - private static PipelineConfigurator createClientPipelineConfigurator(Configs config) { - PipelineConfigurator clientPipelineConfigurator = new PipelineConfiguratorComposite( - new HttpClientPipelineConfigurator(config.getMaxHttpInitialLineLength(), - config.getMaxHttpHeaderSize(), config.getMaxHttpChunkSize(), true), - new HttpObjectAggregationConfigurator(config.getMaxHttpBodyLength())); - return clientPipelineConfigurator; - } - - private static LoggingHandler getLoggingHandler() { - if (LoggerFactory.getLogger(NETWORK_LOG_CATEGORY).isTraceEnabled()) { - return new LoggingHandler(NETWORK_LOG_CATEGORY, LogLevel.TRACE); - } - - return null; - } -} diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java b/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java index 72af9654a7f71..a8bac139adb8b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Error; import com.azure.data.cosmos.directconnectivity.HttpUtils; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.net.URL; @@ -53,39 +53,39 @@ public InternalServerErrorException(Error error, long lsn, String partitionKeyRa } public InternalServerErrorException(String message) { - this(message, (Exception) null, (Map) null, (String) null); + this(message, null, (Map) null, null); } public InternalServerErrorException(String message, Exception innerException) { - this(message, innerException, (HttpResponseHeaders) null, (String) null); + this(message, innerException, (HttpHeaders) null, (String) null); } public InternalServerErrorException(Exception innerException) { - this(RMResources.InternalServerError, innerException, (HttpResponseHeaders) null, (String) null); + this(RMResources.InternalServerError, innerException, (HttpHeaders) null, (String) null); } - public InternalServerErrorException(String message, HttpResponseHeaders headers, URI requestUri) { + public InternalServerErrorException(String message, HttpHeaders headers, URI requestUri) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUri != null ? requestUri.toString() : null); } - public InternalServerErrorException(String message, HttpResponseHeaders headers, String requestUri) { - super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUri); + public InternalServerErrorException(String message, HttpHeaders headers, String requestUriString) { + super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUriString); } - public InternalServerErrorException(String message, HttpResponseHeaders headers, URL requestUri) { - super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUri != null ? requestUri.toString() : null); + public InternalServerErrorException(String message, HttpHeaders headers, URL requestUrl) { + super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUrl != null ? requestUrl.toString() : null); } - public InternalServerErrorException(String message, Exception innerException, HttpResponseHeaders headers, URI requestUri) { + public InternalServerErrorException(String message, Exception innerException, HttpHeaders headers, URI requestUri) { super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUri != null ? requestUri.toString() : null); } - public InternalServerErrorException(String message, Exception innerException, HttpResponseHeaders headers, String requestUri) { - super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUri); + public InternalServerErrorException(String message, Exception innerException, HttpHeaders headers, String requestUriString) { + super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUriString); } - public InternalServerErrorException(String message, Exception innerException, Map headers, String requestUri) { - super(message, innerException, headers, HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUri); + public InternalServerErrorException(String message, Exception innerException, Map headers, String requestUriString) { + super(message, innerException, headers, HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUriString); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java index 5dc17cd969f10..975ab6b58c485 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java @@ -29,10 +29,11 @@ import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; +import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; -import rx.Observable; -import rx.observables.StringObservable; +import reactor.core.publisher.Flux; +import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -67,7 +68,7 @@ public class RxDocumentServiceRequest { public DocumentServiceRequestContext requestContext; - private Observable contentObservable; + private Flux contentObservable; private byte[] byteContent; // NOTE: TODO: these fields are copied from .Net SDK @@ -212,7 +213,7 @@ private RxDocumentServiceRequest(OperationType operationType, private RxDocumentServiceRequest(OperationType operationType, String resourceId, ResourceType resourceType, - Observable contentObservable, + Flux contentObservable, byte[] content, String path, Map headers, @@ -238,7 +239,7 @@ private RxDocumentServiceRequest(OperationType operationType, private RxDocumentServiceRequest(OperationType operationType, ResourceType resourceType, String path, - Observable contentObservable, + Flux contentObservable, Map headers, AuthorizationTokenType authorizationTokenType) { this(operationType, extractIdFromUri(path), resourceType, contentObservable, null, path, headers, authorizationTokenType); @@ -293,7 +294,7 @@ public void setContentBytes(byte[] bytes) { public static RxDocumentServiceRequest create(OperationType operation, ResourceType resourceType, String relativePath, - Observable content, + Flux content, Map headers) { return new RxDocumentServiceRequest(operation, resourceType, relativePath, content, headers, AuthorizationTokenType.PrimaryMasterKey); } @@ -311,7 +312,7 @@ public static RxDocumentServiceRequest create(OperationType operation, public static RxDocumentServiceRequest create(OperationType operation, ResourceType resourceType, String relativePath, - Observable content, + Flux content, Map headers, AuthorizationTokenType authorizationTokenType) { return new RxDocumentServiceRequest(operation, resourceType, relativePath, content, headers, authorizationTokenType); @@ -330,10 +331,9 @@ public static RxDocumentServiceRequest create(OperationType operation, ResourceType resourceType, String relativePath, InputStream inputStream, - Map headers) { - // StringObservable is mis-named. It doesn't make any assumptions on character set - // and handles bytes only - return new RxDocumentServiceRequest(operation, resourceType, relativePath, StringObservable.from(inputStream), headers, AuthorizationTokenType.PrimaryMasterKey); + Map headers) throws IOException { + Flux byteFlux = Flux.just(IOUtils.toByteArray(inputStream)); + return new RxDocumentServiceRequest(operation, resourceType, relativePath, byteFlux, headers, AuthorizationTokenType.PrimaryMasterKey); } /** Creates a DocumentServiceRequest with a stream. @@ -351,10 +351,9 @@ public static RxDocumentServiceRequest create(OperationType operation, String relativePath, InputStream inputStream, Map headers, - AuthorizationTokenType authorizationTokenType) { - // StringObservable is mis-named. It doesn't make any assumptions on character set - // and handles bytes only - return new RxDocumentServiceRequest(operation, resourceType, relativePath, StringObservable.from(inputStream), headers, authorizationTokenType); + AuthorizationTokenType authorizationTokenType) throws IOException { + Flux byteFlux = Flux.just(IOUtils.toByteArray(inputStream)); + return new RxDocumentServiceRequest(operation, resourceType, relativePath, byteFlux, headers, authorizationTokenType); } /** @@ -481,7 +480,7 @@ public static RxDocumentServiceRequest create(ResourceType resourceType, break; } - Observable body = StringObservable.encode(Observable.just(queryText), StandardCharsets.UTF_8); + Flux body = Flux.just(queryText).map(s -> StandardCharsets.UTF_8.encode(s).array()); return new RxDocumentServiceRequest(operation, resourceType, relativePath, body, headers, AuthorizationTokenType.PrimaryMasterKey); } @@ -995,7 +994,7 @@ public void clearRoutingHints() { this.requestContext.resolvedPartitionKeyRange = null; } - public Observable getContentObservable() { + public Flux getContentObservable() { return contentObservable; } diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java b/commons/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java new file mode 100644 index 0000000000000..79b7ed0f58cb8 --- /dev/null +++ b/commons/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java @@ -0,0 +1,92 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.internal.http; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +/** + * HTTP response which will buffer the response's body when/if it is read. + */ +public class BufferedHttpResponse extends HttpResponse { + private final HttpResponse innerHttpResponse; + private final Mono cachedBody; + + /** + * Creates a buffered HTTP response. + * + * @param innerHttpResponse The HTTP response to buffer + */ + public BufferedHttpResponse(HttpResponse innerHttpResponse) { + this.innerHttpResponse = innerHttpResponse; + this.cachedBody = innerHttpResponse.bodyAsByteArray().cache(); + this.withRequest(innerHttpResponse.request()); + } + + @Override + public int statusCode() { + return innerHttpResponse.statusCode(); + } + + @Override + public String headerValue(String name) { + return innerHttpResponse.headerValue(name); + } + + @Override + public HttpHeaders headers() { + return innerHttpResponse.headers(); + } + + @Override + public Mono bodyAsByteArray() { + return cachedBody; + } + + @Override + public Flux body() { + return bodyAsByteArray().flatMapMany(bytes -> Flux.just(Unpooled.wrappedBuffer(bytes))); + } + + @Override + public Mono bodyAsString() { + return bodyAsByteArray() + .map(bytes -> bytes == null ? null : new String(bytes, StandardCharsets.UTF_8)); + } + + @Override + public Mono bodyAsString(Charset charset) { + return bodyAsByteArray() + .map(bytes -> bytes == null ? null : new String(bytes, charset)); + } + + @Override + public BufferedHttpResponse buffer() { + return this; + } +} diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java new file mode 100644 index 0000000000000..1689d37511b76 --- /dev/null +++ b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java @@ -0,0 +1,61 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.internal.http; + +import reactor.core.publisher.Mono; +import reactor.netty.resources.ConnectionProvider; + +/** + * A generic interface for sending HTTP requests and getting responses. + */ +public interface HttpClient { + + /** + * Send the provided request asynchronously. + * + * @param request The HTTP request to send + * @return A {@link Mono} that emits response asynchronously + */ + Mono send(HttpRequest request); + + /** + * Create fixed HttpClient with {@link HttpClientConfig} + * + * @return the HttpClient + */ + static HttpClient createFixed(HttpClientConfig httpClientConfig) { + if (httpClientConfig.getConfigs() == null) { + throw new IllegalArgumentException("HttpClientConfig is null"); + } + + if (httpClientConfig.getMaxPoolSize() == null) { + return new ReactorNettyClient(ConnectionProvider.fixed(httpClientConfig.getConfigs().getReactorNettyConnectionPoolName()), httpClientConfig); + } + return new ReactorNettyClient(ConnectionProvider.fixed(httpClientConfig.getConfigs().getReactorNettyConnectionPoolName(), httpClientConfig.getMaxPoolSize()), httpClientConfig); + } + + /** + * Shutdown the Http Client and clean up resources + */ + void shutdown(); +} diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java new file mode 100644 index 0000000000000..971d1bf310ed6 --- /dev/null +++ b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java @@ -0,0 +1,85 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.azure.data.cosmos.internal.http; + +import com.azure.data.cosmos.internal.Configs; + +import java.net.InetSocketAddress; + +/** + * Helper class internally used for instantiating reactor netty http client. + */ +public class HttpClientConfig { + public final static String REACTOR_NETWORK_LOG_CATEGORY = "com.azure.data.cosmos.netty-network"; + + private final Configs configs; + private Integer maxPoolSize; + private Integer maxIdleConnectionTimeoutInMillis; + private Integer requestTimeoutInMillis; + private InetSocketAddress proxy; + + public HttpClientConfig(Configs configs) { + this.configs = configs; + } + + public HttpClientConfig withPoolSize(int maxPoolSize) { + this.maxPoolSize = maxPoolSize; + return this; + } + + public HttpClientConfig withHttpProxy(InetSocketAddress proxy) { + this.proxy = proxy; + return this; + } + + public HttpClientConfig withMaxIdleConnectionTimeoutInMillis(int maxIdleConnectionTimeoutInMillis) { + this.maxIdleConnectionTimeoutInMillis = maxIdleConnectionTimeoutInMillis; + return this; + } + + public HttpClientConfig withRequestTimeoutInMillis(int requestTimeoutInMillis) { + this.requestTimeoutInMillis = requestTimeoutInMillis; + return this; + } + + public Configs getConfigs() { + return configs; + } + + public Integer getMaxPoolSize() { + return maxPoolSize; + } + + public Integer getMaxIdleConnectionTimeoutInMillis() { + return maxIdleConnectionTimeoutInMillis; + } + + public Integer getRequestTimeoutInMillis() { + return requestTimeoutInMillis; + } + + public InetSocketAddress getProxy() { + return proxy; + } +} diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java new file mode 100644 index 0000000000000..e9cbca44a59fb --- /dev/null +++ b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java @@ -0,0 +1,85 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.internal.http; + +import org.apache.commons.lang3.StringUtils; + +/** + * A single header within a HTTP request or response. + * + * If multiple header values are added to a HTTP request or response with + * the same name (case-insensitive), then the values will be appended + * to the end of the same Header with commas separating them. + */ +public class HttpHeader { + private final String name; + private String value; + + /** + * Create a HttpHeader instance using the provided name and value. + * + * @param name the name + * @param value the value + */ + public HttpHeader(String name, String value) { + this.name = name; + this.value = value; + } + + /** + * Get the header name. + * + * @return the name of this Header + */ + public String name() { + return name; + } + + /** + * Get the header value. + * + * @return the value of this Header + */ + public String value() { + return value; + } + + /** + * Get the comma separated value as an array. + * + * @return the values of this Header that are separated by a comma + */ + public String[] values() { + return value == null ? null : StringUtils.split(value, ","); + } + + /** + * Get the String representation of the header. + * + * @return the String representation of this HttpHeader + */ + @Override + public String toString() { + return name + ":" + value; + } +} diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java new file mode 100644 index 0000000000000..f1bf91509ce3d --- /dev/null +++ b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java @@ -0,0 +1,154 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.azure.data.cosmos.internal.http; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializable; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.jsontype.TypeSerializer; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; + +/** + * A collection of headers on an HTTP request or response. + */ +public class HttpHeaders implements Iterable, JsonSerializable { + private Map headers; + + /** + * Create an empty HttpHeaders instance. + */ + public HttpHeaders() { + this.headers = new HashMap<>(); + } + + /** + * Create an HttpHeaders instance with the given size. + */ + public HttpHeaders(int size) { + this.headers = new HashMap<>(size); + } + + /** + * Create a HttpHeaders instance with the provided initial headers. + * + * @param headers the map of initial headers + */ + public HttpHeaders(Map headers) { + this.headers = new HashMap<>(headers.size()); + for (final Map.Entry header : headers.entrySet()) { + this.set(header.getKey(), header.getValue()); + } + } + + /** + * Gets the number of headers in the collection. + * + * @return the number of headers in this collection. + */ + public int size() { + return headers.size(); + } + + /** + * Set a header. + * + * if header with same name already exists then the value will be overwritten. + * if value is null and header with provided name already exists then it will be removed. + * + * @param name the name + * @param value the value + * @return this HttpHeaders + */ + public HttpHeaders set(String name, String value) { + final String headerKey = name.toLowerCase(Locale.ROOT); + if (value == null) { + headers.remove(headerKey); + } else { + headers.put(headerKey, new HttpHeader(name, value)); + } + return this; + } + + /** + * Get the header value for the provided header name. Null will be returned if the header + * name isn't found. + * + * @param name the name of the header to look for + * @return The String value of the header, or null if the header isn't found + */ + public String value(String name) { + final HttpHeader header = getHeader(name); + return header == null ? null : header.value(); + } + + /** + * Get the header values for the provided header name. Null will be returned if + * the header name isn't found. + * + * @param name the name of the header to look for + * @return the values of the header, or null if the header isn't found + */ + public String[] values(String name) { + final HttpHeader header = getHeader(name); + return header == null ? null : header.values(); + } + + private HttpHeader getHeader(String headerName) { + final String headerKey = headerName.toLowerCase(Locale.ROOT); + return headers.get(headerKey); + } + + /** + * Get {@link Map} representation of the HttpHeaders collection. + * + * @return the headers as map + */ + public Map toMap() { + final Map result = new HashMap<>(headers.size()); + for (final HttpHeader header : headers.values()) { + result.put(header.name(), header.value()); + } + return result; + } + + @Override + public Iterator iterator() { + return headers.values().iterator(); + } + + @Override + public void serialize(JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { + jsonGenerator.writeObject(toMap()); + } + + @Override + public void serializeWithType(JsonGenerator jsonGenerator, SerializerProvider serializerProvider, TypeSerializer typeSerializer) throws IOException { + serialize(jsonGenerator, serializerProvider); + } +} diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java new file mode 100644 index 0000000000000..f1aeb6172c63c --- /dev/null +++ b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java @@ -0,0 +1,225 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.internal.http; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.handler.codec.http.HttpMethod; +import reactor.core.publisher.Flux; + +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; + +/** + * The outgoing Http request. + */ +public class HttpRequest { + private HttpMethod httpMethod; + private URI uri; + private int port; + private HttpHeaders headers; + private Flux body; + + /** + * Create a new HttpRequest instance. + * + * @param httpMethod the HTTP request method + * @param uri the target address to send the request to + */ + public HttpRequest(HttpMethod httpMethod, URI uri, int port, HttpHeaders httpHeaders) { + this.httpMethod = httpMethod; + this.uri = uri; + this.port = port; + this.headers = httpHeaders; + } + + /** + * Create a new HttpRequest instance. + * + * @param httpMethod the HTTP request method + * @param uri the target address to send the request to + */ + public HttpRequest(HttpMethod httpMethod, String uri, int port) throws URISyntaxException { + this.httpMethod = httpMethod; + this.uri = new URI(uri); + this.port = port; + this.headers = new HttpHeaders(); + } + + /** + * Create a new HttpRequest instance. + * + * @param httpMethod the HTTP request method + * @param uri the target address to send the request to + * @param headers the HTTP headers to use with this request + * @param body the request content + */ + public HttpRequest(HttpMethod httpMethod, URI uri, int port, HttpHeaders headers, Flux body) { + this.httpMethod = httpMethod; + this.uri = uri; + this.port = port; + this.headers = headers; + this.body = body; + } + + /** + * Get the request method. + * + * @return the request method + */ + public HttpMethod httpMethod() { + return httpMethod; + } + + /** + * Set the request method. + * + * @param httpMethod the request method + * @return this HttpRequest + */ + public HttpRequest withHttpMethod(HttpMethod httpMethod) { + this.httpMethod = httpMethod; + return this; + } + + /** + * Get the target port. + * + * @return the target port + */ + public int port() { + return port; + } + + /** + * Set the target port to send the request to. + * + * @param port target port + * @return this HttpRequest + */ + public HttpRequest withPort(int port) { + this.port = port; + return this; + } + + /** + * Get the target address. + * + * @return the target address + */ + public URI uri() { + return uri; + } + + /** + * Set the target address to send the request to. + * + * @param uri target address as {@link URI} + * @return this HttpRequest + */ + public HttpRequest withUri(URI uri) { + this.uri = uri; + return this; + } + + /** + * Get the request headers. + * + * @return headers to be sent + */ + public HttpHeaders headers() { + return headers; + } + + /** + * Set the request headers. + * + * @param headers the set of headers + * @return this HttpRequest + */ + public HttpRequest withHeaders(HttpHeaders headers) { + this.headers = headers; + return this; + } + + /** + * Set a request header, replacing any existing value. + * A null for {@code value} will remove the header if one with matching name exists. + * + * @param name the header name + * @param value the header value + * @return this HttpRequest + */ + public HttpRequest withHeader(String name, String value) { + headers.set(name, value); + return this; + } + + /** + * Get the request content. + * + * @return the content to be send + */ + public Flux body() { + return body; + } + + /** + * Set the request content. + * + * @param content the request content + * @return this HttpRequest + */ + public HttpRequest withBody(String content) { + final byte[] bodyBytes = content.getBytes(StandardCharsets.UTF_8); + return withBody(bodyBytes); + } + + /** + * Set the request content. + * The Content-Length header will be set based on the given content's length + * + * @param content the request content + * @return this HttpRequest + */ + public HttpRequest withBody(byte[] content) { + headers.set("Content-Length", String.valueOf(content.length)); + // Unpooled.wrappedBuffer(body) allocates ByteBuf from unpooled heap + return withBody(Flux.defer(() -> Flux.just(Unpooled.wrappedBuffer(content)))); + } + + /** + * Set request content. + *

+ * Caller must set the Content-Length header to indicate the length of the content, + * or use Transfer-Encoding: chunked. + * + * @param content the request content + * @return this HttpRequest + */ + public HttpRequest withBody(Flux content) { + this.body = content; + return this; + } +} diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java new file mode 100644 index 0000000000000..b9a48db61e331 --- /dev/null +++ b/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java @@ -0,0 +1,154 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.azure.data.cosmos.internal.http; + +import io.netty.buffer.ByteBuf; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.netty.Connection; + +import java.nio.charset.Charset; + +/** + * The type representing response of {@link HttpRequest}. + */ +public abstract class HttpResponse implements AutoCloseable { + private HttpRequest request; + + /** + * Get the response status code. + * + * @return the response status code + */ + public abstract int statusCode(); + + /** + * Lookup a response header with the provided name. + * + * @param name the name of the header to lookup. + * @return the value of the header, or null if the header doesn't exist in the response. + */ + public abstract String headerValue(String name); + + /** + * Get all response headers. + * + * @return the response headers + */ + public abstract HttpHeaders headers(); + + /** + * Get the publisher emitting response content chunks. + * + *

+ * Returns a stream of the response's body content. Emissions may occur on the + * Netty EventLoop threads which are shared across channels and should not be + * blocked. Blocking should be avoided as much as possible/practical in reactive + * programming but if you do use methods like {@code blockingSubscribe} or {@code blockingGet} + * on the stream then be sure to use {@code subscribeOn} and {@code observeOn} + * before the blocking call. For example: + * + *

+     * {@code
+     *   response.body()
+     *     .map(bb -> bb.limit())
+     *     .reduce((x,y) -> x + y)
+     *     .subscribeOn(Schedulers.io())
+     *     .observeOn(Schedulers.io())
+     *     .blockingGet();
+     * }
+     * 
+ *

+ * The above code is a simplistic example and would probably run fine without + * the `subscribeOn` and `observeOn` but should be considered a template for + * more complex situations. + * + * @return The response's content as a stream of {@link ByteBuf}. + */ + public abstract Flux body(); + + /** + * Get the response content as a byte[]. + * + * @return this response content as a byte[] + */ + public abstract Mono bodyAsByteArray(); + + /** + * Get the response content as a string. + * + * @return This response content as a string + */ + public abstract Mono bodyAsString(); + + /** + * Get the response content as a string. + * + * @param charset the charset to use as encoding + * @return This response content as a string + */ + public abstract Mono bodyAsString(Charset charset); + + /** + * Get the request which resulted in this response. + * + * @return the request which resulted in this response. + */ + public final HttpRequest request() { + return request; + } + + /** + * Sets the request which resulted in this HttpResponse. + * + * @param request the request + * @return this HTTP response + */ + public final HttpResponse withRequest(HttpRequest request) { + this.request = request; + return this; + } + + /** + * Get a new Response object wrapping this response with it's content + * buffered into memory. + * + * @return the new Response object + */ + public HttpResponse buffer() { + return new BufferedHttpResponse(this); + } + + /** + * Closes the response content stream, if any. + */ + @Override + public void close() { + } + + // package private for test purpose + Connection internConnection() { + return null; + } +} diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java b/commons/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java new file mode 100644 index 0000000000000..6776183c37c9f --- /dev/null +++ b/commons/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java @@ -0,0 +1,198 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.internal.http; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.logging.LogLevel; +import org.reactivestreams.Publisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.netty.ByteBufFlux; +import reactor.netty.Connection; +import reactor.netty.NettyOutbound; +import reactor.netty.http.client.HttpClientRequest; +import reactor.netty.http.client.HttpClientResponse; +import reactor.netty.resources.ConnectionProvider; +import reactor.netty.tcp.ProxyProvider; +import reactor.netty.tcp.TcpResources; + +import java.nio.charset.Charset; +import java.util.Objects; +import java.util.function.BiFunction; + +import static com.azure.data.cosmos.internal.http.HttpClientConfig.REACTOR_NETWORK_LOG_CATEGORY; + +/** + * HttpClient that is implemented using reactor-netty. + */ +class ReactorNettyClient implements HttpClient { + + private final Logger logger = LoggerFactory.getLogger(getClass().getSimpleName()); + + private HttpClientConfig httpClientConfig; + private reactor.netty.http.client.HttpClient httpClient; + private ConnectionProvider connectionProvider; + + /** + * Creates ReactorNettyClient with {@link ConnectionProvider}. + */ + ReactorNettyClient(ConnectionProvider connectionProvider, HttpClientConfig httpClientConfig) { + this.connectionProvider = connectionProvider; + this.httpClientConfig = httpClientConfig; + this.httpClient = reactor.netty.http.client.HttpClient.create(connectionProvider); + configureChannelPipelineHandlers(); + } + + private void configureChannelPipelineHandlers() { + this.httpClient = this.httpClient.tcpConfiguration(tcpClient -> { + if (LoggerFactory.getLogger(REACTOR_NETWORK_LOG_CATEGORY).isTraceEnabled()) { + tcpClient = tcpClient.wiretap(REACTOR_NETWORK_LOG_CATEGORY, LogLevel.TRACE); + } + if (this.httpClientConfig.getProxy() != null) { + tcpClient = tcpClient.proxy(typeSpec -> typeSpec.type(ProxyProvider.Proxy.HTTP).address(this.httpClientConfig.getProxy())); + } + return tcpClient; + }); + } + + @Override + public Mono send(final HttpRequest request) { + Objects.requireNonNull(request.httpMethod()); + Objects.requireNonNull(request.uri()); + Objects.requireNonNull(this.httpClientConfig); + + return this.httpClient + .port(request.port()) + .request(HttpMethod.valueOf(request.httpMethod().toString())) + .uri(request.uri().toString()) + .send(bodySendDelegate(request)) + .responseConnection(responseDelegate(request)) + .single(); + } + + /** + * Delegate to send the request content. + * + * @param restRequest the Rest request contains the body to be sent + * @return a delegate upon invocation sets the request body in reactor-netty outbound object + */ + private static BiFunction> bodySendDelegate(final HttpRequest restRequest) { + return (reactorNettyRequest, reactorNettyOutbound) -> { + for (HttpHeader header : restRequest.headers()) { + reactorNettyRequest.header(header.name(), header.value()); + } + if (restRequest.body() != null) { + Flux nettyByteBufFlux = restRequest.body().map(Unpooled::wrappedBuffer); + return reactorNettyOutbound.options(sendOptions -> sendOptions.flushOnEach(false)).send(nettyByteBufFlux); + } else { + return reactorNettyOutbound.options(sendOptions -> sendOptions.flushOnEach(false)); + } + }; + } + + /** + * Delegate to receive response. + * + * @param restRequest the Rest request whose response this delegate handles + * @return a delegate upon invocation setup Rest response object + */ + private static BiFunction> responseDelegate(final HttpRequest restRequest) { + return (reactorNettyResponse, reactorNettyConnection) -> + Mono.just(new ReactorNettyHttpResponse(reactorNettyResponse, reactorNettyConnection).withRequest(restRequest)); + } + + @Override + public void shutdown() { + TcpResources.disposeLoopsAndConnections(); + this.connectionProvider.dispose(); + } + + private static class ReactorNettyHttpResponse extends HttpResponse { + private final HttpClientResponse reactorNettyResponse; + private final Connection reactorNettyConnection; + + ReactorNettyHttpResponse(HttpClientResponse reactorNettyResponse, Connection reactorNettyConnection) { + this.reactorNettyResponse = reactorNettyResponse; + this.reactorNettyConnection = reactorNettyConnection; + } + + @Override + public int statusCode() { + return reactorNettyResponse.status().code(); + } + + @Override + public String headerValue(String name) { + return reactorNettyResponse.responseHeaders().get(name); + } + + @Override + public HttpHeaders headers() { + HttpHeaders headers = new HttpHeaders(reactorNettyResponse.responseHeaders().size()); + reactorNettyResponse.responseHeaders().forEach(e -> headers.set(e.getKey(), e.getValue())); + return headers; + } + + @Override + public Flux body() { + return bodyIntern().doFinally(s -> this.close()); + } + + @Override + public Mono bodyAsByteArray() { + return bodyIntern().aggregate().asByteArray().doFinally(s -> this.close()); + } + + @Override + public Mono bodyAsString() { + return bodyIntern().aggregate().asString().doFinally(s -> this.close()); + } + + @Override + public Mono bodyAsString(Charset charset) { + return bodyIntern().aggregate().asString(charset).doFinally(s -> this.close()); + } + + @Override + public void close() { + if (reactorNettyConnection.channel().eventLoop().inEventLoop()) { + reactorNettyConnection.dispose(); + } else { + reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); + } + } + + private ByteBufFlux bodyIntern() { + return reactorNettyConnection.inbound().receive(); + } + + @Override + Connection internConnection() { + return reactorNettyConnection; + } + } +} diff --git a/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java b/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java index fb3e24bf486bd..a727b4036229d 100644 --- a/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java @@ -23,17 +23,11 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.internal.HttpConstants; -import io.netty.handler.codec.http.DefaultHttpHeaders; -import io.netty.handler.codec.http.DefaultHttpResponse; -import io.netty.handler.codec.http.HttpHeaders; -import io.netty.handler.codec.http.HttpResponse; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.netty.handler.codec.http.HttpVersion; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpResponse; +import org.mockito.Mockito; import org.testng.annotations.Test; -import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map.Entry; import java.util.Set; @@ -45,14 +39,13 @@ public class HttpUtilsTest { private static final String OWNER_FULL_NAME_VALUE = "dbs/RxJava.SDKTest.SharedDatabase_20190304T121302_iZc/colls/+%20-_,:.%7C~b2d67001-9000-454e-a140-abceb1756c48%20+-_,:.%7C~"; @Test(groups = { "unit" }) - public void verifyConversionOfHttpResponseHeadersToMap() throws UnsupportedEncodingException { - HttpHeaders headersMap = new DefaultHttpHeaders(); - headersMap.add(HttpConstants.HttpHeaders.OWNER_FULL_NAME, OWNER_FULL_NAME_VALUE); + public void verifyConversionOfHttpResponseHeadersToMap() { + HttpHeaders headersMap = new HttpHeaders(1); + headersMap.set(HttpConstants.HttpHeaders.OWNER_FULL_NAME, OWNER_FULL_NAME_VALUE); - HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_0, - HttpResponseStatus.ACCEPTED, - headersMap); - HttpResponseHeaders httpResponseHeaders = new HttpClientResponse(httpResponse, null).getHeaders(); + HttpResponse httpResponse = Mockito.mock(HttpResponse.class); + Mockito.when(httpResponse.headers()).thenReturn(headersMap); + HttpHeaders httpResponseHeaders = httpResponse.headers(); Set> resultHeadersSet = HttpUtils.asMap(httpResponseHeaders).entrySet(); assertThat(resultHeadersSet.size()).isEqualTo(1); @@ -60,7 +53,7 @@ public void verifyConversionOfHttpResponseHeadersToMap() throws UnsupportedEncod assertThat(entry.getKey()).isEqualTo(HttpConstants.HttpHeaders.OWNER_FULL_NAME); assertThat(entry.getValue()).isEqualTo(HttpUtils.urlDecode(OWNER_FULL_NAME_VALUE)); - List> resultHeadersList = HttpUtils.unescape(httpResponseHeaders.entries()); + List> resultHeadersList = HttpUtils.unescape(httpResponseHeaders.toMap().entrySet()); assertThat(resultHeadersList.size()).isEqualTo(1); entry = resultHeadersSet.iterator().next(); assertThat(entry.getKey()).isEqualTo(HttpConstants.HttpHeaders.OWNER_FULL_NAME); diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java b/commons/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java index d69fdaa70bf69..1a06987926f2d 100644 --- a/commons/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java @@ -45,7 +45,7 @@ public void maxHttpBodyLength() { @Test(groups = { "unit" }) public void getProtocol() { Configs config = new Configs(); - assertThat(config.getProtocol()).isEqualTo(Protocol.valueOf(System.getProperty("cosmos.directModeProtocol", "TCP"))); + assertThat(config.getProtocol()).isEqualTo(Protocol.valueOf(System.getProperty("cosmos.directModeProtocol", "TCP").toUpperCase())); } @Test(groups = { "unit" }) diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java b/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java index da6e0a904a988..32e446ccb385b 100644 --- a/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java @@ -28,7 +28,7 @@ import org.apache.commons.lang3.StringUtils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.nio.charset.StandardCharsets; import java.util.UUID; @@ -180,7 +180,7 @@ public void createWithResourceIdURL(String documentUrlWithId, String documentUrl assertThat(request.getResourceId()).isEqualTo("IXYFAOHEBPMBAAAAAAAAAA=="); assertThat(request.getContent()).isEqualTo(document.toJson().getBytes(StandardCharsets.UTF_8)); - Observable inputStream = Observable.just(document.toJson().getBytes(StandardCharsets.UTF_8)); + Flux inputStream = Flux.just(document.toJson().getBytes(StandardCharsets.UTF_8)); request = RxDocumentServiceRequest.create(operationType, ResourceType.Document, documentUrlWithId, inputStream, new HashedMap(), AuthorizationTokenType.SecondaryMasterKey); assertThat(request.authorizationTokenType).isEqualTo(AuthorizationTokenType.SecondaryMasterKey); @@ -222,7 +222,7 @@ public void createWithResourceNameURL(String documentUrlWithId, String documentU assertThat(request.getResourceId()).isNull(); Document document = getDocumentDefinition(); - Observable inputStream = Observable.just(document.toJson().getBytes(StandardCharsets.UTF_8)); + Flux inputStream = Flux.just(document.toJson().getBytes(StandardCharsets.UTF_8)); request = RxDocumentServiceRequest.create(operationType, ResourceType.Document, documentUrlWithName, diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java index b167739a0db6f..37f1efadeaeaa 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java @@ -46,10 +46,10 @@ import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; -import rx.functions.Func1; +import reactor.core.publisher.Mono; import java.util.concurrent.Callable; +import java.util.function.Function; /** * Abstracts out the logic to resolve physical replica addresses for the given {@link RxDocumentServiceRequest} @@ -79,23 +79,23 @@ public void initializeCaches( this.collectionRoutingMapCache = collectionRoutingMapCache; } - public Single resolveAsync( + public Mono resolveAsync( RxDocumentServiceRequest request, boolean forceRefreshPartitionAddresses) { - Single resultObs = this.resolveAddressesAndIdentityAsync(request, forceRefreshPartitionAddresses); + Mono resultObs = this.resolveAddressesAndIdentityAsync(request, forceRefreshPartitionAddresses); return resultObs.flatMap(result -> { try { this.throwIfTargetChanged(request, result.TargetPartitionKeyRange); } catch (Exception e) { - return Single.error(e); + return Mono.error(e); } request.requestContext.resolvedPartitionKeyRange = result.TargetPartitionKeyRange; - return Single.just(result.Addresses); + return Mono.just(result.Addresses); }); } @@ -199,7 +199,7 @@ private static void ensureRoutingMapPresent( } } - private Single tryResolveServerPartitionAsync( + private Mono tryResolveServerPartitionAsync( RxDocumentServiceRequest request, DocumentCollection collection, CollectionRoutingMap routingMap, @@ -229,7 +229,7 @@ private Single tryResolveServerPartitionAsync( request.getResourceType(), request.getOperationType(), request.getResourceAddress()); - return Single.error(BridgeInternal.setResourceAddress(new InternalServerErrorException(RMResources.InternalServerError), request.getResourceAddress())); + return Mono.error(BridgeInternal.setResourceAddress(new InternalServerErrorException(RMResources.InternalServerError), request.getResourceAddress())); } PartitionKeyRange range; @@ -247,30 +247,25 @@ private Single tryResolveServerPartitionAsync( } if (range == null) { - // Collection cache or routing map cache is potentially outdated. Return null - + // Collection cache or routing map cache is potentially outdated. Return empty - // upper logic will refresh cache and retry. - return null; + return Mono.empty(); } - Single addressesObs = this.addressCache.tryGetAddresses( + Mono addressesObs = this.addressCache.tryGetAddresses( request, new PartitionKeyRangeIdentity(collection.resourceId(), range.id()), forceRefreshPartitionAddresses); - return addressesObs.flatMap(addresses -> { - - if (addresses == null) { - logger.info( - "Could not resolve addresses for identity {}/{}. Potentially collection cache or routing map cache is outdated. Return null - upper logic will refresh and retry. ", + return addressesObs.flatMap(addresses -> Mono.just(new ResolutionResult(range, addresses))).switchIfEmpty(Mono.defer(() -> { + logger.info( + "Could not resolve addresses for identity {}/{}. Potentially collection cache or routing map cache is outdated. Return empty - upper logic will refresh and retry. ", new PartitionKeyRangeIdentity(collection.resourceId(), range.id())); - return Single.just(null); - } - - return Single.just(new ResolutionResult(range, addresses)); - }); + return Mono.empty(); + })); } catch (Exception e) { - return Single.error(e); + return Mono.error(e); } } @@ -292,7 +287,7 @@ private PartitionKeyRange tryResolveSinglePartitionCollection( // So we route request to the first partition. If this is non-partitioned collection - request will succeed. // If it is partitioned collection - backend will return bad request as partition key header is required in this case. if (routingMap.getOrderedPartitionKeyRanges().size() == 1) { - return (PartitionKeyRange) routingMap.getOrderedPartitionKeyRanges().get(0); + return routingMap.getOrderedPartitionKeyRanges().get(0); } if (collectionCacheIsUptoDate) { @@ -302,33 +297,27 @@ private PartitionKeyRange tryResolveSinglePartitionCollection( } } - private Single resolveMasterResourceAddress(RxDocumentServiceRequest request, + private Mono resolveMasterResourceAddress(RxDocumentServiceRequest request, boolean forceRefreshPartitionAddresses) { assert ReplicatedResourceClient.isReadingFromMaster(request.getResourceType(), request.getOperationType()) && request.getPartitionKeyRangeIdentity() == null; // ServiceIdentity serviceIdentity = this.masterServiceIdentity; - PartitionKeyRangeIdentity partitionKeyRangeIdentity = this.masterPartitionKeyRangeIdentity; - Single addressesObs = this.addressCache.tryGetAddresses( - request, - partitionKeyRangeIdentity, - forceRefreshPartitionAddresses); + Mono addressesObs = this.addressCache.tryGetAddresses(request, + masterPartitionKeyRangeIdentity,forceRefreshPartitionAddresses); return addressesObs.flatMap(addresses -> { - if (addresses == null) { - logger.warn("Could not get addresses for master partition"); - - // return Observable.error() - NotFoundException e = new NotFoundException(); - BridgeInternal.setResourceAddress(e, request.getResourceAddress()); - return Single.error(e); - } - PartitionKeyRange partitionKeyRange = new PartitionKeyRange(); partitionKeyRange.id(PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID); - return Single.just(new ResolutionResult(partitionKeyRange, addresses)); + return Mono.just(new ResolutionResult(partitionKeyRange, addresses)); + }).switchIfEmpty(Mono.defer(() -> { + logger.warn("Could not get addresses for master partition"); - }); + // return Observable.error() + NotFoundException e = new NotFoundException(); + BridgeInternal.setResourceAddress(e, request.getResourceAddress()); + return Mono.error(e); + })); } private class RefreshState { @@ -340,7 +329,7 @@ private class RefreshState { volatile ResolutionResult resolutionResult; } - private Single getOrRefreshRoutingMap(RxDocumentServiceRequest request, boolean forceRefreshPartitionAddresses) { + private Mono getOrRefreshRoutingMap(RxDocumentServiceRequest request, boolean forceRefreshPartitionAddresses) { RefreshState state = new RefreshState(); @@ -348,11 +337,11 @@ private Single getOrRefreshRoutingMap(RxDocumentServiceRequest req (request.getPartitionKeyRangeIdentity() != null && request.getPartitionKeyRangeIdentity().getCollectionRid() != null); state.collectionRoutingMapCacheIsUptoDate = false; - Single collectionObs = this.collectionCache.resolveCollectionAsync(request); + Mono collectionObs = this.collectionCache.resolveCollectionAsync(request); - Single stateObs = collectionObs.flatMap(collection -> { + Mono stateObs = collectionObs.flatMap(collection -> { state.collection = collection; - Single routingMapObs = + Mono routingMapObs = this.collectionRoutingMapCache.tryLookupAsync(collection.resourceId(), null, request.forceCollectionRoutingMapRefresh, request.properties); final DocumentCollection underlyingCollection = collection; return routingMapObs.flatMap(routingMap -> { @@ -368,11 +357,16 @@ private Single getOrRefreshRoutingMap(RxDocumentServiceRequest req return state; }); } - } - return Single.just(state); - }); + return Mono.just(state); + }).switchIfEmpty(Mono.defer(() -> { + if (request.forcePartitionKeyRangeRefresh) { + state.collectionRoutingMapCacheIsUptoDate = true; + request.forcePartitionKeyRangeRefresh = false; + } + return Mono.just(state); + })); }); return stateObs.flatMap(newState -> { @@ -384,11 +378,11 @@ private Single getOrRefreshRoutingMap(RxDocumentServiceRequest req newState.collectionCacheIsUptoDate = true; newState.collectionRoutingMapCacheIsUptoDate = false; - Single newCollectionObs = this.collectionCache.resolveCollectionAsync(request); + Mono newCollectionObs = this.collectionCache.resolveCollectionAsync(request); return newCollectionObs.flatMap(collection -> { newState.collection = collection; - Single newRoutingMapObs = this.collectionRoutingMapCache.tryLookupAsync( + Mono newRoutingMapObs = this.collectionRoutingMapCache.tryLookupAsync( collection.resourceId(), null, request.properties); @@ -402,15 +396,18 @@ private Single getOrRefreshRoutingMap(RxDocumentServiceRequest req } - return Single.just(newState); + return Mono.just(newState); }); } - private Single getStateWithNewRoutingMap(RefreshState state, Single routingMapSingle) { + private Mono getStateWithNewRoutingMap(RefreshState state, Mono routingMapSingle) { return routingMapSingle.map(r -> { state.routingMap = r; return state; - }); + }).switchIfEmpty(Mono.fromSupplier(() -> { + state.routingMap = null; + return state; + })); } /** @@ -420,7 +417,7 @@ private Single getStateWithNewRoutingMap(RefreshState state, Singl * @param forceRefreshPartitionAddresses Force refresh the partition's endpoint * @return ResolutionResult */ - private Single resolveAddressesAndIdentityAsync( + private Mono resolveAddressesAndIdentityAsync( RxDocumentServiceRequest request, boolean forceRefreshPartitionAddresses) { @@ -429,7 +426,7 @@ private Single resolveAddressesAndIdentityAsync( return resolveMasterResourceAddress(request, forceRefreshPartitionAddresses); } - Single refreshStateObs = this.getOrRefreshRoutingMap(request, forceRefreshPartitionAddresses); + Mono refreshStateObs = this.getOrRefreshRoutingMap(request, forceRefreshPartitionAddresses); return refreshStateObs.flatMap( state -> { @@ -437,11 +434,11 @@ private Single resolveAddressesAndIdentityAsync( AddressResolver.ensureRoutingMapPresent(request, state.routingMap, state.collection); } catch (Exception e) { - return Single.error(e); + return Mono.error(e); } // At this point we have both collection and routingMap. - Single resultObs = this.tryResolveServerPartitionAsync( + Mono resultObs = this.tryResolveServerPartitionAsync( request, state.collection, state.routingMap, @@ -450,61 +447,56 @@ private Single resolveAddressesAndIdentityAsync( forceRefreshPartitionAddresses); - return resultObs.flatMap(result -> { - Func1> addCollectionRidIfNameBased = funcResolutionResult -> { - assert funcResolutionResult != null; - if (request.getIsNameBased()) { - // Append collection rid. - // If we resolved collection rid incorrectly because of outdated cache, this can lead - // to incorrect routing decisions. But backend will validate collection rid and throw - // InvalidPartitionException if we reach wrong collection. - // Also this header will be used by backend to inject collection rid into metrics for - // throttled requests. - request.getHeaders().put(WFConstants.BackendHeaders.COLLECTION_RID, state.collection.resourceId()); - } - - return Single.just(funcResolutionResult); - }; - - if (result != null) { - return addCollectionRidIfNameBased.call(result); + Function> addCollectionRidIfNameBased = funcResolutionResult -> { + assert funcResolutionResult != null; + if (request.getIsNameBased()) { + // Append collection rid. + // If we resolved collection rid incorrectly because of outdated cache, this can lead + // to incorrect routing decisions. But backend will validate collection rid and throw + // InvalidPartitionException if we reach wrong collection. + // Also this header will be used by backend to inject collection rid into metrics for + // throttled requests. + request.getHeaders().put(WFConstants.BackendHeaders.COLLECTION_RID, state.collection.resourceId()); } - // result is null: - assert result == null; + return Mono.just(funcResolutionResult); + }; - Func1> ensureCollectionRoutingMapCacheIsUptoDateFunc = funcState -> { + return resultObs.flatMap(addCollectionRidIfNameBased).switchIfEmpty(Mono.defer(() -> { + // result is empty + + Function> ensureCollectionRoutingMapCacheIsUptoDateFunc = funcState -> { if (!funcState.collectionRoutingMapCacheIsUptoDate) { funcState.collectionRoutingMapCacheIsUptoDate = true; - Single newRoutingMapObs = this.collectionRoutingMapCache.tryLookupAsync( - funcState.collection.resourceId(), - funcState.routingMap, - request.properties); + Mono newRoutingMapObs = this.collectionRoutingMapCache.tryLookupAsync( + funcState.collection.resourceId(), + funcState.routingMap, + request.properties); return getStateWithNewRoutingMap(funcState, newRoutingMapObs); } else { - return Single.just(state); + return Mono.just(state); } }; - Func1> resolveServerPartition = funcState -> { + Function> resolveServerPartition = funcState -> { try { AddressResolver.ensureRoutingMapPresent(request, funcState.routingMap, funcState.collection); } catch (Exception e) { - return Single.error(e); + return Mono.error(e); } return this.tryResolveServerPartitionAsync( - request, - funcState.collection, - funcState.routingMap, - true, - true, - forceRefreshPartitionAddresses); + request, + funcState.collection, + funcState.routingMap, + true, + true, + forceRefreshPartitionAddresses); }; - Func1> onNullThrowNotFound = funcResolutionResult -> { + Function> onNullThrowNotFound = funcResolutionResult -> { if (funcResolutionResult == null) { logger.debug("Couldn't route partitionkeyrange-oblivious request after retry/cache refresh. Collection doesn't exist."); @@ -512,10 +504,10 @@ private Single resolveAddressesAndIdentityAsync( // The only reason we will get here is if collection doesn't exist. // Case when partition-key-range doesn't exist is handled in the corresponding method. - return Single.error(BridgeInternal.setResourceAddress(new NotFoundException(), request.getResourceAddress())); + return Mono.error(BridgeInternal.setResourceAddress(new NotFoundException(), request.getResourceAddress())); } - return Single.just(funcResolutionResult); + return Mono.just(funcResolutionResult); }; // Couldn't resolve server partition or its addresses. @@ -524,35 +516,37 @@ private Single resolveAddressesAndIdentityAsync( request.forceNameCacheRefresh = true; state.collectionCacheIsUptoDate = true; - Single newCollectionObs = this.collectionCache.resolveCollectionAsync(request); - Single newRefreshStateObs = newCollectionObs.flatMap(collection -> { + Mono newCollectionObs = this.collectionCache.resolveCollectionAsync(request); + Mono newRefreshStateObs = newCollectionObs.flatMap(collection -> { state.collection = collection; if (collection.resourceId() != state.routingMap.getCollectionUniqueId()) { // Collection cache was stale. We resolved to new Rid. routing map cache is potentially stale // for this new collection rid. Mark it as such. state.collectionRoutingMapCacheIsUptoDate = false; - Single newRoutingMap = this.collectionRoutingMapCache.tryLookupAsync( - collection.resourceId(), - null, - request.properties); + Mono newRoutingMap = this.collectionRoutingMapCache.tryLookupAsync( + collection.resourceId(), + null, + request.properties); return getStateWithNewRoutingMap(state, newRoutingMap); } - return Single.just(state); + return Mono.just(state); }); - Single newResultObs = newRefreshStateObs.flatMap(ensureCollectionRoutingMapCacheIsUptoDateFunc::call) - .flatMap(resolveServerPartition::call); + Mono newResultObs = newRefreshStateObs.flatMap(ensureCollectionRoutingMapCacheIsUptoDateFunc) + .flatMap(resolveServerPartition); - return newResultObs.flatMap(onNullThrowNotFound::call).flatMap(addCollectionRidIfNameBased::call); + return newResultObs.flatMap(onNullThrowNotFound).flatMap(addCollectionRidIfNameBased); } else { - return ensureCollectionRoutingMapCacheIsUptoDateFunc.call(state) - .flatMap(resolveServerPartition::call).flatMap(onNullThrowNotFound).flatMap(addCollectionRidIfNameBased); + return ensureCollectionRoutingMapCacheIsUptoDateFunc.apply(state) + .flatMap(resolveServerPartition) + .flatMap(onNullThrowNotFound) + .flatMap(addCollectionRidIfNameBased); } - }); + })); } ); } @@ -576,15 +570,15 @@ private ResolutionResult handleRangeAddressResolutionFailure( return null; } - private Single returnOrError(Callable function) { + private Mono returnOrError(Callable function) { try { - return Single.just(function.call()); + return Mono.justOrEmpty(function.call()); } catch (Exception e) { - return Single.error(e); + return Mono.error(e); } } - private Single tryResolveServerPartitionByPartitionKeyRangeIdAsync( + private Mono tryResolveServerPartitionByPartitionKeyRangeIdAsync( RxDocumentServiceRequest request, DocumentCollection collection, CollectionRoutingMap routingMap, @@ -598,25 +592,20 @@ private Single tryResolveServerPartitionByPartitionKeyRangeIdA return returnOrError(() -> this.handleRangeAddressResolutionFailure(request, collectionCacheIsUpToDate, routingMapCacheIsUpToDate, routingMap)); } - Single addressesObs = this.addressCache.tryGetAddresses( + Mono addressesObs = this.addressCache.tryGetAddresses( request, new PartitionKeyRangeIdentity(collection.resourceId(), request.getPartitionKeyRangeIdentity().getPartitionKeyRangeId()), forceRefreshPartitionAddresses); - return addressesObs.flatMap(addresses -> { + return addressesObs.flatMap(addresses -> Mono.just(new ResolutionResult(partitionKeyRange, addresses))).switchIfEmpty(Mono.defer(() -> { + logger.debug("Cannot resolve addresses for range '{}'", request.getPartitionKeyRangeIdentity().toHeader()); - if (addresses == null) { - logger.debug("Cannot resolve addresses for range '{}'", request.getPartitionKeyRangeIdentity().toHeader()); - - try { - return Single.just(this.handleRangeAddressResolutionFailure(request, collectionCacheIsUpToDate, routingMapCacheIsUpToDate, routingMap)); - } catch (CosmosClientException e) { - return Single.error(e); - } + try { + return Mono.justOrEmpty(this.handleRangeAddressResolutionFailure(request, collectionCacheIsUpToDate, routingMapCacheIsUpToDate, routingMap)); + } catch (CosmosClientException e) { + return Mono.error(e); } - - return Single.just(new ResolutionResult(partitionKeyRange, addresses)); - }); + })); } private PartitionKeyRange tryResolveServerPartitionByPartitionKey( @@ -694,12 +683,12 @@ private PartitionKeyRange tryResolveServerPartitionByPartitionKey( } private class ResolutionResult { - public final PartitionKeyRange TargetPartitionKeyRange; - public final AddressInformation[] Addresses; + final PartitionKeyRange TargetPartitionKeyRange; + final AddressInformation[] Addresses; - public ResolutionResult( - PartitionKeyRange targetPartitionKeyRange, - AddressInformation[] addresses) { + ResolutionResult( + PartitionKeyRange targetPartitionKeyRange, + AddressInformation[] addresses) { if (targetPartitionKeyRange == null) { throw new NullPointerException("targetPartitionKeyRange"); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java index bca577ce6a76d..9737533ae0eb3 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Strings; -import rx.Single; +import reactor.core.publisher.Mono; import java.net.URI; import java.util.Arrays; @@ -41,22 +41,22 @@ public AddressSelector(IAddressResolver addressResolver, Protocol protocol) { this.protocol = protocol; } - public Single> resolveAllUriAsync( + public Mono> resolveAllUriAsync( RxDocumentServiceRequest request, boolean includePrimary, boolean forceRefresh) { - Single> allReplicaAddressesObs = this.resolveAddressesAsync(request, forceRefresh); + Mono> allReplicaAddressesObs = this.resolveAddressesAsync(request, forceRefresh); return allReplicaAddressesObs.map(allReplicaAddresses -> allReplicaAddresses.stream().filter(a -> includePrimary || !a.isPrimary()) .map(a -> HttpUtils.toURI(a.getPhysicalUri())).collect(Collectors.toList())); } - public Single resolvePrimaryUriAsync(RxDocumentServiceRequest request, boolean forceAddressRefresh) { - Single> replicaAddressesObs = this.resolveAddressesAsync(request, forceAddressRefresh); + public Mono resolvePrimaryUriAsync(RxDocumentServiceRequest request, boolean forceAddressRefresh) { + Mono> replicaAddressesObs = this.resolveAddressesAsync(request, forceAddressRefresh); return replicaAddressesObs.flatMap(replicaAddresses -> { try { - return Single.just(AddressSelector.getPrimaryUri(request, replicaAddresses)); + return Mono.just(AddressSelector.getPrimaryUri(request, replicaAddresses)); } catch (Exception e) { - return Single.error(e); + return Mono.error(e); } }); } @@ -77,19 +77,17 @@ public static URI getPrimaryUri(RxDocumentServiceRequest request, List address.getPhysicalUri()).collect(Collectors.toList()))), null); + replicaAddresses.stream().map(AddressInformation::getPhysicalUri).collect(Collectors.joining(","))), null); } return HttpUtils.toURI(primaryAddress.getPhysicalUri()); } - public Single> resolveAddressesAsync(RxDocumentServiceRequest request, boolean forceAddressRefresh) { - Single> resolvedAddressesObs = + public Mono> resolveAddressesAsync(RxDocumentServiceRequest request, boolean forceAddressRefresh) { + Mono> resolvedAddressesObs = (this.addressResolver.resolveAsync(request, forceAddressRefresh)) .map(addresses -> Arrays.stream(addresses) - .filter(address -> { - return !Strings.isNullOrEmpty(address.getPhysicalUri()) && Strings.areEqualIgnoreCase(address.getProtocolScheme(), this.protocol.scheme()); - }) + .filter(address -> !Strings.isNullOrEmpty(address.getPhysicalUri()) && Strings.areEqualIgnoreCase(address.getProtocolScheme(), this.protocol.scheme())) .collect(Collectors.toList())); return resolvedAddressesObs.map( @@ -98,7 +96,7 @@ public Single> resolveAddressesAsync(RxDocumentServiceR if (r.size() > 0) { return r; } else { - return resolvedAddresses.stream().filter(address -> address.isPublic()).collect(Collectors.toList()); + return resolvedAddresses.stream().filter(AddressInformation::isPublic).collect(Collectors.toList()); } } ); diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java index 58db1cd1d31ec..d0c7ea2013f05 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java @@ -37,15 +37,15 @@ import com.azure.data.cosmos.internal.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; -import rx.exceptions.Exceptions; +import reactor.core.Exceptions; +import reactor.core.publisher.Mono; import java.util.Map; public class BarrierRequestHelper { private final static Logger logger = LoggerFactory.getLogger(BarrierRequestHelper.class); - public static Single createAsync( + public static Mono createAsync( RxDocumentServiceRequest request, IAuthorizationTokenProvider authorizationTokenProvider, Long targetLsn, @@ -123,7 +123,7 @@ public static Single createAsync( String unknownAuthToken = "Unknown authorization token kind for read request"; assert false : unknownAuthToken; logger.error(unknownAuthToken); - Exceptions.propagate(new InternalServerErrorException(RMResources.InternalServerError)); + throw Exceptions.propagate(new InternalServerErrorException(RMResources.InternalServerError)); } barrierLsnRequest.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorizationToken); @@ -139,7 +139,7 @@ public static Single createAsync( barrierLsnRequest.getHeaders().put(WFConstants.BackendHeaders.COLLECTION_RID, request.getHeaders().get(WFConstants.BackendHeaders.COLLECTION_RID)); } - return Single.just(barrierLsnRequest); + return Mono.just(barrierLsnRequest); } static boolean isCollectionHeadBarrierRequest(ResourceType resourceType, OperationType operationType) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java index e0e54d923e864..8a1527565a304 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -57,8 +57,8 @@ public ConflictException(String msg, String resourceAddress) { super(msg, null, null, HttpConstants.StatusCodes.CONFLICT, resourceAddress); } - public ConflictException(String message, HttpResponseHeaders headers, String requestUri) { - this(message, null, headers, requestUri); + public ConflictException(String message, HttpHeaders headers, String requestUriString) { + this(message, null, headers, requestUriString); } public ConflictException(Exception innerException) { @@ -71,12 +71,12 @@ public ConflictException(Error error, Map headers) { public ConflictException(String message, Exception innerException, - HttpResponseHeaders headers, - String requestUri) { + HttpHeaders headers, + String requestUriString) { super(String.format("%s: %s", RMResources.EntityAlreadyExists, message), innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.CONFLICT, - requestUri); + requestUriString); } } \ No newline at end of file diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java index 3f1b798379ec2..2427dee230453 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java @@ -37,7 +37,7 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; +import reactor.core.publisher.Mono; import java.util.HashMap; import java.util.List; @@ -172,12 +172,12 @@ public class ConsistencyReader { private final Configs configs; public ConsistencyReader( - Configs configs, - AddressSelector addressSelector, - ISessionContainer sessionContainer, - TransportClient transportClient, - GatewayServiceConfigurationReader serviceConfigReader, - IAuthorizationTokenProvider authorizationTokenProvider) { + Configs configs, + AddressSelector addressSelector, + ISessionContainer sessionContainer, + TransportClient transportClient, + GatewayServiceConfigurationReader serviceConfigReader, + IAuthorizationTokenProvider authorizationTokenProvider) { this.configs = configs; this.addressSelector = addressSelector; this.serviceConfigReader = serviceConfigReader; @@ -186,18 +186,18 @@ public ConsistencyReader( this.quorumReader = createQuorumReader(transportClient, addressSelector, this.storeReader, serviceConfigReader, authorizationTokenProvider); } - public Single readAsync(RxDocumentServiceRequest entity, - TimeoutHelper timeout, - boolean isInRetry, - boolean forceRefresh) { + public Mono readAsync(RxDocumentServiceRequest entity, + TimeoutHelper timeout, + boolean isInRetry, + boolean forceRefresh) { if (!isInRetry) { if (timeout.isElapsed()) { - return Single.error(new RequestTimeoutException()); + return Mono.error(new RequestTimeoutException()); } } else { if (timeout.isElapsed()) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } } @@ -219,7 +219,7 @@ public Single readAsync(RxDocumentServiceRequest entity, try { desiredReadMode = this.deduceReadMode(entity, targetConsistencyLevel, useSessionToken); } catch (CosmosClientException e) { - return Single.error(e); + return Mono.error(e); } int maxReplicaCount = this.getMaxReplicaSetSize(entity); int readQuorumValue = maxReplicaCount - (maxReplicaCount / 2); @@ -259,97 +259,83 @@ public Single readAsync(RxDocumentServiceRequest entity, } } - private Single readPrimaryAsync(RxDocumentServiceRequest entity, - boolean useSessionToken) { + private Mono readPrimaryAsync(RxDocumentServiceRequest entity, + boolean useSessionToken) { - Single responseObs = this.storeReader.readPrimaryAsync( - entity, - false /*required valid LSN*/, - useSessionToken); + Mono responseObs = this.storeReader.readPrimaryAsync( + entity, + false /*required valid LSN*/, + useSessionToken); return responseObs.flatMap(response -> { try { - return Single.just(response.toResponse()); + return Mono.just(response.toResponse()); } catch (CosmosClientException e) { - // TODO: RxJava1 due to design flaw doesn't allow throwing checked exception - // RxJava2 has fixed this design flaw, - // once we switched to RxJava2 we can get rid of unnecessary catch block - // also we can switch to Observable.map(.) - return Single.error(e); + return Mono.error(e); } }); } - private Single readAnyAsync(RxDocumentServiceRequest entity, - ReadMode readMode) { - Single> responsesObs = this.storeReader.readMultipleReplicaAsync( - entity, - /* includePrimary */ true, - /* replicaCountToRead */ 1, - /* requiresValidLSN*/ false, - /* useSessionToken */ false, - /* readMode */ readMode); + private Mono readAnyAsync(RxDocumentServiceRequest entity, + ReadMode readMode) { + Mono> responsesObs = this.storeReader.readMultipleReplicaAsync( + entity, + /* includePrimary */ true, + /* replicaCountToRead */ 1, + /* requiresValidLSN*/ false, + /* useSessionToken */ false, + /* readMode */ readMode); return responsesObs.flatMap( responses -> { - if (responses.size() == 0) { - return Single.error(new GoneException(RMResources.Gone)); - } + if (responses.size() == 0) { + return Mono.error(new GoneException(RMResources.Gone)); + } - try { - return Single.just(responses.get(0).toResponse()); - } catch (CosmosClientException e) { - // TODO: RxJava1 due to design flaw doesn't allow throwing checked exception - // RxJava2 has fixed this design flaw, - // once we switched to RxJava2 we can get rid of unnecessary catch block - // also we can switch to Observable.map(.) - return Single.error(e); - } + try { + return Mono.just(responses.get(0).toResponse()); + } catch (CosmosClientException e) { + return Mono.error(e); + } } ); } - private Single readSessionAsync(RxDocumentServiceRequest entity, - ReadMode readMode) { + private Mono readSessionAsync(RxDocumentServiceRequest entity, + ReadMode readMode) { if (entity.requestContext.timeoutHelper.isElapsed()) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } - Single> responsesObs = this.storeReader.readMultipleReplicaAsync( - entity, - /* includePrimary */ true, - /* replicaCountToRead */ 1, - /* requiresValidLSN */ true, - /* useSessionToken */ true, - /* readMode */ readMode, - /* checkMinLsn */ true, - /* forceReadAll */ false); + Mono> responsesObs = this.storeReader.readMultipleReplicaAsync( + entity, + /* includePrimary */ true, + /* replicaCountToRead */ 1, + /* requiresValidLSN */ true, + /* useSessionToken */ true, + /* readMode */ readMode, + /* checkMinLsn */ true, + /* forceReadAll */ false); return responsesObs.flatMap(responses -> { if (responses.size() > 0) { try { - return Single.just(responses.get(0).toResponse(entity.requestContext.requestChargeTracker)); + return Mono.just(responses.get(0).toResponse(entity.requestContext.requestChargeTracker)); } catch (NotFoundException notFoundException) { try { if (entity.requestContext.sessionToken != null - && responses.get(0).sessionToken != null - && !entity.requestContext.sessionToken.isValid(responses.get(0).sessionToken)) { + && responses.get(0).sessionToken != null + && !entity.requestContext.sessionToken.isValid(responses.get(0).sessionToken)) { logger.warn("Convert to session read exception, request {} SESSION Lsn {}, responseLSN {}", entity.getResourceAddress(), entity.requestContext.sessionToken.convertToString(), responses.get(0).lsn); notFoundException.responseHeaders().put(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)); } - return Single.error(notFoundException); + return Mono.error(notFoundException); } catch (CosmosClientException e) { - // TODO: RxJava1 due to design flaw doesn't allow throwing checked exception - // so we have to catch and return - // once we move to RxJava2 we can fix this. - return Single.error(e); + return Mono.error(e); } } catch (CosmosClientException dce) { - // TODO: RxJava1 due to design flaw doesn't allow throwing checked exception - // so we have to catch and return - // once we move to RxJava2 we can fix this. - return Single.error(dce); + return Mono.error(dce); } } @@ -359,7 +345,7 @@ private Single readSessionAsync(RxDocumentServiceRequest entity, responseHeaders.put(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)); ISessionToken requestSessionToken = entity.requestContext.sessionToken; logger.warn("Fail the session read {}, request session token {}", entity.getResourceAddress(), requestSessionToken == null ? "" : requestSessionToken.convertToString()); - return Single.error(new NotFoundException(RMResources.ReadSessionNotAvailable, responseHeaders, null)); + return Mono.error(new NotFoundException(RMResources.ReadSessionNotAvailable, responseHeaders, null)); }); } @@ -419,8 +405,8 @@ StoreReader createStoreReader(TransportClient transportClient, AddressSelector addressSelector, ISessionContainer sessionContainer) { return new StoreReader(transportClient, - addressSelector, - sessionContainer); + addressSelector, + sessionContainer); } QuorumReader createQuorumReader(TransportClient transportClient, @@ -429,10 +415,10 @@ QuorumReader createQuorumReader(TransportClient transportClient, GatewayServiceConfigurationReader serviceConfigurationReader, IAuthorizationTokenProvider authorizationTokenProvider) { return new QuorumReader(transportClient, - addressSelector, - storeReader, - serviceConfigurationReader, - authorizationTokenProvider, - configs); + addressSelector, + storeReader, + serviceConfigurationReader, + authorizationTokenProvider, + configs); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java index b6a8dcc28640c..9dd94774451b8 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java @@ -39,14 +39,15 @@ import org.apache.commons.collections4.ComparatorUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; -import rx.schedulers.Schedulers; +import reactor.core.Exceptions; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import java.net.URI; +import java.time.Duration; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; @@ -88,12 +89,12 @@ public class ConsistencyWriter { private final StoreReader storeReader; public ConsistencyWriter( - AddressSelector addressSelector, - ISessionContainer sessionContainer, - TransportClient transportClient, - IAuthorizationTokenProvider authorizationTokenProvider, - GatewayServiceConfigurationReader serviceConfigReader, - boolean useMultipleWriteLocations) { + AddressSelector addressSelector, + ISessionContainer sessionContainer, + TransportClient transportClient, + IAuthorizationTokenProvider authorizationTokenProvider, + GatewayServiceConfigurationReader serviceConfigReader, + boolean useMultipleWriteLocations) { this.transportClient = transportClient; this.addressSelector = addressSelector; this.sessionContainer = sessionContainer; @@ -103,34 +104,34 @@ public ConsistencyWriter( this.storeReader = new StoreReader(transportClient, addressSelector, null /*we need store reader only for global strong, no session is needed*/); } - public Single writeAsync( - RxDocumentServiceRequest entity, - TimeoutHelper timeout, - boolean forceRefresh) { + public Mono writeAsync( + RxDocumentServiceRequest entity, + TimeoutHelper timeout, + boolean forceRefresh) { if (timeout.isElapsed()) { - return Single.error(new RequestTimeoutException()); + return Mono.error(new RequestTimeoutException()); } String sessionToken = entity.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); return this.writePrivateAsync(entity, timeout, forceRefresh).doOnEach( - arg -> { - try { - SessionTokenHelper.setOriginalSessionToken(entity, sessionToken); - } catch (Throwable throwable) { - logger.error("Unexpected failure in handling orig [{}]: new [{}]", arg, throwable.getMessage(), throwable); - } + arg -> { + try { + SessionTokenHelper.setOriginalSessionToken(entity, sessionToken); + } catch (Throwable throwable) { + logger.error("Unexpected failure in handling orig [{}]: new [{}]", arg, throwable.getMessage(), throwable); } + } ); } - Single writePrivateAsync( - RxDocumentServiceRequest request, - TimeoutHelper timeout, - boolean forceRefresh) { + Mono writePrivateAsync( + RxDocumentServiceRequest request, + TimeoutHelper timeout, + boolean forceRefresh) { if (timeout.isElapsed()) { - return Single.error(new RequestTimeoutException()); + return Mono.error(new RequestTimeoutException()); } request.requestContext.timeoutHelper = timeout; @@ -147,7 +148,7 @@ Single writePrivateAsync( if (request.requestContext.globalStrongWriteResponse == null) { - Single> replicaAddressesObs = this.addressSelector.resolveAddressesAsync(request, forceRefresh); + Mono> replicaAddressesObs = this.addressSelector.resolveAddressesAsync(request, forceRefresh); AtomicReference primaryURI = new AtomicReference<>(); return replicaAddressesObs.flatMap(replicaAddresses -> { @@ -155,16 +156,16 @@ Single writePrivateAsync( List contactedReplicas = new ArrayList<>(); replicaAddresses.forEach(replicaAddress -> contactedReplicas.add(HttpUtils.toURI(replicaAddress.getPhysicalUri()))); request.requestContext.clientSideRequestStatistics.setContactedReplicas(contactedReplicas); - return Single.just(AddressSelector.getPrimaryUri(request, replicaAddresses)); + return Mono.just(AddressSelector.getPrimaryUri(request, replicaAddresses)); } catch (GoneException e) { // RxJava1 doesn't allow throwing checked exception from Observable operators - return Single.error(e); + return Mono.error(e); } }).flatMap(primaryUri -> { try { primaryURI.set(primaryUri); if (this.useMultipleWriteLocations && - RequestHelper.GetConsistencyLevelToUse(this.serviceConfigReader, request) == ConsistencyLevel.SESSION) { + RequestHelper.GetConsistencyLevelToUse(this.serviceConfigReader, request) == ConsistencyLevel.SESSION) { // Set session token to ensure session consistency for write requests // when writes can be issued to multiple locations SessionTokenHelper.setPartitionLocalSessionToken(request, this.sessionContainer); @@ -175,39 +176,38 @@ Single writePrivateAsync( } } catch (Exception e) { - // RxJava1 doesn't allow throwing checked exception from Observable operators - return Single.error(e); + return Mono.error(e); } return this.transportClient.invokeResourceOperationAsync(primaryUri, request) - .doOnError( - t -> { - try { - CosmosClientException ex = Utils.as(t, CosmosClientException.class); - try { - request.requestContext.clientSideRequestStatistics.recordResponse(request, - storeReader.createStoreResult(null, ex, false, false, primaryUri)); - } catch (CosmosClientException e) { - logger.error("Error occurred while recording response", e); - } - String value = ex.responseHeaders().get(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH); - if (!Strings.isNullOrWhiteSpace(value)) { - Integer result = Integers.tryParse(value); - if (result != null && result == 1) { - startBackgroundAddressRefresh(request); - } - } - } catch (Throwable throwable) { - logger.error("Unexpected failure in handling orig [{}]", t.getMessage(), t); - logger.error("Unexpected failure in handling orig [{}] : new [{}]", t.getMessage(), throwable.getMessage(), throwable); - } - } - ); + .doOnError( + t -> { + try { + CosmosClientException ex = Utils.as(t, CosmosClientException.class); + try { + request.requestContext.clientSideRequestStatistics.recordResponse(request, + storeReader.createStoreResult(null, ex, false, false, primaryUri)); + } catch (CosmosClientException e) { + logger.error("Error occurred while recording response", e); + } + String value = ex.responseHeaders().get(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH); + if (!Strings.isNullOrWhiteSpace(value)) { + Integer result = Integers.tryParse(value); + if (result != null && result == 1) { + startBackgroundAddressRefresh(request); + } + } + } catch (Throwable throwable) { + logger.error("Unexpected failure in handling orig [{}]", t.getMessage(), t); + logger.error("Unexpected failure in handling orig [{}] : new [{}]", t.getMessage(), throwable.getMessage(), throwable); + } + } + ); }).flatMap(response -> { try { request.requestContext.clientSideRequestStatistics.recordResponse(request, - storeReader.createStoreResult(response, null, false, false, primaryURI.get())); + storeReader.createStoreResult(response, null, false, false, primaryURI.get())); } catch (CosmosClientException e) { logger.error("Error occurred while recording response", e); } @@ -215,19 +215,17 @@ Single writePrivateAsync( }); } else { - Single barrierRequestObs = BarrierRequestHelper.createAsync(request, this.authorizationTokenProvider, null, request.requestContext.globalCommittedSelectedLSN); - return barrierRequestObs.flatMap(barrierRequest -> { - return waitForWriteBarrierAsync(barrierRequest, request.requestContext.globalCommittedSelectedLSN) - .flatMap(v -> { + Mono barrierRequestObs = BarrierRequestHelper.createAsync(request, this.authorizationTokenProvider, null, request.requestContext.globalCommittedSelectedLSN); + return barrierRequestObs.flatMap(barrierRequest -> waitForWriteBarrierAsync(barrierRequest, request.requestContext.globalCommittedSelectedLSN) + .flatMap(v -> { - if (!v.booleanValue()) { - logger.warn("ConsistencyWriter: Write barrier has not been met for global strong request. SelectedGlobalCommittedLsn: {}", request.requestContext.globalCommittedSelectedLSN); - return Single.error(new GoneException(RMResources.GlobalStrongWriteBarrierNotMet)); - } + if (!v) { + logger.warn("ConsistencyWriter: Write barrier has not been met for global strong request. SelectedGlobalCommittedLsn: {}", request.requestContext.globalCommittedSelectedLSN); + return Mono.error(new GoneException(RMResources.GlobalStrongWriteBarrierNotMet)); + } - return Single.just(request); - }); - }).map(req -> req.requestContext.globalStrongWriteResponse); + return Mono.just(request); + })).map(req -> req.requestContext.globalStrongWriteResponse); } } @@ -247,7 +245,7 @@ boolean isGlobalStrongRequest(RxDocumentServiceRequest request, StoreResponse re return false; } - Single barrierForGlobalStrong(RxDocumentServiceRequest request, StoreResponse response) { + Mono barrierForGlobalStrong(RxDocumentServiceRequest request, StoreResponse response) { try { if (ReplicatedResourceClient.isGlobalStrongEnabled() && this.isGlobalStrongRequest(request, response)) { Utils.ValueHolder lsn = Utils.ValueHolder.initialize(-1l); @@ -256,7 +254,7 @@ Single barrierForGlobalStrong(RxDocumentServiceRequest request, S getLsnAndGlobalCommittedLsn(response, lsn, globalCommittedLsn); if (lsn.v == -1 || globalCommittedLsn.v == -1) { logger.error("ConsistencyWriter: lsn {} or GlobalCommittedLsn {} is not set for global strong request", - lsn, globalCommittedLsn); + lsn, globalCommittedLsn); throw new GoneException(RMResources.Gone); } @@ -270,107 +268,106 @@ Single barrierForGlobalStrong(RxDocumentServiceRequest request, S //barrier only if necessary, i.e. when write region completes write, but read regions have not. if (globalCommittedLsn.v < lsn.v) { - Single barrierRequestObs = BarrierRequestHelper.createAsync(request, - this.authorizationTokenProvider, - null, - request.requestContext.globalCommittedSelectedLSN); + Mono barrierRequestObs = BarrierRequestHelper.createAsync(request, + this.authorizationTokenProvider, + null, + request.requestContext.globalCommittedSelectedLSN); return barrierRequestObs.flatMap(barrierRequest -> { - Single barrierWait = this.waitForWriteBarrierAsync(barrierRequest, request.requestContext.globalCommittedSelectedLSN); + Mono barrierWait = this.waitForWriteBarrierAsync(barrierRequest, request.requestContext.globalCommittedSelectedLSN); return barrierWait.flatMap(res -> { if (!res) { logger.error("ConsistencyWriter: Write barrier has not been met for global strong request. SelectedGlobalCommittedLsn: {}", - request.requestContext.globalCommittedSelectedLSN); + request.requestContext.globalCommittedSelectedLSN); // RxJava1 doesn't allow throwing checked exception - return Single.error(new GoneException(RMResources.GlobalStrongWriteBarrierNotMet)); + return Mono.error(new GoneException(RMResources.GlobalStrongWriteBarrierNotMet)); } - return Single.just(request.requestContext.globalStrongWriteResponse); + return Mono.just(request.requestContext.globalStrongWriteResponse); }); }); } else { - return Single.just(request.requestContext.globalStrongWriteResponse); + return Mono.just(request.requestContext.globalStrongWriteResponse); } } else { - return Single.just(response); + return Mono.just(response); } } catch (CosmosClientException e) { // RxJava1 doesn't allow throwing checked exception from Observable operators - return Single.error(e); + return Mono.error(e); } } - private Single waitForWriteBarrierAsync(RxDocumentServiceRequest barrierRequest, long selectedGlobalCommittedLsn) { + private Mono waitForWriteBarrierAsync(RxDocumentServiceRequest barrierRequest, long selectedGlobalCommittedLsn) { AtomicInteger writeBarrierRetryCount = new AtomicInteger(ConsistencyWriter.MAX_NUMBER_OF_WRITE_BARRIER_READ_RETRIES); AtomicLong maxGlobalCommittedLsnReceived = new AtomicLong(0); - return Observable.defer(() -> { + return Flux.defer(() -> { if (barrierRequest.requestContext.timeoutHelper.isElapsed()) { - return Observable.error(new RequestTimeoutException()); + return Flux.error(new RequestTimeoutException()); } - Single> storeResultListObs = this.storeReader.readMultipleReplicaAsync( - barrierRequest, - true /*allowPrimary*/, - 1 /*any replica with correct globalCommittedLsn is good enough*/, - false /*requiresValidLsn*/, - false /*useSessionToken*/, - ReadMode.Strong, - false /*checkMinLsn*/, - false /*forceReadAll*/); + Mono> storeResultListObs = this.storeReader.readMultipleReplicaAsync( + barrierRequest, + true /*allowPrimary*/, + 1 /*any replica with correct globalCommittedLsn is good enough*/, + false /*requiresValidLsn*/, + false /*useSessionToken*/, + ReadMode.Strong, + false /*checkMinLsn*/, + false /*forceReadAll*/); return storeResultListObs.flatMap( - responses -> { - if (responses != null && responses.stream().anyMatch(response -> response.globalCommittedLSN >= selectedGlobalCommittedLsn)) { - return Single.just(Boolean.TRUE); - } - - //get max global committed lsn from current batch of responses, then update if greater than max of all batches. - long maxGlobalCommittedLsn = (responses != null || !responses.isEmpty()) ? - (Long) responses.stream().map(s -> s.globalCommittedLSN).max(ComparatorUtils.NATURAL_COMPARATOR).get() : - 0l; - maxGlobalCommittedLsnReceived.set(maxGlobalCommittedLsnReceived.get() > maxGlobalCommittedLsn ? - maxGlobalCommittedLsnReceived.get() : maxGlobalCommittedLsn); - - //only refresh on first barrier call, set to false for subsequent attempts. - barrierRequest.requestContext.forceRefreshAddressCache = false; - - //trace on last retry. - if (writeBarrierRetryCount.getAndDecrement() == 0) { - logger.debug("ConsistencyWriter: WaitForWriteBarrierAsync - Last barrier multi-region strong. Responses: {}", - String.join("; ", responses.stream().map(r -> r.toString()).collect(Collectors.toList()))); - } - - return Single.just(null); - }).toObservable(); + responses -> { + if (responses != null && responses.stream().anyMatch(response -> response.globalCommittedLSN >= selectedGlobalCommittedLsn)) { + return Mono.just(Boolean.TRUE); + } + + //get max global committed lsn from current batch of responses, then update if greater than max of all batches. + long maxGlobalCommittedLsn = (responses != null || !responses.isEmpty()) ? + (Long) responses.stream().map(s -> s.globalCommittedLSN).max(ComparatorUtils.NATURAL_COMPARATOR).get() : + 0L; + maxGlobalCommittedLsnReceived.set(maxGlobalCommittedLsnReceived.get() > maxGlobalCommittedLsn ? + maxGlobalCommittedLsnReceived.get() : maxGlobalCommittedLsn); + + //only refresh on first barrier call, set to false for subsequent attempts. + barrierRequest.requestContext.forceRefreshAddressCache = false; + + //trace on last retry. + if (writeBarrierRetryCount.getAndDecrement() == 0) { + logger.debug("ConsistencyWriter: WaitForWriteBarrierAsync - Last barrier multi-region strong. Responses: {}", + responses.stream().map(StoreResult::toString).collect(Collectors.joining("; "))); + } + + return Mono.empty(); + }).flux(); }).repeatWhen(s -> { if (writeBarrierRetryCount.get() == 0) { - return Observable.empty(); + return Flux.empty(); } else { if ((ConsistencyWriter.MAX_NUMBER_OF_WRITE_BARRIER_READ_RETRIES - writeBarrierRetryCount.get()) > ConsistencyWriter.MAX_SHORT_BARRIER_RETRIES_FOR_MULTI_REGION) { - return Observable.timer(ConsistencyWriter.DELAY_BETWEEN_WRITE_BARRIER_CALLS_IN_MS, TimeUnit.MILLISECONDS); + return Flux.just(0L).delayElements(Duration.ofMillis(ConsistencyWriter.DELAY_BETWEEN_WRITE_BARRIER_CALLS_IN_MS)); } else { - return Observable.timer(ConsistencyWriter.SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION, TimeUnit.MILLISECONDS); + return Flux.just(0L).delayElements(Duration.ofMillis(ConsistencyWriter.SHORT_BARRIER_RETRY_INTERVAL_IN_MS_FOR_MULTI_REGION)); } } }).take(1) - .map(r -> { - if (r == null) { - // after retries exhausted print this log and return false - logger.debug("ConsistencyWriter: Highest global committed lsn received for write barrier call is {}", maxGlobalCommittedLsnReceived); - - return false; - } - return r; - }).toSingle(); + .switchIfEmpty(Mono.defer(() -> { + // after retries exhausted print this log and return false + logger.debug("ConsistencyWriter: Highest global committed lsn received for write barrier call is {}", maxGlobalCommittedLsnReceived); + + return Mono.just(false); + })) + .map(r -> r) + .single(); } static void getLsnAndGlobalCommittedLsn(StoreResponse response, Utils.ValueHolder lsn, Utils.ValueHolder globalCommittedLsn) { - lsn.v = -1l; - globalCommittedLsn.v = -1l; + lsn.v = -1L; + globalCommittedLsn.v = -1L; String headerValue; @@ -385,12 +382,12 @@ static void getLsnAndGlobalCommittedLsn(StoreResponse response, Utils.ValueHolde void startBackgroundAddressRefresh(RxDocumentServiceRequest request) { this.addressSelector.resolvePrimaryUriAsync(request, true) - .observeOn(Schedulers.io()) - .subscribe( - r -> { - }, - e -> logger.warn( - "Background refresh of the primary address failed with {}", e.getMessage(), e) - ); + .publishOn(Schedulers.elastic()) + .subscribe( + r -> { + }, + e -> logger.warn( + "Background refresh of the primary address failed with {}", e.getMessage(), e) + ); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ErrorUtils.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ErrorUtils.java index 0d1abc33dc076..ccb40aa15f6dc 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ErrorUtils.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ErrorUtils.java @@ -23,33 +23,29 @@ package com.azure.data.cosmos.directconnectivity; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; +import io.netty.handler.codec.http.HttpMethod; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; +import reactor.core.publisher.Mono; import java.net.URI; +import java.nio.charset.StandardCharsets; public class ErrorUtils { - private static final Logger logger = LoggerFactory.getLogger(TransportClient.class); + private static final Logger logger = LoggerFactory.getLogger(ErrorUtils.class); - protected static Single getErrorResponseAsync(HttpClientResponse responseMessage) { - - if (responseMessage.getContent() == null) { - return Single.just(StringUtils.EMPTY); + static Mono getErrorResponseAsync(HttpResponse responseMessage, HttpRequest request) { + Mono responseAsString = ResponseUtils.toString(responseMessage.body()); + if (request.httpMethod() == HttpMethod.DELETE) { + return Mono.just(StringUtils.EMPTY); } - - return getErrorFromStream(responseMessage.getContent()); - } - - protected static Single getErrorFromStream(Observable stream) { - return ResponseUtils.toString(stream).toSingle(); + return responseAsString; } - protected static void logGoneException(URI physicalAddress, String activityId) { + static void logGoneException(URI physicalAddress, String activityId) { logger.trace("Listener not found. Store Physical Address {} ActivityId {}", physicalAddress, activityId); } @@ -59,7 +55,7 @@ protected static void logGoneException(String physicalAddress, String activityId physicalAddress, activityId); } - protected static void logException(URI physicalAddress, String activityId) { + static void logException(URI physicalAddress, String activityId) { logger.trace("Store Request Failed. Store Physical Address {} ActivityId {}", physicalAddress, activityId); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java index 413e54f96b973..5e36b3e56f5c0 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java @@ -11,7 +11,7 @@ * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -28,7 +28,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.util.Map; @@ -45,14 +45,14 @@ public ForbiddenException(Error error, long lsn, String partitionKeyRangeId, Map } public ForbiddenException(String message) { - this(message, (Exception) null, (HttpResponseHeaders) null, null); + this(message, null, null, null); } - public ForbiddenException(String message, HttpResponseHeaders headers, String requestUri) { - this(message, null, headers, requestUri); + public ForbiddenException(String message, HttpHeaders headers, String requestUrlString) { + this(message, null, headers, requestUrlString); } - public ForbiddenException(String message, HttpResponseHeaders headers, URI requestUri) { + public ForbiddenException(String message, HttpHeaders headers, URI requestUri) { this(message, headers, requestUri != null ? requestUri.toString() : null); } @@ -61,13 +61,13 @@ public ForbiddenException(Exception innerException) { } public ForbiddenException(String message, - Exception innerException, - HttpResponseHeaders headers, - String requestUri) { + Exception innerException, + HttpHeaders headers, + String requestUrlString) { super(String.format("%s: %s", RMResources.Forbidden, message), innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.FORBIDDEN, - requestUri != null ? requestUri.toString() : null); + requestUrlString); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java index 3adaa06d98cc7..830694a288d96 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java @@ -42,19 +42,18 @@ import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.caches.AsyncCache; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; +import io.netty.handler.codec.http.HttpMethod; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Completable; -import rx.Observable; -import rx.Single; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.net.MalformedURLException; import java.net.URISyntaxException; @@ -89,7 +88,7 @@ public class GatewayAddressCache implements IAddressCache { private final String protocolFilter; private final IAuthorizationTokenProvider tokenProvider; private final HashMap defaultRequestHeaders; - private final CompositeHttpClient httpClient; + private final HttpClient httpClient; private volatile Pair masterPartitionAddressCache; private volatile Instant suboptimalMasterPartitionTimestamp; @@ -99,7 +98,7 @@ public GatewayAddressCache( Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, - CompositeHttpClient httpClient, + HttpClient httpClient, long suboptimalPartitionForceRefreshIntervalInSeconds) { try { this.addressEndpoint = new URL(serviceEndpoint, Paths.ADDRESS_PATH_SEGMENT); @@ -139,7 +138,7 @@ public GatewayAddressCache( Protocol protocol, IAuthorizationTokenProvider tokenProvider, UserAgentContainer userAgent, - CompositeHttpClient httpClient) { + HttpClient httpClient) { this(serviceEndpoint, protocol, tokenProvider, @@ -153,7 +152,7 @@ private URL getServiceEndpoint() { } @Override - public Single tryGetAddresses(RxDocumentServiceRequest request, + public Mono tryGetAddresses(RxDocumentServiceRequest request, PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses) { @@ -164,7 +163,7 @@ public Single tryGetAddresses(RxDocumentServiceRequest req PartitionKeyRange.MASTER_PARTITION_KEY_RANGE_ID)) { // if that's master partition return master partition address! - return this.resolveMasterAsync(request, forceRefreshPartitionAddresses, request.properties).map(r -> r.getRight()); + return this.resolveMasterAsync(request, forceRefreshPartitionAddresses, request.properties).map(Pair::getRight); } Instant suboptimalServerPartitionTimestamp = this.suboptimalServerPartitionTimestamps.get(partitionKeyRangeIdentity); @@ -206,7 +205,7 @@ public Single tryGetAddresses(RxDocumentServiceRequest req this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } - Single addressesObs = this.serverPartitionAddressCache.getAsync( + Mono addressesObs = this.serverPartitionAddressCache.getAsync( partitionKeyRangeIdentity, null, () -> this.getAddressesForRangeId( @@ -222,15 +221,14 @@ public Single tryGetAddresses(RxDocumentServiceRequest req } return addresses; - }).onErrorResumeNext(ex -> { + }).onErrorResume(ex -> { CosmosClientException dce = com.azure.data.cosmos.internal.Utils.as(ex, CosmosClientException.class); if (dce == null) { if (forceRefreshPartitionAddressesModified) { this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); } - return Single.error(ex); + return Mono.error(ex); } else { - assert dce != null; if (Exceptions.isStatusCode(dce, HttpConstants.StatusCodes.NOTFOUND) || Exceptions.isStatusCode(dce, HttpConstants.StatusCodes.GONE) || Exceptions.isSubStatusCode(dce, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { @@ -238,13 +236,13 @@ public Single tryGetAddresses(RxDocumentServiceRequest req this.suboptimalServerPartitionTimestamps.remove(partitionKeyRangeIdentity); return null; } - return Single.error(ex); + return Mono.error(ex); } }); } - Single> getServerAddressesViaGatewayAsync( + Mono> getServerAddressesViaGatewayAsync( RxDocumentServiceRequest request, String collectionRid, List partitionKeyRangeIds, @@ -263,7 +261,7 @@ Single> getServerAddressesViaGatewayAsync( addressQuery.put(HttpConstants.QueryStrings.PARTITION_KEY_RANGE_IDS, String.join(",", partitionKeyRangeIds)); headers.put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); - String token = null; + String token; token = this.tokenProvider.getUserAuthorizationToken( collectionRid, @@ -289,22 +287,25 @@ Single> getServerAddressesViaGatewayAsync( headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, token); URL targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(addressQuery)); String identifier = logAddressResolutionStart(request, targetEndpoint); - HttpClientRequest httpGet = HttpClientRequest.createGet(targetEndpoint.toString()); + HttpHeaders httpHeaders = new HttpHeaders(headers.size()); for (Map.Entry entry : headers.entrySet()) { - httpGet.withHeader(entry.getKey(), entry.getValue()); + httpHeaders.set(entry.getKey(), entry.getValue()); } - RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(targetEndpoint.getHost(), targetEndpoint.getPort()); - Observable> responseObs = this.httpClient.submit(serverInfo, httpGet); + HttpRequest httpRequest; + try { + httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint.toURI(), targetEndpoint.getPort(), httpHeaders); + } catch (URISyntaxException e) { + throw new IllegalArgumentException(targetEndpoint.toString(), e); + } + Mono httpResponseMono = this.httpClient.send(httpRequest); - Single dsrObs = responseObs.toSingle().flatMap(rsp -> - HttpClientUtils.parseResponseAsync(rsp)); + Mono dsrObs = HttpClientUtils.parseResponseAsync(httpResponseMono, httpRequest); return dsrObs.map( dsr -> { logAddressResolutionEnd(request, identifier); - List

addresses = dsr.getQueryResponse(Address.class); - return addresses; + return dsr.getQueryResponse(Address.class); }); } @@ -313,7 +314,7 @@ public void dispose() { //https://msdata.visualstudio.com/CosmosDB/_workitems/edit/340842 } - private Single> resolveMasterAsync(RxDocumentServiceRequest request, boolean forceRefresh, Map properties) { + private Mono> resolveMasterAsync(RxDocumentServiceRequest request, boolean forceRefresh, Map properties) { Pair masterAddressAndRangeInitial = this.masterPartitionAddressCache; forceRefresh = forceRefresh || @@ -322,7 +323,7 @@ private Single> resolveMas Duration.between(this.suboptimalMasterPartitionTimestamp, Instant.now()).getSeconds() > this.suboptimalPartitionForceRefreshIntervalInSeconds); if (forceRefresh || this.masterPartitionAddressCache == null) { - Single> masterReplicaAddressesObs = this.getMasterAddressesViaGatewayAsync( + Mono> masterReplicaAddressesObs = this.getMasterAddressesViaGatewayAsync( request, ResourceType.Database, null, @@ -356,29 +357,29 @@ private Single> resolveMas this.suboptimalMasterPartitionTimestamp = Instant.now(); } - return Single.just(masterAddressAndRangeInitial); + return Mono.just(masterAddressAndRangeInitial); } } - private Single getAddressesForRangeId( + private Mono getAddressesForRangeId( RxDocumentServiceRequest request, String collectionRid, String partitionKeyRangeId, boolean forceRefresh) { - Single> addressResponse = this.getServerAddressesViaGatewayAsync(request, collectionRid, Collections.singletonList(partitionKeyRangeId), forceRefresh); + Mono> addressResponse = this.getServerAddressesViaGatewayAsync(request, collectionRid, Collections.singletonList(partitionKeyRangeId), forceRefresh); - Single>> addressInfos = + Mono>> addressInfos = addressResponse.map( addresses -> addresses.stream().filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) .collect(Collectors.groupingBy( - address -> address.getParitionKeyRangeId())) + Address::getParitionKeyRangeId)) .values().stream() .map(groupedAddresses -> toPartitionAddressAndRange(collectionRid, addresses)) .collect(Collectors.toList())); - Single>> result = addressInfos.map(addressInfo -> addressInfo.stream() + Mono>> result = addressInfos.map(addressInfo -> addressInfo.stream() .filter(a -> StringUtils.equals(a.getLeft().getPartitionKeyRangeId(), partitionKeyRangeId)) .collect(Collectors.toList())); @@ -395,14 +396,14 @@ private Single getAddressesForRangeId( PartitionKeyRangeGoneException e = new PartitionKeyRangeGoneException(errorMessage); BridgeInternal.setResourceAddress(e, collectionRid); - return Single.error(e); + return Mono.error(e); } else { - return Single.just(list.get(0).getRight()); + return Mono.just(list.get(0).getRight()); } }); } - Single> getMasterAddressesViaGatewayAsync( + Mono> getMasterAddressesViaGatewayAsync( RxDocumentServiceRequest request, ResourceType resourceType, String resourceAddress, @@ -435,22 +436,26 @@ Single> getMasterAddressesViaGatewayAsync( headers.put(HttpConstants.HttpHeaders.AUTHORIZATION, HttpUtils.urlEncode(token)); URL targetEndpoint = Utils.setQuery(this.addressEndpoint.toString(), Utils.createQuery(queryParameters)); String identifier = logAddressResolutionStart(request, targetEndpoint); - HttpClientRequest httpGet = HttpClientRequest.createGet(targetEndpoint.toString()); + HttpHeaders defaultHttpHeaders = new HttpHeaders(headers.size()); for (Map.Entry entry : headers.entrySet()) { - httpGet.withHeader(entry.getKey(), entry.getValue()); + defaultHttpHeaders.set(entry.getKey(), entry.getValue()); } - RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(targetEndpoint.getHost(), targetEndpoint.getPort()); - Observable> responseObs = this.httpClient.submit(serverInfo, httpGet); + HttpRequest httpRequest; + try { + httpRequest = new HttpRequest(HttpMethod.GET, targetEndpoint.toURI(), targetEndpoint.getPort(), defaultHttpHeaders); + } catch (URISyntaxException e) { + throw new IllegalArgumentException(targetEndpoint.toString(), e); + } + + Mono httpResponseMono = this.httpClient.send(httpRequest); + Mono dsrObs = HttpClientUtils.parseResponseAsync(httpResponseMono, httpRequest); - Single dsrObs = responseObs.toSingle().flatMap(rsp -> - HttpClientUtils.parseResponseAsync(rsp)); return dsrObs.map( dsr -> { logAddressResolutionEnd(request, identifier); - List
addresses = dsr.getQueryResponse(Address.class); - return addresses; + return dsr.getQueryResponse(Address.class); }); } @@ -468,10 +473,10 @@ private static AddressInformation toAddressInformation(Address address) { return new AddressInformation(true, address.IsPrimary(), address.getPhyicalUri(), address.getProtocolScheme()); } - public Completable openAsync( + public Mono openAsync( DocumentCollection collection, List partitionKeyRangeIdentities) { - List>> tasks = new ArrayList<>(); + List>> tasks = new ArrayList<>(); int batchSize = GatewayAddressCache.DefaultBatchSize; RxDocumentServiceRequest request = RxDocumentServiceRequest.create( @@ -480,7 +485,7 @@ public Completable openAsync( collection.resourceId(), ResourceType.DocumentCollection, // AuthorizationTokenType.PrimaryMasterKey - Collections.EMPTY_MAP); + Collections.emptyMap()); for (int i = 0; i < partitionKeyRangeIdentities.size(); i += batchSize) { int endIndex = i + batchSize; @@ -492,16 +497,16 @@ public Completable openAsync( collection.resourceId(), partitionKeyRangeIdentities.subList(i, endIndex). - stream().map(range -> range.getPartitionKeyRangeId()).collect(Collectors.toList()), - false).toObservable()); + stream().map(PartitionKeyRangeIdentity::getPartitionKeyRangeId).collect(Collectors.toList()), + false).flux()); } - return Observable.concat(tasks) + return Flux.concat(tasks) .doOnNext(list -> { List> addressInfos = list.stream() .filter(addressInfo -> this.protocolScheme.equals(addressInfo.getProtocolScheme())) - .collect(Collectors.groupingBy(address -> address.getParitionKeyRangeId())) - .entrySet().stream().map(group -> toPartitionAddressAndRange(collection.resourceId(), group.getValue())) + .collect(Collectors.groupingBy(Address::getParitionKeyRangeId)) + .values().stream().map(addresses -> toPartitionAddressAndRange(collection.resourceId(), addresses)) .collect(Collectors.toList()); for (Pair addressInfo : addressInfos) { @@ -509,11 +514,11 @@ public Completable openAsync( new PartitionKeyRangeIdentity(collection.resourceId(), addressInfo.getLeft().getPartitionKeyRangeId()), addressInfo.getRight()); } - }).toCompletable(); + }).then(); } private boolean notAllReplicasAvailable(AddressInformation[] addressInformations) { - return addressInformations.length < this.serviceConfig.userReplicationPolicy.MaxReplicaSetSize; + return addressInformations.length < ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize; } private static String logAddressResolutionStart(RxDocumentServiceRequest request, URL targetEndpointUrl) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java index 5feac5c55db40..684361de5839e 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java @@ -34,16 +34,12 @@ import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.Utils; -import io.netty.buffer.ByteBuf; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; import io.netty.handler.codec.http.HttpMethod; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; -import org.apache.commons.lang3.StringUtils; -import rx.Observable; -import rx.Single; -import rx.functions.Action1; +import reactor.core.publisher.Mono; import java.net.MalformedURLException; import java.net.URI; @@ -77,11 +73,11 @@ public class GatewayServiceConfigurationReader { private final BaseAuthorizationTokenProvider baseAuthorizationTokenProvider; private final boolean hasAuthKeyResourceToken; private final String authKeyResourceToken; - private CompositeHttpClient httpClient; + private HttpClient httpClient; public GatewayServiceConfigurationReader(URI serviceEndpoint, boolean hasResourceToken, String resourceToken, ConnectionPolicy connectionPolicy, BaseAuthorizationTokenProvider baseAuthorizationTokenProvider, - CompositeHttpClient httpClient) { + HttpClient httpClient) { this.serviceEndpoint = serviceEndpoint; this.baseAuthorizationTokenProvider = baseAuthorizationTokenProvider; this.hasAuthKeyResourceToken = hasResourceToken; @@ -119,11 +115,10 @@ public Map getQueryEngineConfiguration() { return this.queryEngineConfiguration; } - private Single getDatabaseAccountAsync(URI serviceEndpoint) { - HttpClientRequest httpRequest = HttpClientRequest.create(HttpMethod.GET, - this.serviceEndpoint.toString()); + private Mono getDatabaseAccountAsync(URI serviceEndpoint) { - httpRequest.withHeader(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.set(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); UserAgentContainer userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.userAgentSuffix(); @@ -131,30 +126,28 @@ private Single getDatabaseAccountAsync(URI serviceEndpoint) { userAgentContainer.setSuffix(userAgentSuffix); } - httpRequest.withHeader(HttpConstants.HttpHeaders.USER_AGENT, userAgentContainer.getUserAgent()); - httpRequest.withHeader(HttpConstants.HttpHeaders.API_TYPE, Constants.Properties.SQL_API_TYPE); - String authorizationToken = StringUtils.EMPTY; + httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, userAgentContainer.getUserAgent()); + httpHeaders.set(HttpConstants.HttpHeaders.API_TYPE, Constants.Properties.SQL_API_TYPE); + String authorizationToken; if (this.hasAuthKeyResourceToken || baseAuthorizationTokenProvider == null) { authorizationToken = HttpUtils.urlEncode(this.authKeyResourceToken); } else { // Retrieve the document service properties. String xDate = Utils.nowAsRFC1123(); - httpRequest.withHeader(HttpConstants.HttpHeaders.X_DATE, xDate); + httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, xDate); Map header = new HashMap<>(); header.put(HttpConstants.HttpHeaders.X_DATE, xDate); authorizationToken = baseAuthorizationTokenProvider .generateKeyAuthorizationSignature(HttpConstants.HttpMethods.GET, serviceEndpoint, header); } + httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorizationToken); - httpRequest.withHeader(HttpConstants.HttpHeaders.AUTHORIZATION, authorizationToken); - RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(serviceEndpoint.getHost(), serviceEndpoint.getPort()); - - Observable> clientResponseObservable = this.httpClient.submit(serverInfo, - httpRequest); - return toDatabaseAccountObservable(clientResponseObservable.toSingle()); + HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, serviceEndpoint, serviceEndpoint.getPort(), httpHeaders); + Mono httpResponse = httpClient.send(httpRequest); + return toDatabaseAccountObservable(httpResponse, httpRequest); } - public Single initializeReaderAsync() { + public Mono initializeReaderAsync() { try { return GlobalEndpointManager.getDatabaseAccountFromAnyLocationsAsync(this.serviceEndpoint.toURL(), @@ -164,28 +157,22 @@ public Single initializeReaderAsync() { } catch (URISyntaxException e) { throw new IllegalArgumentException("URI " + url); } - }).doOnSuccess(new Action1() { - - @Override - public void call(DatabaseAccount databaseAccount) { - userReplicationPolicy = BridgeInternal.getReplicationPolicy(databaseAccount); - systemReplicationPolicy = BridgeInternal.getSystemReplicationPolicy(databaseAccount); - queryEngineConfiguration = BridgeInternal.getQueryEngineConfiuration(databaseAccount); - consistencyLevel = BridgeInternal.getConsistencyPolicy(databaseAccount).getDefaultConsistencyLevel(); - initialized = true; - } + }).doOnSuccess(databaseAccount -> { + userReplicationPolicy = BridgeInternal.getReplicationPolicy(databaseAccount); + systemReplicationPolicy = BridgeInternal.getSystemReplicationPolicy(databaseAccount); + queryEngineConfiguration = BridgeInternal.getQueryEngineConfiuration(databaseAccount); + consistencyLevel = BridgeInternal.getConsistencyPolicy(databaseAccount).getDefaultConsistencyLevel(); + initialized = true; }); } catch (MalformedURLException e) { throw new IllegalArgumentException(this.serviceEndpoint.toString(), e); } } - private Single toDatabaseAccountObservable( - Single> clientResponseObservable) { - return clientResponseObservable.flatMap(clientResponse -> { - return HttpClientUtils.parseResponseAsync(clientResponse) - .map(rxDocumentServiceResponse -> rxDocumentServiceResponse.getResource(DatabaseAccount.class)); - }); + private Mono toDatabaseAccountObservable(Mono httpResponse, HttpRequest httpRequest) { + + return HttpClientUtils.parseResponseAsync(httpResponse, httpRequest) + .map(rxDocumentServiceResponse -> rxDocumentServiceResponse.getResource(DatabaseAccount.class)); } private void throwIfNotInitialized() { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java index 3a5f71c480067..779d125cafaca 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java @@ -34,7 +34,7 @@ import org.apache.commons.lang3.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; +import reactor.core.publisher.Mono; import java.time.Duration; @@ -68,7 +68,7 @@ public GoneAndRetryWithRetryPolicy(RxDocumentServiceRequest request, Integer wai } @Override - public Single shouldRetry(Exception exception) { + public Mono shouldRetry(Exception exception) { CosmosClientException exceptionToThrow = null; Duration backoffTime = Duration.ofSeconds(0); Duration timeout = Duration.ofSeconds(0); @@ -83,7 +83,7 @@ public Single shouldRetry(Exception exception) { logger.debug("Operation will NOT be retried. Current attempt {}, Exception: {} ", this.attemptCount, exception); stopStopWatch(this.durationTimer); - return Single.just(ShouldRetryResult.noRetry()); + return Mono.just(ShouldRetryResult.noRetry()); } else if (exception instanceof RetryWithException) { this.lastRetryWithException = (RetryWithException) exception; } @@ -137,7 +137,7 @@ public Single shouldRetry(Exception exception) { exception.toString()); } stopStopWatch(this.durationTimer); - return Single.just(ShouldRetryResult.error(exceptionToThrow)); + return Mono.just(ShouldRetryResult.error(exceptionToThrow)); } backoffTime = Duration.ofSeconds(Math.min(Math.min(this.currentBackoffSeconds, remainingSeconds), GoneAndRetryWithRetryPolicy.MAXIMUM_BACKOFF_TIME_IN_SECONDS)); @@ -166,7 +166,7 @@ public Single shouldRetry(Exception exception) { // for second InvalidPartitionException, stop retrying. logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); - return Single.just(ShouldRetryResult + return Mono.just(ShouldRetryResult .error(new CosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception))); } @@ -176,7 +176,7 @@ public Single shouldRetry(Exception exception) { } else { logger.error("Received unexpected invalid collection exception, request should be non-null.", exception); - return Single.just(ShouldRetryResult + return Mono.just(ShouldRetryResult .error(new CosmosClientException(HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, exception))); } forceRefreshAddressCache = false; @@ -193,7 +193,7 @@ public Single shouldRetry(Exception exception) { // from refreshing any caches. forceRefreshAddressCache = false; } - return Single.just(ShouldRetryResult.retryAfter(backoffTime, + return Mono.just(ShouldRetryResult.retryAfter(backoffTime, Quadruple.with(forceRefreshAddressCache, true, timeout, currentRetryAttemptCount))); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java index b638839cb797e..4222179dec2b2 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java @@ -27,37 +27,37 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; -import rx.Single; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; +import reactor.core.publisher.Mono; public class HttpClientUtils { - public static Single parseResponseAsync(HttpClientResponse responseMessage) { + static Mono parseResponseAsync(Mono httpResponse, HttpRequest httpRequest) { + return httpResponse.flatMap(response -> { + if (response.statusCode() < HttpConstants.StatusCodes.MINIMUM_STATUSCODE_AS_ERROR_GATEWAY) { - if (responseMessage.getStatus().code() < HttpConstants.StatusCodes.MINIMUM_STATUSCODE_AS_ERROR_GATEWAY) { + return ResponseUtils.toStoreResponse(response, httpRequest).map(RxDocumentServiceResponse::new); - Single storeResponse = ResponseUtils.toStoreResponse(responseMessage); - return storeResponse.map(sr -> new RxDocumentServiceResponse(sr)); + // TODO: to break the dependency between RxDocumentServiceResponse and StoreResponse + // we should factor out the RxDocumentServiceResponse(StoreResponse) constructor to a helper class - // TODO: to break the dependency between RxDocumentServiceResponse and StoreResponse - // we should factor out the RxDocumentServiceResponse(StoreResponse) constructor to a helper class - - } else { - return HttpClientUtils.createDocumentClientException(responseMessage).flatMap(e -> Single.error(e)); - } + } else { + return HttpClientUtils + .createDocumentClientException(response).flatMap(Mono::error); + } + }); } - private static Single createDocumentClientException(HttpClientResponse responseMessage) { - Single readStream = ResponseUtils.toString(responseMessage.getContent()).toSingle(); + private static Mono createDocumentClientException(HttpResponse httpResponse) { + Mono readStream = ResponseUtils.toString(httpResponse.body()); return readStream.map(body -> { Error error = new Error(body); // TODO: we should set resource address in the Document Client Exception - - return new CosmosClientException(responseMessage.getStatus().code(), error, - HttpUtils.asMap(responseMessage.getHeaders())); + return new CosmosClientException(httpResponse.statusCode(), error, + httpResponse.headers().toMap()); }); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java index b39a1cc753b77..1ddf45e6f89a4 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java @@ -27,7 +27,6 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.internal.BadRequestException; import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.HttpClientFactory; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Integers; import com.azure.data.cosmos.internal.InternalServerErrorException; @@ -47,19 +46,16 @@ import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.Utils; -import io.netty.buffer.ByteBuf; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpClientConfig; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; import io.netty.handler.codec.http.HttpMethod; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; -import io.reactivex.netty.protocol.http.client.HttpRequestHeaders; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; +import reactor.core.publisher.Mono; import java.net.URI; import java.time.Instant; @@ -74,17 +70,17 @@ */ public class HttpTransportClient extends TransportClient { private final Logger logger = LoggerFactory.getLogger(HttpTransportClient.class); - private final CompositeHttpClient httpClient; + private final HttpClient httpClient; private final Map defaultHeaders; private final Configs configs; - CompositeHttpClient createHttpClient(int requestTimeout) { + HttpClient createHttpClient(int requestTimeout) { // TODO: use one instance of SSL context everywhere - HttpClientFactory httpClientFactory = new HttpClientFactory(this.configs); - httpClientFactory.withRequestTimeoutInMillis(requestTimeout * 1000); - httpClientFactory.withPoolSize(configs.getDirectHttpsMaxConnectionLimit()); + HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs); + httpClientConfig.withRequestTimeoutInMillis(requestTimeout * 1000); + httpClientConfig.withPoolSize(configs.getDirectHttpsMaxConnectionLimit()); - return httpClientFactory.toHttpClientBuilder().build(); + return HttpClient.createFixed(httpClientConfig); } public HttpTransportClient(Configs configs, int requestTimeout, UserAgentContainer userAgent) { @@ -110,13 +106,12 @@ public void close() { httpClient.shutdown(); } - public Single invokeStoreAsync( + public Mono invokeStoreAsync( URI physicalAddress, - ResourceOperation resourceOperation, RxDocumentServiceRequest request) { try { - + ResourceOperation resourceOperation = new ResourceOperation(request.getOperationType(), request.getResourceType()); // uuid correlation manager UUID activityId = UUID.fromString(request.getActivityId()); @@ -128,110 +123,109 @@ public Single invokeStoreAsync( throw new InternalServerErrorException(RMResources.InternalServerError, null, errorResponseHeaders, null); } - HttpClientRequest httpRequest = prepareHttpMessage(activityId, physicalAddress, resourceOperation, request); - RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(physicalAddress.getHost(), physicalAddress.getPort()); + HttpRequest httpRequest = prepareHttpMessage(activityId, physicalAddress, resourceOperation, request); MutableVolatile sendTimeUtc = new MutableVolatile<>(); - Single> responseMessage = this.httpClient.submit(serverInfo, httpRequest).toSingle(); - responseMessage = responseMessage.doOnSubscribe(() -> { - sendTimeUtc.v = Instant.now(); - this.beforeRequest( - activityId, - httpRequest.getUri(), - request.getResourceType(), - httpRequest.getHeaders()); - }); - - responseMessage = responseMessage.onErrorResumeNext(t -> { - - Exception exception = Utils.as(t, Exception.class); - if (exception == null) { - logger.error("critical failure", t); - t.printStackTrace(); - assert false : "critical failure"; - return Single.error(t); - } - - //Trace.CorrelationManager.ActivityId = activityId; - if (WebExceptionUtility.isWebExceptionRetriable(exception)) { - logger.debug("Received retriable exception {} " + - "sending the request to {}, will re-resolve the address " + - "send time UTC: {}", - exception, - physicalAddress, - sendTimeUtc); - - GoneException goneException = new GoneException( - String.format( - RMResources.ExceptionMessage, - RMResources.Gone), - exception, - null, - physicalAddress); + Mono httpResponseMono = this.httpClient + .send(httpRequest) + .doOnSubscribe(subscription -> { + sendTimeUtc.v = Instant.now(); + this.beforeRequest( + activityId, + httpRequest.uri(), + request.getResourceType(), + httpRequest.headers()); + }) + .onErrorResume(t -> { + Exception exception = Utils.as(t, Exception.class); + if (exception == null) { + logger.error("critical failure", t); + t.printStackTrace(); + assert false : "critical failure"; + return Mono.error(t); + } - return Single.error(goneException); - } else if (request.isReadOnlyRequest()) { - logger.trace("Received exception {} on readonly request" + - "sending the request to {}, will reresolve the address " + - "send time UTC: {}", - exception, - physicalAddress, - sendTimeUtc); + //Trace.CorrelationManager.ActivityId = activityId; + if (WebExceptionUtility.isWebExceptionRetriable(exception)) { + logger.debug("Received retriable exception {} " + + "sending the request to {}, will re-resolve the address " + + "send time UTC: {}", + exception, + physicalAddress, + sendTimeUtc); - GoneException goneException = new GoneException( - String.format( - RMResources.ExceptionMessage, - RMResources.Gone), - exception, - null, - physicalAddress); - - return Single.error(goneException); - } else { - // We can't throw a GoneException here because it will cause retry and we don't - // know if the request failed before or after the message got sent to the server. - // So in order to avoid duplicating the request we will not retry. - // TODO: a possible solution for this is to add the ability to send a request to the server - // to check if the previous request was received or not and act accordingly. - ServiceUnavailableException serviceUnavailableException = new ServiceUnavailableException( - String.format( - RMResources.ExceptionMessage, - RMResources.ServiceUnavailable), - exception, - null, - physicalAddress.toString()); - serviceUnavailableException.responseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); - serviceUnavailableException.responseHeaders().put(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH, "1"); - return Single.error(serviceUnavailableException); - } - }).doOnSuccess(httpClientResponse -> { - Instant receivedTimeUtc = Instant.now(); - double durationInMilliSeconds = (receivedTimeUtc.toEpochMilli() - sendTimeUtc.v.toEpochMilli()); - this.afterRequest( - activityId, - httpClientResponse.getStatus().code() , - durationInMilliSeconds, - httpClientResponse.getHeaders()); - }).doOnError( e -> { - Instant receivedTimeUtc = Instant.now(); - double durationInMilliSeconds = (receivedTimeUtc.toEpochMilli() - sendTimeUtc.v.toEpochMilli()); - this.afterRequest( - activityId, - 0, - durationInMilliSeconds, - null); - }); - - return responseMessage.flatMap(rsp -> processHttpResponse(request.getResourceAddress(), httpRequest, activityId.toString(), rsp, physicalAddress)); + GoneException goneException = new GoneException( + String.format( + RMResources.ExceptionMessage, + RMResources.Gone), + exception, + null, + physicalAddress); + + return Mono.error(goneException); + } else if (request.isReadOnlyRequest()) { + logger.trace("Received exception {} on readonly request" + + "sending the request to {}, will reresolve the address " + + "send time UTC: {}", + exception, + physicalAddress, + sendTimeUtc); + + GoneException goneException = new GoneException( + String.format( + RMResources.ExceptionMessage, + RMResources.Gone), + exception, + null, + physicalAddress); + + return Mono.error(goneException); + } else { + // We can't throw a GoneException here because it will cause retry and we don't + // know if the request failed before or after the message got sent to the server. + // So in order to avoid duplicating the request we will not retry. + // TODO: a possible solution for this is to add the ability to send a request to the server + // to check if the previous request was received or not and act accordingly. + ServiceUnavailableException serviceUnavailableException = new ServiceUnavailableException( + String.format( + RMResources.ExceptionMessage, + RMResources.ServiceUnavailable), + exception, + null, + physicalAddress.toString()); + serviceUnavailableException.responseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); + serviceUnavailableException.responseHeaders().put(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH, "1"); + return Mono.error(serviceUnavailableException); + }}) + .doOnSuccess(httpClientResponse -> { + Instant receivedTimeUtc = Instant.now(); + double durationInMilliSeconds = (receivedTimeUtc.toEpochMilli() - sendTimeUtc.v.toEpochMilli()); + this.afterRequest( + activityId, + httpClientResponse.statusCode(), + durationInMilliSeconds, + httpClientResponse.headers()); + }) + .doOnError(e -> { + Instant receivedTimeUtc = Instant.now(); + double durationInMilliSeconds = (receivedTimeUtc.toEpochMilli() - sendTimeUtc.v.toEpochMilli()); + this.afterRequest( + activityId, + 0, + durationInMilliSeconds, + null); + }); + + return httpResponseMono.flatMap(rsp -> processHttpResponse(request.getResourceAddress(), + httpRequest, activityId.toString(), rsp, physicalAddress)); } catch (Exception e) { - // TODO improve on exception catching - return Single.error(e); + return Mono.error(e); } } - private void beforeRequest(UUID activityId, String uri, ResourceType resourceType, HttpRequestHeaders requestHeaders) { + private void beforeRequest(UUID activityId, URI uri, ResourceType resourceType, HttpHeaders requestHeaders) { // TODO: perf counters // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/258624 } @@ -239,25 +233,25 @@ private void beforeRequest(UUID activityId, String uri, ResourceType resourceTyp private void afterRequest(UUID activityId, int statusCode, double durationInMilliSeconds, - HttpResponseHeaders responseHeaders) { + HttpHeaders responseHeaders) { // TODO: perf counters // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/258624 } - private static void addHeader(HttpRequestHeaders requestHeaders, String headerName, RxDocumentServiceRequest request) { + private static void addHeader(HttpHeaders requestHeaders, String headerName, RxDocumentServiceRequest request) { String headerValue = request.getHeaders().get(headerName); if (!Strings.isNullOrEmpty(headerValue)) { - requestHeaders.add(headerName, headerValue); + requestHeaders.set(headerName, headerValue); } } - private static void addHeader(HttpRequestHeaders requestHeaders, String headerName, String headerValue) { + private static void addHeader(HttpHeaders requestHeaders, String headerName, String headerValue) { if (!Strings.isNullOrEmpty(headerValue)) { - requestHeaders.add(headerName, headerValue); + requestHeaders.set(headerName, headerValue); } } - private String GetMatch(RxDocumentServiceRequest request, ResourceOperation resourceOperation) { + private String getMatch(RxDocumentServiceRequest request, ResourceOperation resourceOperation) { switch (resourceOperation.operationType) { case Delete: case ExecuteJavaScript: @@ -275,13 +269,13 @@ private String GetMatch(RxDocumentServiceRequest request, ResourceOperation reso } } - private HttpClientRequest prepareHttpMessage( + private HttpRequest prepareHttpMessage( UUID activityId, URI physicalAddress, ResourceOperation resourceOperation, RxDocumentServiceRequest request) throws Exception { - HttpClientRequest httpRequestMessage = null; + HttpRequest httpRequestMessage; URI requestUri; HttpMethod method; @@ -290,83 +284,83 @@ private HttpClientRequest prepareHttpMessage( // HttpRequestMessage -> StreamContent -> MemoryStream all get disposed, the original stream will be left open. switch (resourceOperation.operationType) { case Create: - requestUri = this.getResourceFeedUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress, request); method = HttpMethod.POST; assert request.getContent() != null; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); - httpRequestMessage.withContent(request.getContent()); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); + httpRequestMessage.withBody(request.getContent()); break; case ExecuteJavaScript: - requestUri = this.getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); method = HttpMethod.POST; assert request.getContent() != null; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); - httpRequestMessage.withContent(request.getContent()); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); + httpRequestMessage.withBody(request.getContent()); break; case Delete: - requestUri = this.getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); method = HttpMethod.DELETE; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); break; case Read: - requestUri = this.getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); method = HttpMethod.GET; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); break; case ReadFeed: - requestUri = this.getResourceFeedUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress, request); method = HttpMethod.GET; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); break; case Replace: - requestUri = this.getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); method = HttpMethod.PUT; assert request.getContent() != null; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); - httpRequestMessage.withContent(request.getContent()); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); + httpRequestMessage.withBody(request.getContent()); break; case Update: - requestUri = this.getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); method = new HttpMethod("PATCH"); assert request.getContent() != null; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); - httpRequestMessage.withContent(request.getContent()); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); + httpRequestMessage.withBody(request.getContent()); break; case Query: case SqlQuery: - requestUri = this.getResourceFeedUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress, request); method = HttpMethod.POST; assert request.getContent() != null; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); - httpRequestMessage.withContent(request.getContent()); - HttpTransportClient.addHeader(httpRequestMessage.getHeaders(), HttpConstants.HttpHeaders.CONTENT_TYPE, request); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); + httpRequestMessage.withBody(request.getContent()); + HttpTransportClient.addHeader(httpRequestMessage.headers(), HttpConstants.HttpHeaders.CONTENT_TYPE, request); break; case Upsert: - requestUri = this.getResourceFeedUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress, request); method = HttpMethod.POST; assert request.getContent() != null; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); - httpRequestMessage.withContent(request.getContent()); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); + httpRequestMessage.withBody(request.getContent()); break; case Head: - requestUri = this.getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress, request); method = HttpMethod.HEAD; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); break; case HeadFeed: - requestUri = this.getResourceFeedUri(resourceOperation.resourceType, physicalAddress, request); + requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress, request); method = HttpMethod.HEAD; - httpRequestMessage = HttpClientRequest.create(method, requestUri.toString()); + httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getPort()); break; default: @@ -375,7 +369,7 @@ private HttpClientRequest prepareHttpMessage( } Map documentServiceRequestHeaders = request.getHeaders(); - HttpRequestHeaders httpRequestHeaders = httpRequestMessage.getHeaders(); + HttpHeaders httpRequestHeaders = httpRequestMessage.headers(); // add default headers for(Map.Entry entry: defaultHeaders.entrySet()) { @@ -411,7 +405,7 @@ private HttpClientRequest prepareHttpMessage( String dateHeader = HttpUtils.getDateHeader(documentServiceRequestHeaders); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.X_DATE, dateHeader); - HttpTransportClient.addHeader(httpRequestHeaders, "Match", this.GetMatch(request, resourceOperation)); + HttpTransportClient.addHeader(httpRequestHeaders, "Match", this.getMatch(request, resourceOperation)); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IF_MODIFIED_SINCE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.A_IM, request); if (!request.getIsNameBased()) { @@ -421,7 +415,7 @@ private HttpClientRequest prepareHttpMessage( HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.ENTITY_ID, request.entityId); String fanoutRequestHeader = request.getHeaders().get(WFConstants.BackendHeaders.IS_FANOUT_REQUEST); - HttpTransportClient.addHeader(httpRequestMessage.getHeaders(), WFConstants.BackendHeaders.IS_FANOUT_REQUEST, fanoutRequestHeader); + HttpTransportClient.addHeader(httpRequestMessage.headers(), WFConstants.BackendHeaders.IS_FANOUT_REQUEST, fanoutRequestHeader); if (request.getResourceType() == ResourceType.DocumentCollection) { HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.COLLECTION_PARTITION_INDEX, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.COLLECTION_PARTITION_INDEX)); @@ -524,7 +518,7 @@ static URI getResourceFeedUri(ResourceType resourceType, URI physicalAddress, Rx } } - static URI getResourceEntryUri(ResourceType resourceType, URI physicalAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getResourceEntryUri(ResourceType resourceType, URI physicalAddress, RxDocumentServiceRequest request) throws Exception { switch (resourceType) { case Attachment: return getAttachmentEntryUri(physicalAddress, request); @@ -559,7 +553,7 @@ static URI getResourceEntryUri(ResourceType resourceType, URI physicalAddress, R } } - static URI createURI(URI baseAddress, String resourcePath) { + private static URI createURI(URI baseAddress, String resourcePath) { return baseAddress.resolve(HttpUtils.urlEncode(trimBeginningAndEndingSlashes(resourcePath))); } @@ -567,100 +561,99 @@ static URI getRootFeedUri(URI baseAddress) { return baseAddress; } - static URI getDatabaseFeedUri(URI baseAddress) throws Exception { + private static URI getDatabaseFeedUri(URI baseAddress) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Database, StringUtils.EMPTY, true)); } - static URI getDatabaseEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getDatabaseEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Database, request, false)); } - static URI getCollectionFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getCollectionFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.DocumentCollection, request, true)); } - static URI getStoredProcedureFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getStoredProcedureFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.StoredProcedure, request, true)); } - static URI getTriggerFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getTriggerFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Trigger, request, true)); } - static URI getUserDefinedFunctionFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getUserDefinedFunctionFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.UserDefinedFunction, request, true)); } - static URI getCollectionEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getCollectionEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.DocumentCollection, request, false)); } - static URI getStoredProcedureEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getStoredProcedureEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.StoredProcedure, request, false)); } - static URI getTriggerEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getTriggerEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Trigger, request, false)); } - static URI getUserDefinedFunctionEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getUserDefinedFunctionEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.UserDefinedFunction, request, false)); } - static URI getDocumentFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getDocumentFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Document, request, true)); } - static URI getDocumentEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getDocumentEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Document, request, false)); } - static URI getConflictFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getConflictFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Conflict, request, true)); } - static URI getConflictEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getConflictEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Conflict, request, false)); } - static URI getAttachmentFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getAttachmentFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Attachment, request, true)); } - static URI getAttachmentEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getAttachmentEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Attachment, request, false)); } - static URI getUserFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getUserFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.User, request, true)); } - static URI getUserEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getUserEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.User, request, false)); } - static URI getPermissionFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getPermissionFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Permission, request, true)); } - static URI getPermissionEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getPermissionEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Permission, request, false)); } - static URI getOfferFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getOfferFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Offer, request, true)); } - - static URI getSchemaFeedUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getSchemaFeedUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Schema, request, true)); } - static URI getSchemaEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getSchemaEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Schema, request, false)); } - static URI getOfferEntryUri(URI baseAddress, RxDocumentServiceRequest request) throws Exception { + private static URI getOfferEntryUri(URI baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Offer, request, false)); } @@ -674,64 +667,73 @@ static String getHeader(String[] names, String[] values, String name) { return null; } - private Single processHttpResponse(String resourceAddress, HttpClientRequest request, String activityId, HttpClientResponse response, URI physicalAddress) { + private Mono processHttpResponse(String resourceAddress, HttpRequest httpRequest, String activityId, HttpResponse response, URI physicalAddress) { if (response == null) { InternalServerErrorException exception = - new InternalServerErrorException( - String.format( - RMResources.ExceptionMessage, - RMResources.InvalidBackendResponse), - null, - physicalAddress); + new InternalServerErrorException( + String.format( + RMResources.ExceptionMessage, + RMResources.InvalidBackendResponse), + null, + physicalAddress); exception.responseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, - activityId); + activityId); exception.responseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); - return Single.error(exception); + return Mono.error(exception); } // If the status code is < 300 or 304 NotModified (we treat not modified as success) then it means that it's a success code and shouldn't throw. - if (response.getStatus().code() < HttpConstants.StatusCodes.MINIMUM_STATUSCODE_AS_ERROR_GATEWAY || - response.getStatus().code() == HttpConstants.StatusCodes.NOT_MODIFIED) { - return HttpTransportClient.createStoreResponseFromHttpResponse(response); + if (response.statusCode() < HttpConstants.StatusCodes.MINIMUM_STATUSCODE_AS_ERROR_GATEWAY || + response.statusCode() == HttpConstants.StatusCodes.NOT_MODIFIED) { + return ResponseUtils.toStoreResponse(response, httpRequest); } else { - return this.createErrorResponseFromHttpResponse(resourceAddress, activityId, request, response); + return this.createErrorResponseFromHttpResponse(resourceAddress, activityId, httpRequest, response); } } - private Single createErrorResponseFromHttpResponse(String resourceAddress, String activityId, - HttpClientRequest request, - HttpClientResponse response) { - HttpResponseStatus statusCode = response.getStatus(); - Single errorMessageObs = ErrorUtils.getErrorResponseAsync(response); + private Mono createErrorResponseFromHttpResponse(String resourceAddress, String activityId, + HttpRequest request, + HttpResponse response) { + int statusCode = response.statusCode(); + Mono errorMessageObs = ErrorUtils.getErrorResponseAsync(response, request); return errorMessageObs.flatMap( errorMessage -> { long responseLSN = -1; - List lsnValues; - if ((lsnValues = response.getHeaders().getAll(WFConstants.BackendHeaders.LSN)) != null) { + List lsnValues = null; + String[] headerValues = response.headers().values(WFConstants.BackendHeaders.LSN); + if (headerValues != null) { + lsnValues = com.google.common.collect.Lists.newArrayList(headerValues); + } + + if (lsnValues != null) { String temp = lsnValues.isEmpty() ? null : lsnValues.get(0); responseLSN = Longs.tryParse(temp, responseLSN); } String responsePartitionKeyRangeId = null; - List partitionKeyRangeIdValues; - if ((partitionKeyRangeIdValues = response.getHeaders().getAll(WFConstants.BackendHeaders.PARTITION_KEY_RANGE_ID)) != null) { + List partitionKeyRangeIdValues = null; + headerValues = response.headers().values(WFConstants.BackendHeaders.PARTITION_KEY_RANGE_ID); + if (headerValues != null) { + partitionKeyRangeIdValues = com.google.common.collect.Lists.newArrayList(headerValues); + } + if (partitionKeyRangeIdValues != null) { responsePartitionKeyRangeId = Lists.firstOrDefault(partitionKeyRangeIdValues, null); } CosmosClientException exception; - switch (statusCode.code()) { + switch (statusCode) { case HttpConstants.StatusCodes.UNAUTHORIZED: exception = new UnauthorizedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Unauthorized : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); break; case HttpConstants.StatusCodes.FORBIDDEN: @@ -739,8 +741,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Forbidden : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); break; case HttpConstants.StatusCodes.NOTFOUND: @@ -751,15 +753,15 @@ private Single createErrorResponseFromHttpResponse(String resourc // the presence of Content-Type header in the response // and map it to HTTP Gone (410), which is the more // appropriate response for this case. - if (response.getContent() != null && response.getHeaders() != null && response.getHeaders().get(HttpConstants.HttpHeaders.CONTENT_TYPE) != null && - !Strings.isNullOrEmpty(response.getHeaders().get(HttpConstants.HttpHeaders.CONTENT_TYPE)) && - Strings.containsIgnoreCase(response.getHeaders().get(HttpConstants.HttpHeaders.CONTENT_TYPE), RuntimeConstants.MediaTypes.TEXT_HTML)) { + if (response.body() != null && response.headers() != null && response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE) != null && + !Strings.isNullOrEmpty(response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE)) && + Strings.containsIgnoreCase(response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE), RuntimeConstants.MediaTypes.TEXT_HTML)) { // Have the request URL in the exception message for debugging purposes. exception = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), - request.getUri()); + request.uri().toString()); exception.responseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); @@ -769,8 +771,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.NotFound : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); break; } @@ -779,8 +781,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.BadRequest : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); break; case HttpConstants.StatusCodes.METHOD_NOT_ALLOWED: @@ -789,28 +791,26 @@ private Single createErrorResponseFromHttpResponse(String resourc RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.MethodNotAllowed : errorMessage), null, - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri().toString()); break; case HttpConstants.StatusCodes.GONE: { // TODO: update perf counter // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/258624 - ErrorUtils.logGoneException(request.getUri(), activityId); + ErrorUtils.logGoneException(request.uri(), activityId); Integer nSubStatus = 0; - String valueSubStatus = null; - - valueSubStatus = response.getHeaders().get(WFConstants.BackendHeaders.SUB_STATUS); + String valueSubStatus = response.headers().value(WFConstants.BackendHeaders.SUB_STATUS); if (!Strings.isNullOrEmpty(valueSubStatus)) { if ((nSubStatus = Integers.tryParse(valueSubStatus)) == null) { exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); break; } } @@ -820,32 +820,32 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE) { exception = new PartitionKeyRangeGoneException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.COMPLETING_SPLIT) { exception = new PartitionKeyRangeIsSplittingException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.COMPLETING_PARTITION_MIGRATION) { exception = new PartitionIsMigratingException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri().toString()); break; } else { // Have the request URL in the exception message for debugging purposes. @@ -853,8 +853,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, RMResources.Gone), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); exception.responseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); @@ -867,8 +867,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.EntityAlreadyExists : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri().toString()); break; case HttpConstants.StatusCodes.PRECONDITION_FAILED: @@ -876,8 +876,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.PreconditionFailed : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri().toString()); break; case HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE: @@ -887,8 +887,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.RequestEntityTooLarge, HttpConstants.HttpHeaders.PAGE_SIZE)), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri().toString()); break; case HttpConstants.StatusCodes.LOCKED: @@ -896,8 +896,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Locked : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri().toString()); break; case HttpConstants.StatusCodes.SERVICE_UNAVAILABLE: @@ -905,8 +905,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.ServiceUnavailable : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); break; case HttpConstants.StatusCodes.REQUEST_TIMEOUT: @@ -914,8 +914,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.RequestTimeout : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); break; case HttpConstants.StatusCodes.RETRY_WITH: @@ -923,8 +923,8 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.RetryWith : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); break; case HttpConstants.StatusCodes.TOO_MANY_REQUESTS: @@ -933,11 +933,14 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.TooManyRequests : errorMessage), - response.getHeaders(), - request.getUri()); - - List values = response.getHeaders().getAll(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); + response.headers(), + request.uri()); + List values = null; + headerValues = response.headers().values(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); + if (headerValues != null) { + values = com.google.common.collect.Lists.newArrayList(headerValues); + } if (values == null || values.isEmpty()) { logger.warn("RequestRateTooLargeException being thrown without RetryAfter."); } else { @@ -951,36 +954,29 @@ private Single createErrorResponseFromHttpResponse(String resourc String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.InternalServerError : errorMessage), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); break; default: logger.error("Unrecognized status code {} returned by backend. ActivityId {}", statusCode, activityId); - ErrorUtils.logException(request.getUri(), activityId); + ErrorUtils.logException(request.uri(), activityId); exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), - response.getHeaders(), - request.getUri()); + response.headers(), + request.uri()); break; } BridgeInternal.setLSN(exception, responseLSN); BridgeInternal.setPartitionKeyRangeId(exception, responsePartitionKeyRangeId); BridgeInternal.setResourceAddress(exception, resourceAddress); - BridgeInternal.setRequestHeaders(exception, HttpUtils.asMap(request.getHeaders())); + BridgeInternal.setRequestHeaders(exception, HttpUtils.asMap(request.headers())); - return Single.error(exception); + return Mono.error(exception); } ); } - - private static Single createStoreResponseFromHttpResponse( - HttpClientResponse responseMessage) { - - Single storeResponse = ResponseUtils.toStoreResponse(responseMessage); - return storeResponse; - } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressCache.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressCache.java index 98af574519688..b42b7a364de65 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressCache.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressCache.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import rx.Single; +import reactor.core.publisher.Mono; public interface IAddressCache { @@ -39,7 +39,7 @@ public interface IAddressCache { * @param forceRefreshPartitionAddresses Whether addresses need to be refreshed as previously resolved addresses were determined to be outdated. * @return Physical addresses. */ - Single tryGetAddresses( + Mono tryGetAddresses( RxDocumentServiceRequest request, PartitionKeyRangeIdentity partitionKeyRangeIdentity, boolean forceRefreshPartitionAddresses); diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressResolver.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressResolver.java index aa375a33c1cda..f051489d74d9f 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressResolver.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressResolver.java @@ -24,10 +24,10 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import rx.Single; +import reactor.core.publisher.Mono; public interface IAddressResolver { - Single resolveAsync( + Mono resolveAsync( RxDocumentServiceRequest request, boolean forceRefreshPartitionAddresses); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IStoreClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IStoreClient.java index fcaa8f0d94b85..054db339f5f03 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IStoreClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IStoreClient.java @@ -26,29 +26,30 @@ import com.azure.data.cosmos.internal.IRetryPolicy; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; -import rx.Single; -import rx.functions.Func1; +import reactor.core.publisher.Mono; + +import java.util.function.Function; public interface IStoreClient { - Single processMessageAsync( + Mono processMessageAsync( RxDocumentServiceRequest request, IRetryPolicy retryPolicy, - Func1> prepareRequestAsyncDelegate); + Function> prepareRequestAsyncDelegate); - default Single processMessageAsync( + default Mono processMessageAsync( RxDocumentServiceRequest request, - Func1> prepareRequestAsyncDelegate) { + Function> prepareRequestAsyncDelegate) { return processMessageAsync(request, null, prepareRequestAsyncDelegate); } - default Single processMessageAsync( + default Mono processMessageAsync( RxDocumentServiceRequest request, IRetryPolicy retryPolicy) { return processMessageAsync(request, retryPolicy, null); } - default Single processMessageAsync( + default Mono processMessageAsync( RxDocumentServiceRequest request) { return processMessageAsync(request, null, null); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java index dd58608203a36..55697eda865cc 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -56,8 +56,8 @@ public LockedException(String msg, String resourceAddress) { super(msg, null, null, HttpConstants.StatusCodes.LOCKED, resourceAddress); } - public LockedException(String message, HttpResponseHeaders headers, String requestUri) { - this(message, null, headers, requestUri); + public LockedException(String message, HttpHeaders headers, String requestUriString) { + this(message, null, headers, requestUriString); } public LockedException(Exception innerException) { @@ -66,12 +66,12 @@ public LockedException(Exception innerException) { public LockedException(String message, Exception innerException, - HttpResponseHeaders headers, - String requestUri) { + HttpHeaders headers, + String requestUriString) { super(String.format("%s: %s", RMResources.Locked, message), innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.LOCKED, - requestUri); + requestUriString); } } \ No newline at end of file diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java index 7c74e1357378c..308b0728b5ccb 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.util.Map; @@ -45,14 +45,14 @@ public MethodNotAllowedException(Error error, long lsn, String partitionKeyRange } public MethodNotAllowedException(String message) { - this(message, (Exception) null, (HttpResponseHeaders) null, null); + this(message, null, null, null); } - public MethodNotAllowedException(String message, HttpResponseHeaders headers, String requestUri) { - this(message, null, headers, requestUri); + public MethodNotAllowedException(String message, HttpHeaders headers, String requestUriString) { + this(message, null, headers, requestUriString); } - public MethodNotAllowedException(String message, HttpResponseHeaders headers, URI requestUri) { + public MethodNotAllowedException(String message, HttpHeaders headers, URI requestUri) { this(message, headers, requestUri != null ? requestUri.toString() : null); } @@ -62,12 +62,12 @@ public MethodNotAllowedException(Exception innerException) { public MethodNotAllowedException(String message, Exception innerException, - HttpResponseHeaders headers, - String requestUri) { + HttpHeaders headers, + String requestUriString) { super(String.format("%s: %s", RMResources.MethodNotAllowed, message), innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.METHOD_NOT_ALLOWED, - requestUri != null ? requestUri.toString() : null); + requestUriString); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java index b76ca82264d3d..faedc7a43ce15 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -53,25 +53,25 @@ public PartitionKeyRangeGoneException(Error error, long lsn, String partitionKey } public PartitionKeyRangeGoneException(String message) { - this(message, (Exception) null, null, null); + this(message, null, null, null); } public PartitionKeyRangeGoneException(String message, Exception innerException) { - this(message, innerException, (HttpResponseHeaders) null, null); + this(message, innerException, null, null); } public PartitionKeyRangeGoneException(Exception innerException) { - this(RMResources.Gone, innerException, (HttpResponseHeaders) null, null); + this(RMResources.Gone, innerException, null, null); } - public PartitionKeyRangeGoneException(String message, HttpResponseHeaders headers, String requestUri) { - super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUri); + public PartitionKeyRangeGoneException(String message, HttpHeaders headers, String requestUriString) { + super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUriString); this.setSubstatus(); } - public PartitionKeyRangeGoneException(String message, Exception innerException, HttpResponseHeaders headers, String requestUri) { - super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUri); + public PartitionKeyRangeGoneException(String message, Exception innerException, HttpHeaders headers, String requestUriString) { + super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUriString); this.setSubstatus(); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java index e26450aa4eb89..0fd726c167137 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -57,8 +57,8 @@ public PreconditionFailedException(String msg, String resourceAddress) { super(msg, null, null, HttpConstants.StatusCodes.PRECONDITION_FAILED, resourceAddress); } - public PreconditionFailedException(String message, HttpResponseHeaders headers, String requestUri) { - this(message, null, headers, requestUri); + public PreconditionFailedException(String message, HttpHeaders headers, String requestUriString) { + this(message, null, headers, requestUriString); } public PreconditionFailedException(Exception innerException) { @@ -67,12 +67,12 @@ public PreconditionFailedException(Exception innerException) { public PreconditionFailedException(String message, Exception innerException, - HttpResponseHeaders headers, - String requestUri) { + HttpHeaders headers, + String requestUriString) { super(String.format("%s: %s", RMResources.PreconditionFailed, message), innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.PRECONDITION_FAILED, - requestUri); + requestUriString); } } \ No newline at end of file diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java index ecd2d097856d4..e3828f79d20db 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java @@ -38,12 +38,12 @@ import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import java.time.Duration; import java.util.Comparator; import java.util.List; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; @@ -105,12 +105,12 @@ public class QuorumReader { private final IAuthorizationTokenProvider authorizationTokenProvider; public QuorumReader( - Configs configs, - TransportClient transportClient, - AddressSelector addressSelector, - StoreReader storeReader, - GatewayServiceConfigurationReader serviceConfigReader, - IAuthorizationTokenProvider authorizationTokenProvider) { + Configs configs, + TransportClient transportClient, + AddressSelector addressSelector, + StoreReader storeReader, + GatewayServiceConfigurationReader serviceConfigReader, + IAuthorizationTokenProvider authorizationTokenProvider) { this.storeReader = storeReader; this.serviceConfigReader = serviceConfigReader; this.authorizationTokenProvider = authorizationTokenProvider; @@ -126,247 +126,247 @@ public QuorumReader( } public QuorumReader( - TransportClient transportClient, - AddressSelector addressSelector, - StoreReader storeReader, - GatewayServiceConfigurationReader serviceConfigReader, - IAuthorizationTokenProvider authorizationTokenProvider, - Configs configs) { + TransportClient transportClient, + AddressSelector addressSelector, + StoreReader storeReader, + GatewayServiceConfigurationReader serviceConfigReader, + IAuthorizationTokenProvider authorizationTokenProvider, + Configs configs) { this(configs, transportClient, addressSelector, storeReader, serviceConfigReader, authorizationTokenProvider); } - public Single readStrongAsync( - RxDocumentServiceRequest entity, - int readQuorumValue, - ReadMode readMode) { + public Mono readStrongAsync( + RxDocumentServiceRequest entity, + int readQuorumValue, + ReadMode readMode) { final MutableVolatile shouldRetryOnSecondary = new MutableVolatile<>(false); final MutableVolatile hasPerformedReadFromPrimary = new MutableVolatile<>(false); - return Observable.defer( - // the following will be repeated till the repeat().takeUntil(.) condition is satisfied. - () -> { - if (entity.requestContext.timeoutHelper.isElapsed()) { - return Observable.error(new GoneException()); - } + return Flux.defer( + // the following will be repeated till the repeat().takeUntil(.) condition is satisfied. + () -> { + if (entity.requestContext.timeoutHelper.isElapsed()) { + return Flux.error(new GoneException()); + } - shouldRetryOnSecondary.v = false; - Single secondaryQuorumReadResultObs = - this.readQuorumAsync(entity, readQuorumValue, false, readMode); + shouldRetryOnSecondary.v = false; + Mono secondaryQuorumReadResultObs = + this.readQuorumAsync(entity, readQuorumValue, false, readMode); - return secondaryQuorumReadResultObs.toObservable().flatMap( - secondaryQuorumReadResult -> { + return secondaryQuorumReadResultObs.flux().flatMap( + secondaryQuorumReadResult -> { - switch (secondaryQuorumReadResult.quorumResult) { - case QuorumMet: - try { - return Observable.just(secondaryQuorumReadResult.getResponse()); - } catch (CosmosClientException e) { - return Observable.error(e); - } + switch (secondaryQuorumReadResult.quorumResult) { + case QuorumMet: + try { + return Flux.just(secondaryQuorumReadResult.getResponse()); + } catch (CosmosClientException e) { + return Flux.error(e); + } + + case QuorumSelected: + Mono barrierRequestObs = BarrierRequestHelper.createAsync( + entity, + this.authorizationTokenProvider, + secondaryQuorumReadResult.selectedLsn, + secondaryQuorumReadResult.globalCommittedSelectedLsn); + + return barrierRequestObs.flux().flatMap(barrierRequest -> { + Mono readBarrierObs = this.waitForReadBarrierAsync( + barrierRequest, + true /* include primary */, + readQuorumValue, + secondaryQuorumReadResult.selectedLsn, + secondaryQuorumReadResult.globalCommittedSelectedLsn, + readMode); + + return readBarrierObs.flux().flatMap( + readBarrier -> { + + if (readBarrier) { + try { + return Flux.just(secondaryQuorumReadResult.getResponse()); + } catch (Exception e) { + return Flux.error(e); + } + } - case QuorumSelected: - Single barrierRequestObs = BarrierRequestHelper.createAsync( - entity, - this.authorizationTokenProvider, + // else barrier was not successful + logger.warn( + "QuorumSelected: Could not converge on the LSN {} GlobalCommittedLSN {} after primary read barrier with read quorum {} for strong read, Responses: {}", secondaryQuorumReadResult.selectedLsn, - secondaryQuorumReadResult.globalCommittedSelectedLsn); - - return barrierRequestObs.toObservable().flatMap(barrierRequest -> { - Single readBarrierObs = this.waitForReadBarrierAsync( - barrierRequest, - true /* include primary */, - readQuorumValue, - secondaryQuorumReadResult.selectedLsn, - secondaryQuorumReadResult.globalCommittedSelectedLsn, - readMode); - - return readBarrierObs.toObservable().flatMap( - readBarrier -> { - - if (readBarrier) { - try { - return Observable.just(secondaryQuorumReadResult.getResponse()); - } catch (Exception e) { - return Observable.error(e); - } - } - - // else barrier was not successful - logger.warn( - "QuorumSelected: Could not converge on the LSN {} GlobalCommittedLSN {} after primary read barrier with read quorum {} for strong read, Responses: {}", - secondaryQuorumReadResult.selectedLsn, - secondaryQuorumReadResult.globalCommittedSelectedLsn, - readQuorumValue, - String.join(";", secondaryQuorumReadResult.storeResponses) - ); - - entity.requestContext.quorumSelectedStoreResponse = secondaryQuorumReadResult.selectedResponse; - entity.requestContext.storeResponses = secondaryQuorumReadResult.storeResponses; - entity.requestContext.quorumSelectedLSN = secondaryQuorumReadResult.selectedLsn; - entity.requestContext.globalCommittedSelectedLSN = secondaryQuorumReadResult.globalCommittedSelectedLsn; - - return Observable.empty(); - } + secondaryQuorumReadResult.globalCommittedSelectedLsn, + readQuorumValue, + String.join(";", secondaryQuorumReadResult.storeResponses) ); - }); - case QuorumNotSelected: - if (hasPerformedReadFromPrimary.v) { - logger.warn("QuorumNotSelected: Primary read already attempted. Quorum could not be selected after retrying on secondaries."); - return Observable.error(new GoneException(RMResources.ReadQuorumNotMet)); + entity.requestContext.quorumSelectedStoreResponse = secondaryQuorumReadResult.selectedResponse; + entity.requestContext.storeResponses = secondaryQuorumReadResult.storeResponses; + entity.requestContext.quorumSelectedLSN = secondaryQuorumReadResult.selectedLsn; + entity.requestContext.globalCommittedSelectedLSN = secondaryQuorumReadResult.globalCommittedSelectedLsn; + + return Flux.empty(); } + ); + }); - logger.warn("QuorumNotSelected: Quorum could not be selected with read quorum of {}", readQuorumValue); - Single responseObs = this.readPrimaryAsync(entity, readQuorumValue, false); - - return responseObs.toObservable().flatMap( - response -> { - if (response.isSuccessful && response.shouldRetryOnSecondary) { - assert false : "QuorumNotSelected: PrimaryResult has both Successful and shouldRetryOnSecondary flags set"; - logger.error("PrimaryResult has both Successful and shouldRetryOnSecondary flags set"); - } else if (response.isSuccessful) { - logger.debug("QuorumNotSelected: ReadPrimary successful"); - try { - return Observable.just(response.getResponse()); - } catch (CosmosClientException e) { - return Observable.error(e); - } - } else if (response.shouldRetryOnSecondary) { - shouldRetryOnSecondary.v = true; - logger.warn("QuorumNotSelected: ReadPrimary did not succeed. Will retry on secondary."); - hasPerformedReadFromPrimary.v = true; - } else { - logger.warn("QuorumNotSelected: Could not get successful response from ReadPrimary"); - return Observable.error(new GoneException(String.format(RMResources.ReadQuorumNotMet, readQuorumValue))); - } - - return Observable.empty(); + case QuorumNotSelected: + if (hasPerformedReadFromPrimary.v) { + logger.warn("QuorumNotSelected: Primary read already attempted. Quorum could not be selected after retrying on secondaries."); + return Flux.error(new GoneException(RMResources.ReadQuorumNotMet)); + } - } - ); + logger.warn("QuorumNotSelected: Quorum could not be selected with read quorum of {}", readQuorumValue); + Mono responseObs = this.readPrimaryAsync(entity, readQuorumValue, false); + + return responseObs.flux().flatMap( + response -> { + if (response.isSuccessful && response.shouldRetryOnSecondary) { + assert false : "QuorumNotSelected: PrimaryResult has both Successful and shouldRetryOnSecondary flags set"; + logger.error("PrimaryResult has both Successful and shouldRetryOnSecondary flags set"); + } else if (response.isSuccessful) { + logger.debug("QuorumNotSelected: ReadPrimary successful"); + try { + return Flux.just(response.getResponse()); + } catch (CosmosClientException e) { + return Flux.error(e); + } + } else if (response.shouldRetryOnSecondary) { + shouldRetryOnSecondary.v = true; + logger.warn("QuorumNotSelected: ReadPrimary did not succeed. Will retry on secondary."); + hasPerformedReadFromPrimary.v = true; + } else { + logger.warn("QuorumNotSelected: Could not get successful response from ReadPrimary"); + return Flux.error(new GoneException(String.format(RMResources.ReadQuorumNotMet, readQuorumValue))); + } - default: - logger.error("Unknown ReadQuorum result {}", secondaryQuorumReadResult.quorumResult.toString()); - return Observable.error(new InternalServerErrorException(RMResources.InternalServerError)); - } + return Flux.empty(); + + } + ); - }); - }).repeat(maxNumberOfReadQuorumRetries) - .takeUntil(dummy -> !shouldRetryOnSecondary.v) - .concatWith(Observable.defer(() -> { - logger.warn("Could not complete read quorum with read quorum value of {}", readQuorumValue); - - return Observable.error(new GoneException( - String.format( - RMResources.ReadQuorumNotMet, - readQuorumValue))); - })) - .take(1) - .toSingle(); + default: + logger.error("Unknown ReadQuorum result {}", secondaryQuorumReadResult.quorumResult.toString()); + return Flux.error(new InternalServerErrorException(RMResources.InternalServerError)); + } + + }); + }).repeat(maxNumberOfReadQuorumRetries) + .takeUntil(dummy -> !shouldRetryOnSecondary.v) + .concatWith(Flux.defer(() -> { + logger.warn("Could not complete read quorum with read quorum value of {}", readQuorumValue); + + return Flux.error(new GoneException( + String.format( + RMResources.ReadQuorumNotMet, + readQuorumValue))); + })) + .take(1) + .single(); } - private Single readQuorumAsync( - RxDocumentServiceRequest entity, - int readQuorum, - boolean includePrimary, - ReadMode readMode) { + private Mono readQuorumAsync( + RxDocumentServiceRequest entity, + int readQuorum, + boolean includePrimary, + ReadMode readMode) { if (entity.requestContext.timeoutHelper.isElapsed()) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } return ensureQuorumSelectedStoreResponse(entity, readQuorum, includePrimary, readMode).flatMap( - res -> { - if (res.getLeft() != null) { - // no need for barrier - return Single.just(res.getKey()); - } + res -> { + if (res.getLeft() != null) { + // no need for barrier + return Mono.just(res.getKey()); + } - long readLsn = res.getValue().getValue0(); - long globalCommittedLSN = res.getValue().getValue1(); - StoreResult storeResult = res.getValue().getValue2(); - List storeResponses = res.getValue().getValue3(); - - // ReadBarrier required - Single barrierRequestObs = BarrierRequestHelper.createAsync(entity, this.authorizationTokenProvider, readLsn, globalCommittedLSN); - return barrierRequestObs.flatMap( - barrierRequest -> { - Single waitForObs = this.waitForReadBarrierAsync(barrierRequest, false, readQuorum, readLsn, globalCommittedLSN, readMode); - return waitForObs.flatMap( - waitFor -> { - if (!waitFor) { - return Single.just(new ReadQuorumResult( - entity.requestContext.requestChargeTracker, - ReadQuorumResultKind.QuorumSelected, - readLsn, - globalCommittedLSN, - storeResult, - storeResponses)); - } + long readLsn = res.getValue().getValue0(); + long globalCommittedLSN = res.getValue().getValue1(); + StoreResult storeResult = res.getValue().getValue2(); + List storeResponses = res.getValue().getValue3(); + + // ReadBarrier required + Mono barrierRequestObs = BarrierRequestHelper.createAsync(entity, this.authorizationTokenProvider, readLsn, globalCommittedLSN); + return barrierRequestObs.flatMap( + barrierRequest -> { + Mono waitForObs = this.waitForReadBarrierAsync(barrierRequest, false, readQuorum, readLsn, globalCommittedLSN, readMode); + return waitForObs.flatMap( + waitFor -> { + if (!waitFor) { + return Mono.just(new ReadQuorumResult( + entity.requestContext.requestChargeTracker, + ReadQuorumResultKind.QuorumSelected, + readLsn, + globalCommittedLSN, + storeResult, + storeResponses)); + } - return Single.just(new ReadQuorumResult( - entity.requestContext.requestChargeTracker, - ReadQuorumResultKind.QuorumMet, - readLsn, - globalCommittedLSN, - storeResult, - storeResponses)); - } - ); + return Mono.just(new ReadQuorumResult( + entity.requestContext.requestChargeTracker, + ReadQuorumResultKind.QuorumMet, + readLsn, + globalCommittedLSN, + storeResult, + storeResponses)); } - ); - } + ); + } + ); + } ); } - private Single>>> ensureQuorumSelectedStoreResponse(RxDocumentServiceRequest entity, int readQuorum, boolean includePrimary, ReadMode readMode) { + private Mono>>> ensureQuorumSelectedStoreResponse(RxDocumentServiceRequest entity, int readQuorum, boolean includePrimary, ReadMode readMode) { if (entity.requestContext.quorumSelectedStoreResponse == null) { - Single> responseResultObs = this.storeReader.readMultipleReplicaAsync( - entity, includePrimary, readQuorum, true /*required valid LSN*/, false, readMode); + Mono> responseResultObs = this.storeReader.readMultipleReplicaAsync( + entity, includePrimary, readQuorum, true /*required valid LSN*/, false, readMode); return responseResultObs.flatMap( - responseResult -> { - List storeResponses = responseResult.stream().map(response -> response.toString()).collect(Collectors.toList()); - int responseCount = (int) responseResult.stream().filter(response -> response.isValid).count(); - if (responseCount < readQuorum) { - return Single.just(Pair.of(new ReadQuorumResult(entity.requestContext.requestChargeTracker, - ReadQuorumResultKind.QuorumNotSelected, - -1, -1, null, storeResponses), null)); - } + responseResult -> { + List storeResponses = responseResult.stream().map(response -> response.toString()).collect(Collectors.toList()); + int responseCount = (int) responseResult.stream().filter(response -> response.isValid).count(); + if (responseCount < readQuorum) { + return Mono.just(Pair.of(new ReadQuorumResult(entity.requestContext.requestChargeTracker, + ReadQuorumResultKind.QuorumNotSelected, + -1, -1, null, storeResponses), null)); + } - //either request overrides consistency level with strong, or request does not override and account default consistency level is strong - boolean isGlobalStrongReadCandidate = - (ReplicatedResourceClient.isGlobalStrongEnabled() && this.serviceConfigReader.getDefaultConsistencyLevel() == ConsistencyLevel.STRONG) && - (entity.requestContext.originalRequestConsistencyLevel == null || entity.requestContext.originalRequestConsistencyLevel == ConsistencyLevel.STRONG); - - ValueHolder readLsn = new ValueHolder(-1); - ValueHolder globalCommittedLSN = new ValueHolder(-1); - ValueHolder storeResult = new ValueHolder(null); - - if (this.isQuorumMet( - responseResult, - readQuorum, - false, - isGlobalStrongReadCandidate, - readLsn, - globalCommittedLSN, - storeResult)) { - return Single.just(Pair.of(new ReadQuorumResult( - entity.requestContext.requestChargeTracker, - ReadQuorumResultKind.QuorumMet, - readLsn.v, - globalCommittedLSN.v, - storeResult.v, - storeResponses), null)); - } + //either request overrides consistency level with strong, or request does not override and account default consistency level is strong + boolean isGlobalStrongReadCandidate = + (ReplicatedResourceClient.isGlobalStrongEnabled() && this.serviceConfigReader.getDefaultConsistencyLevel() == ConsistencyLevel.STRONG) && + (entity.requestContext.originalRequestConsistencyLevel == null || entity.requestContext.originalRequestConsistencyLevel == ConsistencyLevel.STRONG); + + ValueHolder readLsn = new ValueHolder(-1); + ValueHolder globalCommittedLSN = new ValueHolder(-1); + ValueHolder storeResult = new ValueHolder(null); + + if (this.isQuorumMet( + responseResult, + readQuorum, + false, + isGlobalStrongReadCandidate, + readLsn, + globalCommittedLSN, + storeResult)) { + return Mono.just(Pair.of(new ReadQuorumResult( + entity.requestContext.requestChargeTracker, + ReadQuorumResultKind.QuorumMet, + readLsn.v, + globalCommittedLSN.v, + storeResult.v, + storeResponses), null)); + } - // at this point, if refresh were necessary, we would have refreshed it in ReadMultipleReplicaAsync - // so set to false here to avoid further refrehses for this request. - entity.requestContext.forceRefreshAddressCache = false; + // at this point, if refresh were necessary, we would have refreshed it in ReadMultipleReplicaAsync + // so set to false here to avoid further refrehses for this request. + entity.requestContext.forceRefreshAddressCache = false; - Quadruple> state = Quadruple.with(readLsn.v, globalCommittedLSN.v, storeResult.v, storeResponses); - return Single.just(Pair.of(null, state)); - } + Quadruple> state = Quadruple.with(readLsn.v, globalCommittedLSN.v, storeResult.v, storeResponses); + return Mono.just(Pair.of(null, state)); + } ); } else { @@ -376,7 +376,7 @@ private Single storeResponses = entity.requestContext.storeResponses; Quadruple> state = Quadruple.with(readLsn.v, globalCommittedLSN.v, storeResult.v, storeResponses); - return Single.just(Pair.of(null, state)); + return Mono.just(Pair.of(null, state)); } } @@ -388,270 +388,268 @@ private Single readPrimaryAsync( - RxDocumentServiceRequest entity, - int readQuorum, - boolean useSessionToken) { + private Mono readPrimaryAsync( + RxDocumentServiceRequest entity, + int readQuorum, + boolean useSessionToken) { if (entity.requestContext.timeoutHelper.isElapsed()) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } // We would have already refreshed address before reaching here. Avoid performing here. entity.requestContext.forceRefreshAddressCache = false; - Single storeResultObs = this.storeReader.readPrimaryAsync( - entity, true /*required valid LSN*/, useSessionToken); + Mono storeResultObs = this.storeReader.readPrimaryAsync( + entity, true /*required valid LSN*/, useSessionToken); return storeResultObs.flatMap( - storeResult -> { - if (!storeResult.isValid) { - try { - return Single.error(storeResult.getException()); - } catch (InternalServerErrorException e) { - return Single.error(e); - } + storeResult -> { + if (!storeResult.isValid) { + try { + return Mono.error(storeResult.getException()); + } catch (InternalServerErrorException e) { + return Mono.error(e); } + } - if (storeResult.currentReplicaSetSize <= 0 || storeResult.lsn < 0 || storeResult.quorumAckedLSN < 0) { - String message = String.format( - "INVALID value received from response header. CurrentReplicaSetSize %d, StoreLSN %d, QuorumAckedLSN %d", - storeResult.currentReplicaSetSize, storeResult.lsn, storeResult.quorumAckedLSN); + if (storeResult.currentReplicaSetSize <= 0 || storeResult.lsn < 0 || storeResult.quorumAckedLSN < 0) { + String message = String.format( + "INVALID value received from response header. CurrentReplicaSetSize %d, StoreLSN %d, QuorumAckedLSN %d", + storeResult.currentReplicaSetSize, storeResult.lsn, storeResult.quorumAckedLSN); - // might not be returned if primary is still building the secondary replicas (during churn) - logger.error(message); + // might not be returned if primary is still building the secondary replicas (during churn) + logger.error(message); - // throw exception instead of returning inconsistent result. - return Single.error(new GoneException(String.format(RMResources.ReadQuorumNotMet, readQuorum))); + // throw exception instead of returning inconsistent result. + return Mono.error(new GoneException(String.format(RMResources.ReadQuorumNotMet, readQuorum))); - } + } - if (storeResult.currentReplicaSetSize > readQuorum) { - logger.warn( - "Unexpected response. Replica Set size is {} which is greater than min value {}", storeResult.currentReplicaSetSize, readQuorum); - return Single.just(new ReadPrimaryResult(entity.requestContext.requestChargeTracker, /*isSuccessful */ false, - /* shouldRetryOnSecondary: */ true, /* response: */ null)); - } + if (storeResult.currentReplicaSetSize > readQuorum) { + logger.warn( + "Unexpected response. Replica Set size is {} which is greater than min value {}", storeResult.currentReplicaSetSize, readQuorum); + return Mono.just(new ReadPrimaryResult(entity.requestContext.requestChargeTracker, /*isSuccessful */ false, + /* shouldRetryOnSecondary: */ true, /* response: */ null)); + } - // To accommodate for store latency, where an LSN may be acked by not persisted in the store, we compare the quorum acked LSN and store LSN. - // In case of sync replication, the store LSN will follow the quorum committed LSN - // In case of async replication (if enabled for bounded staleness), the store LSN can be ahead of the quorum committed LSN if the primary is able write to faster than secondary acks. - // We pick higher of the 2 LSN and wait for the other to reach that LSN. - if (storeResult.lsn != storeResult.quorumAckedLSN) { - logger.warn("Store LSN {} and quorum acked LSN {} don't match", storeResult.lsn, storeResult.quorumAckedLSN); - long higherLsn = storeResult.lsn > storeResult.quorumAckedLSN ? storeResult.lsn : storeResult.quorumAckedLSN; - - Single waitForLsnRequestObs = BarrierRequestHelper.createAsync(entity, this.authorizationTokenProvider, higherLsn, null); - return waitForLsnRequestObs.flatMap( - waitForLsnRequest -> { - Single primaryWaitForLsnResponseObs = this.waitForPrimaryLsnAsync(waitForLsnRequest, higherLsn, readQuorum); - return primaryWaitForLsnResponseObs.map( - primaryWaitForLsnResponse -> { - if (primaryWaitForLsnResponse == PrimaryReadOutcome.QuorumNotMet) { - return new ReadPrimaryResult( - entity.requestContext.requestChargeTracker, /*(isSuccessful: */ false, /* shouldRetryOnSecondary: */ false, /* response: */null); - } else if (primaryWaitForLsnResponse == PrimaryReadOutcome.QuorumInconclusive) { - return new ReadPrimaryResult( - entity.requestContext.requestChargeTracker, /* isSuccessful: */ false, /* shouldRetryOnSecondary: */ - true, /* response: */ null); - } + // To accommodate for store latency, where an LSN may be acked by not persisted in the store, we compare the quorum acked LSN and store LSN. + // In case of sync replication, the store LSN will follow the quorum committed LSN + // In case of async replication (if enabled for bounded staleness), the store LSN can be ahead of the quorum committed LSN if the primary is able write to faster than secondary acks. + // We pick higher of the 2 LSN and wait for the other to reach that LSN. + if (storeResult.lsn != storeResult.quorumAckedLSN) { + logger.warn("Store LSN {} and quorum acked LSN {} don't match", storeResult.lsn, storeResult.quorumAckedLSN); + long higherLsn = storeResult.lsn > storeResult.quorumAckedLSN ? storeResult.lsn : storeResult.quorumAckedLSN; + + Mono waitForLsnRequestObs = BarrierRequestHelper.createAsync(entity, this.authorizationTokenProvider, higherLsn, null); + return waitForLsnRequestObs.flatMap( + waitForLsnRequest -> { + Mono primaryWaitForLsnResponseObs = this.waitForPrimaryLsnAsync(waitForLsnRequest, higherLsn, readQuorum); + return primaryWaitForLsnResponseObs.map( + primaryWaitForLsnResponse -> { + if (primaryWaitForLsnResponse == PrimaryReadOutcome.QuorumNotMet) { + return new ReadPrimaryResult( + entity.requestContext.requestChargeTracker, /*(isSuccessful: */ false, /* shouldRetryOnSecondary: */ false, /* response: */null); + } else if (primaryWaitForLsnResponse == PrimaryReadOutcome.QuorumInconclusive) { + return new ReadPrimaryResult( + entity.requestContext.requestChargeTracker, /* isSuccessful: */ false, /* shouldRetryOnSecondary: */ + true, /* response: */ null); + } - return new ReadPrimaryResult( - entity.requestContext.requestChargeTracker, /* isSuccessful: */ true, /* shouldRetryOnSecondary: */ false, /*response: */ storeResult); - } - ); + return new ReadPrimaryResult( + entity.requestContext.requestChargeTracker, /* isSuccessful: */ true, /* shouldRetryOnSecondary: */ false, /*response: */ storeResult); } - ); - } - - return Single.just(new ReadPrimaryResult( - /* requestChargeTracker: */ entity.requestContext.requestChargeTracker, /* isSuccessful: */ true, /* shouldRetryOnSecondary:*/ false, - /*response: */ storeResult)); + ); + } + ); } + + return Mono.just(new ReadPrimaryResult( + /* requestChargeTracker: */ entity.requestContext.requestChargeTracker, /* isSuccessful: */ true, /* shouldRetryOnSecondary:*/ false, + /*response: */ storeResult)); + } ); } - private Single waitForPrimaryLsnAsync( - RxDocumentServiceRequest barrierRequest, - long lsnToWaitFor, - int readQuorum) { + private Mono waitForPrimaryLsnAsync( + RxDocumentServiceRequest barrierRequest, + long lsnToWaitFor, + int readQuorum) { - return Observable.defer(() -> { + return Flux.defer(() -> { if (barrierRequest.requestContext.timeoutHelper.isElapsed()) { - return Observable.error(new GoneException()); + return Flux.error(new GoneException()); } // We would have already refreshed address before reaching here. Avoid performing here. barrierRequest.requestContext.forceRefreshAddressCache = false; - Single storeResultObs = this.storeReader.readPrimaryAsync(barrierRequest, true /*required valid LSN*/, false); + Mono storeResultObs = this.storeReader.readPrimaryAsync(barrierRequest, true /*required valid LSN*/, false); - return storeResultObs.toObservable().flatMap( - storeResult -> { - if (!storeResult.isValid) { - try { - return Observable.error(storeResult.getException()); - } catch (InternalServerErrorException e) { - return Observable.error(e); - } - } - - if (storeResult.currentReplicaSetSize > readQuorum) { - logger.warn( - "Unexpected response. Replica Set size is {} which is greater than min value {}", storeResult.currentReplicaSetSize, readQuorum); - return Observable.just(PrimaryReadOutcome.QuorumInconclusive); + return storeResultObs.flux().flatMap( + storeResult -> { + if (!storeResult.isValid) { + try { + return Flux.error(storeResult.getException()); + } catch (InternalServerErrorException e) { + return Flux.error(e); } + } - // Java this will move to the repeat logic - if (storeResult.lsn < lsnToWaitFor || storeResult.quorumAckedLSN < lsnToWaitFor) { - logger.warn( - "Store LSN {} or quorum acked LSN {} are lower than expected LSN {}", storeResult.lsn, storeResult.quorumAckedLSN, lsnToWaitFor); + if (storeResult.currentReplicaSetSize > readQuorum) { + logger.warn( + "Unexpected response. Replica Set size is {} which is greater than min value {}", storeResult.currentReplicaSetSize, readQuorum); + return Flux.just(PrimaryReadOutcome.QuorumInconclusive); + } - return Observable.timer(delayBetweenReadBarrierCallsInMs, TimeUnit.MILLISECONDS).flatMap(dummy -> Observable.empty()); - } + // Java this will move to the repeat logic + if (storeResult.lsn < lsnToWaitFor || storeResult.quorumAckedLSN < lsnToWaitFor) { + logger.warn( + "Store LSN {} or quorum acked LSN {} are lower than expected LSN {}", storeResult.lsn, storeResult.quorumAckedLSN, lsnToWaitFor); - return Observable.just(PrimaryReadOutcome.QuorumMet); + return Flux.just(0L).delayElements(Duration.ofMillis(delayBetweenReadBarrierCallsInMs)).flatMap(dummy -> Flux.empty()); } + + return Flux.just(PrimaryReadOutcome.QuorumMet); + } ); }).repeat(maxNumberOfPrimaryReadRetries) // Loop for store and quorum LSN to match - .defaultIfEmpty(PrimaryReadOutcome.QuorumNotMet) - .first() - .toSingle(); + .defaultIfEmpty(PrimaryReadOutcome.QuorumNotMet) + .take(1) + .single(); } - private Single waitForReadBarrierAsync( - RxDocumentServiceRequest barrierRequest, - boolean allowPrimary, - final int readQuorum, - final long readBarrierLsn, - final long targetGlobalCommittedLSN, - ReadMode readMode) { + private Mono waitForReadBarrierAsync( + RxDocumentServiceRequest barrierRequest, + boolean allowPrimary, + final int readQuorum, + final long readBarrierLsn, + final long targetGlobalCommittedLSN, + ReadMode readMode) { AtomicInteger readBarrierRetryCount = new AtomicInteger(maxNumberOfReadBarrierReadRetries); AtomicInteger readBarrierRetryCountMultiRegion = new AtomicInteger(maxBarrierRetriesForMultiRegion); AtomicLong maxGlobalCommittedLsn = new AtomicLong(0); - return Observable.defer(() -> { + return Flux.defer(() -> { if (barrierRequest.requestContext.timeoutHelper.isElapsed()) { - return Observable.error(new GoneException()); + return Flux.error(new GoneException()); } - Single> responsesObs = this.storeReader.readMultipleReplicaAsync( - barrierRequest, allowPrimary, readQuorum, - true /*required valid LSN*/, false /*useSessionToken*/, readMode, false /*checkMinLSN*/, true /*forceReadAll*/); + Mono> responsesObs = this.storeReader.readMultipleReplicaAsync( + barrierRequest, allowPrimary, readQuorum, + true /*required valid LSN*/, false /*useSessionToken*/, readMode, false /*checkMinLSN*/, true /*forceReadAll*/); - return responsesObs.toObservable().flatMap( - responses -> { + return responsesObs.flux().flatMap( + responses -> { - long maxGlobalCommittedLsnInResponses = responses.size() > 0 ? responses.stream() - .mapToLong(response -> response.globalCommittedLSN).max().getAsLong() : 0; + long maxGlobalCommittedLsnInResponses = responses.size() > 0 ? responses.stream() + .mapToLong(response -> response.globalCommittedLSN).max().getAsLong() : 0; - if ((responses.stream().filter(response -> response.lsn >= readBarrierLsn).count() >= readQuorum) && - (!(targetGlobalCommittedLSN > 0) || maxGlobalCommittedLsnInResponses >= targetGlobalCommittedLSN)) { - return Observable.just(true); - } + if ((responses.stream().filter(response -> response.lsn >= readBarrierLsn).count() >= readQuorum) && + (!(targetGlobalCommittedLSN > 0) || maxGlobalCommittedLsnInResponses >= targetGlobalCommittedLSN)) { + return Flux.just(true); + } - maxGlobalCommittedLsn.set(maxGlobalCommittedLsn.get() > maxGlobalCommittedLsnInResponses ? - maxGlobalCommittedLsn.get() : maxGlobalCommittedLsnInResponses); + maxGlobalCommittedLsn.set(maxGlobalCommittedLsn.get() > maxGlobalCommittedLsnInResponses ? + maxGlobalCommittedLsn.get() : maxGlobalCommittedLsnInResponses); - //only refresh on first barrier call, set to false for subsequent attempts. - barrierRequest.requestContext.forceRefreshAddressCache = false; + //only refresh on first barrier call, set to false for subsequent attempts. + barrierRequest.requestContext.forceRefreshAddressCache = false; - if (readBarrierRetryCount.decrementAndGet() == 0) { - logger.debug("QuorumReader: waitForReadBarrierAsync - Last barrier for single-region requests. Responses: {}", - JavaStreamUtils.toString(responses, "; ")); + if (readBarrierRetryCount.decrementAndGet() == 0) { + logger.debug("QuorumReader: waitForReadBarrierAsync - Last barrier for single-region requests. Responses: {}", + JavaStreamUtils.toString(responses, "; ")); - // retries exhausted - return Observable.just(false); + // retries exhausted + return Flux.just(false); - } else { - // delay - //await Task.Delay(QuorumReader.delayBetweenReadBarrierCallsInMs); - return Observable.empty(); + } else { + // delay + //await Task.Delay(QuorumReader.delayBetweenReadBarrierCallsInMs); + return Flux.empty(); - } } + } ); - }).repeatWhen(obs -> obs.flatMap(aVoid -> { - return Observable.timer(delayBetweenReadBarrierCallsInMs, TimeUnit.MILLISECONDS); - })) + }).repeatWhen(obs -> obs.flatMap(aVoid -> Flux.just(0L).delayElements(Duration.ofMillis(delayBetweenReadBarrierCallsInMs)))) .take(1) // Retry loop - .flatMap(barrierRequestSucceeded -> - Observable.defer(() -> { - - if (barrierRequestSucceeded) { - return Observable.just(true); - } - - // we will go into global strong read barrier mode for global strong requests after regular barrier calls have been exhausted. - if (targetGlobalCommittedLSN > 0) { - return Observable.defer(() -> { - - if (barrierRequest.requestContext.timeoutHelper.isElapsed()) { - return Observable.error(new GoneException()); - } - - Single> responsesObs = this.storeReader.readMultipleReplicaAsync( - barrierRequest, allowPrimary, readQuorum, - true /*required valid LSN*/, false /*useSessionToken*/, readMode, false /*checkMinLSN*/, true /*forceReadAll*/); - - return responsesObs.toObservable().flatMap( - responses -> { - long maxGlobalCommittedLsnInResponses = responses.size() > 0 ? responses.stream() - .mapToLong(response -> response.globalCommittedLSN).max().getAsLong() : 0; - - if ((responses.stream().filter(response -> response.lsn >= readBarrierLsn).count() >= readQuorum) && - maxGlobalCommittedLsnInResponses >= targetGlobalCommittedLSN) { - return Observable.just(true); - } - - maxGlobalCommittedLsn.set(maxGlobalCommittedLsn.get() > maxGlobalCommittedLsnInResponses ? - maxGlobalCommittedLsn.get() : maxGlobalCommittedLsnInResponses); - - //trace on last retry. - if (readBarrierRetryCountMultiRegion.getAndDecrement() == 0) { - logger.debug("QuorumReader: waitForReadBarrierAsync - Last barrier for mult-region strong requests. Responses: {}", - JavaStreamUtils.toString(responses, "; ")); - return Observable.just(false); - } else { - return Observable.empty(); - } - } - ); - - }).repeatWhen(obs -> obs.flatMap(aVoid -> { - - if ((maxBarrierRetriesForMultiRegion - readBarrierRetryCountMultiRegion.get()) > maxShortBarrierRetriesForMultiRegion) { - return Observable.timer(barrierRetryIntervalInMsForMultiRegion, TimeUnit.MILLISECONDS); - } else { - return Observable.timer(shortBarrierRetryIntervalInMsForMultiRegion, TimeUnit.MILLISECONDS); - } - - }) - // stop predicate, simulating while loop + .flatMap(barrierRequestSucceeded -> + Flux.defer(() -> { + + if (barrierRequestSucceeded) { + return Flux.just(true); + } + + // we will go into global strong read barrier mode for global strong requests after regular barrier calls have been exhausted. + if (targetGlobalCommittedLSN > 0) { + return Flux.defer(() -> { + + if (barrierRequest.requestContext.timeoutHelper.isElapsed()) { + return Flux.error(new GoneException()); + } + + Mono> responsesObs = this.storeReader.readMultipleReplicaAsync( + barrierRequest, allowPrimary, readQuorum, + true /*required valid LSN*/, false /*useSessionToken*/, readMode, false /*checkMinLSN*/, true /*forceReadAll*/); + + return responsesObs.flux().flatMap( + responses -> { + long maxGlobalCommittedLsnInResponses = responses.size() > 0 ? responses.stream() + .mapToLong(response -> response.globalCommittedLSN).max().getAsLong() : 0; + + if ((responses.stream().filter(response -> response.lsn >= readBarrierLsn).count() >= readQuorum) && + maxGlobalCommittedLsnInResponses >= targetGlobalCommittedLSN) { + return Flux.just(true); + } + + maxGlobalCommittedLsn.set(maxGlobalCommittedLsn.get() > maxGlobalCommittedLsnInResponses ? + maxGlobalCommittedLsn.get() : maxGlobalCommittedLsnInResponses); + + //trace on last retry. + if (readBarrierRetryCountMultiRegion.getAndDecrement() == 0) { + logger.debug("QuorumReader: waitForReadBarrierAsync - Last barrier for mult-region strong requests. Responses: {}", + JavaStreamUtils.toString(responses, "; ")); + return Flux.just(false); + } else { + return Flux.empty(); + } + } + ); + + }).repeatWhen(obs -> obs.flatMap(aVoid -> { + + if ((maxBarrierRetriesForMultiRegion - readBarrierRetryCountMultiRegion.get()) > maxShortBarrierRetriesForMultiRegion) { + return Flux.just(0L).delayElements(Duration.ofMillis(barrierRetryIntervalInMsForMultiRegion)); + } else { + return Flux.just(0L).delayElements(Duration.ofMillis(shortBarrierRetryIntervalInMsForMultiRegion)); + } + + }) + // stop predicate, simulating while loop ).take(1); - } - - return Observable.empty(); - })). - concatWith( - Observable.defer(() -> { - logger.debug("QuorumReader: waitForReadBarrierAsync - TargetGlobalCommittedLsn: {}, MaxGlobalCommittedLsn: {}.", targetGlobalCommittedLSN, maxGlobalCommittedLsn); - return Observable.just(false); - }) - ).take(1).toSingle(); + } + + return Flux.empty(); + })). + concatWith( + Flux.defer(() -> { + logger.debug("QuorumReader: waitForReadBarrierAsync - TargetGlobalCommittedLsn: {}, MaxGlobalCommittedLsn: {}.", targetGlobalCommittedLSN, maxGlobalCommittedLsn); + return Flux.just(false); + }) + ).take(1).single(); } private boolean isQuorumMet( - List readResponses, - int readQuorum, - boolean isPrimaryIncluded, - boolean isGlobalStrongRead, - ValueHolder readLsn, - ValueHolder globalCommittedLSN, - ValueHolder selectedResponse) { + List readResponses, + int readQuorum, + boolean isPrimaryIncluded, + boolean isGlobalStrongRead, + ValueHolder readLsn, + ValueHolder globalCommittedLSN, + ValueHolder selectedResponse) { long maxLsn = 0; long minLsn = Long.MAX_VALUE; int replicaCountMaxLsn = 0; @@ -688,13 +686,13 @@ private boolean isQuorumMet( selectedResponse.v = validReadResponses.stream().filter(s -> s.lsn == maxLsnFinal).findFirst().get(); readLsn.v = selectedResponse.v.itemLSN == -1 ? - maxLsn : Math.min(selectedResponse.v.itemLSN, maxLsn); + maxLsn : Math.min(selectedResponse.v.itemLSN, maxLsn); globalCommittedLSN.v = checkForGlobalStrong ? readLsn.v : -1l; long maxGlobalCommittedLSN = validReadResponses.stream().mapToLong(res -> res.globalCommittedLSN).max().getAsLong(); logger.debug("QuorumReader: MaxLSN {} ReplicaCountMaxLSN {} bCheckGlobalStrong {} MaxGlobalCommittedLSN {} NumberOfReadRegions {} SelectedResponseItemLSN {}", - maxLsn, replicaCountMaxLsn, checkForGlobalStrong, maxGlobalCommittedLSN, numberOfReadRegions, selectedResponse.v.itemLSN); + maxLsn, replicaCountMaxLsn, checkForGlobalStrong, maxGlobalCommittedLSN, numberOfReadRegions, selectedResponse.v.itemLSN); // quorum is met if one of the following conditions are satisfied: // 1. readLsn is greater than zero @@ -710,13 +708,13 @@ private boolean isQuorumMet( boolean isQuorumMet = false; if ((readLsn.v > 0 && replicaCountMaxLsn >= readQuorum) && - (!checkForGlobalStrong || maxGlobalCommittedLSN >= maxLsn)) { + (!checkForGlobalStrong || maxGlobalCommittedLSN >= maxLsn)) { isQuorumMet = true; } if (!isQuorumMet && validResponsesCount >= readQuorum && selectedResponse.v.itemLSN != -1 && - (minLsn != Long.MAX_VALUE && selectedResponse.v.itemLSN <= minLsn) && - (!checkForGlobalStrong || (selectedResponse.v.itemLSN <= maxGlobalCommittedLSN))) { + (minLsn != Long.MAX_VALUE && selectedResponse.v.itemLSN <= minLsn) && + (!checkForGlobalStrong || (selectedResponse.v.itemLSN <= maxGlobalCommittedLSN))) { isQuorumMet = true; } @@ -752,12 +750,12 @@ public StoreResponse getResponse() throws CosmosClientException { private class ReadQuorumResult extends ReadResult { public ReadQuorumResult( - RequestChargeTracker requestChargeTracker, - ReadQuorumResultKind QuorumResult, - long selectedLsn, - long globalCommittedSelectedLsn, - StoreResult selectedResponse, - List storeResponses) { + RequestChargeTracker requestChargeTracker, + ReadQuorumResultKind QuorumResult, + long selectedLsn, + long globalCommittedSelectedLsn, + StoreResult selectedResponse, + List storeResponses) { super(requestChargeTracker, selectedResponse); this.quorumResult = QuorumResult; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java index c60645dce0707..f0ffa9683344c 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java @@ -37,11 +37,11 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; -import rx.functions.Func1; -import rx.functions.Func2; +import reactor.core.publisher.Mono; import java.time.Duration; +import java.util.function.BiFunction; +import java.util.function.Function; /** * ReplicatedResourceClient uses the ConsistencyReader to make requests to @@ -109,9 +109,9 @@ public static boolean isGlobalStrongEnabled() { return true; } - public Single invokeAsync(RxDocumentServiceRequest request, - Func1> prepareRequestAsyncDelegate) { - Func2, RxDocumentServiceRequest, Single> mainFuncDelegate = ( + public Mono invokeAsync(RxDocumentServiceRequest request, + Function> prepareRequestAsyncDelegate) { + BiFunction, RxDocumentServiceRequest, Mono> mainFuncDelegate = ( Quadruple forceRefreshAndTimeout, RxDocumentServiceRequest documentServiceRequest) -> { documentServiceRequest.getHeaders().put(HttpConstants.HttpHeaders.CLIENT_RETRY_ATTEMPT_COUNT, @@ -122,19 +122,17 @@ public Single invokeAsync(RxDocumentServiceRequest request, forceRefreshAndTimeout.getValue1(), forceRefreshAndTimeout.getValue0()); }; - Func1, Single> funcDelegate = ( + Function, Mono> funcDelegate = ( Quadruple forceRefreshAndTimeout) -> { if (prepareRequestAsyncDelegate != null) { - return prepareRequestAsyncDelegate.call(request).flatMap(responseReq -> { - return mainFuncDelegate.call(forceRefreshAndTimeout, responseReq); - }); + return prepareRequestAsyncDelegate.apply(request).flatMap(responseReq -> mainFuncDelegate.apply(forceRefreshAndTimeout, responseReq)); } else { - return mainFuncDelegate.call(forceRefreshAndTimeout, request); + return mainFuncDelegate.apply(forceRefreshAndTimeout, request); } }; - Func1, Single> inBackoffFuncDelegate = null; + Function, Mono> inBackoffFuncDelegate = null; // we will enable fallback to other regions if the following conditions are met: // 1. request is a read operation AND @@ -149,17 +147,15 @@ public Single invokeAsync(RxDocumentServiceRequest request, RxDocumentServiceRequest readRequestClone = freshRequest.clone(); if (prepareRequestAsyncDelegate != null) { - return prepareRequestAsyncDelegate.call(readRequestClone).flatMap(responseReq -> { - logger.trace(String.format("Executing inBackoffAlternateCallbackMethod on readRegionIndex {}", - forceRefreshAndTimeout.getValue3())); + return prepareRequestAsyncDelegate.apply(readRequestClone).flatMap(responseReq -> { + logger.trace("Executing inBackoffAlternateCallbackMethod on readRegionIndex {}", forceRefreshAndTimeout.getValue3()); responseReq.requestContext.RouteToLocation(forceRefreshAndTimeout.getValue3(), true); return invokeAsync(responseReq, new TimeoutHelper(forceRefreshAndTimeout.getValue2()), forceRefreshAndTimeout.getValue1(), forceRefreshAndTimeout.getValue0()); }); } else { - logger.trace(String.format("Executing inBackoffAlternateCallbackMethod on readRegionIndex {}", - forceRefreshAndTimeout.getValue3())); + logger.trace("Executing inBackoffAlternateCallbackMethod on readRegionIndex {}", forceRefreshAndTimeout.getValue3()); readRequestClone.requestContext.RouteToLocation(forceRefreshAndTimeout.getValue3(), true); return invokeAsync(readRequestClone, new TimeoutHelper(forceRefreshAndTimeout.getValue2()), forceRefreshAndTimeout.getValue1(), @@ -178,7 +174,7 @@ public Single invokeAsync(RxDocumentServiceRequest request, ReplicatedResourceClient.MIN_BACKOFF_FOR_FAILLING_BACK_TO_OTHER_REGIONS_FOR_READ_REQUESTS_IN_SECONDS)); } - private Single invokeAsync(RxDocumentServiceRequest request, TimeoutHelper timeout, + private Mono invokeAsync(RxDocumentServiceRequest request, TimeoutHelper timeout, boolean isInRetry, boolean forceRefresh) { if (request.getOperationType().equals(OperationType.ExecuteJavaScript)) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java index 0d78f4e368375..9277ee71b2370 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -56,8 +56,8 @@ public RequestEntityTooLargeException(String msg, String resourceAddress) { super(msg, null, null, HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE, resourceAddress); } - public RequestEntityTooLargeException(String message, HttpResponseHeaders headers, String requestUri) { - this(message, null, headers, requestUri); + public RequestEntityTooLargeException(String message, HttpHeaders headers, String requestUriString) { + this(message, null, headers, requestUriString); } public RequestEntityTooLargeException(Exception innerException) { @@ -66,12 +66,12 @@ public RequestEntityTooLargeException(Exception innerException) { public RequestEntityTooLargeException(String message, Exception innerException, - HttpResponseHeaders headers, - String requestUri) { + HttpHeaders headers, + String requestUriString) { super(String.format(RMResources.RequestEntityTooLarge, message), innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE, - requestUri); + requestUriString); } } \ No newline at end of file diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java index d769b45ce9801..a16762c13f4bf 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.util.Map; @@ -46,30 +46,30 @@ public RequestRateTooLargeException(Error error, long lsn, String partitionKeyRa } public RequestRateTooLargeException(String message, URI requestUri) { - this(message, (Exception) null, (HttpResponseHeaders) null, requestUri); + this(message, null, null, requestUri); } public RequestRateTooLargeException(String message, Exception innerException, URI requestUri) { - this(message, innerException, (HttpResponseHeaders) null, requestUri); + this(message, innerException, null, requestUri); } public RequestRateTooLargeException(Exception innerException) { - this(RMResources.TooManyRequests, innerException, (HttpResponseHeaders) null, null); + this(RMResources.TooManyRequests, innerException, null, null); } - public RequestRateTooLargeException(String message, HttpResponseHeaders headers, URI requestUri) { + public RequestRateTooLargeException(String message, HttpHeaders headers, URI requestUri) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.TOO_MANY_REQUESTS, requestUri != null ? requestUri.toString() : null); } - public RequestRateTooLargeException(String message, HttpResponseHeaders headers, String requestUri) { - super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.TOO_MANY_REQUESTS, requestUri); + public RequestRateTooLargeException(String message, HttpHeaders headers, String requestUriString) { + super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.TOO_MANY_REQUESTS, requestUriString); } public RequestRateTooLargeException(String message, Exception innerException, - HttpResponseHeaders headers, + HttpHeaders headers, URI requestUri) { super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.TOO_MANY_REQUESTS, requestUri != null ? requestUri.toString() : null); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResponseUtils.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResponseUtils.java index e2a30a0dbec1c..4383194fd9e74 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResponseUtils.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResponseUtils.java @@ -23,30 +23,23 @@ package com.azure.data.cosmos.directconnectivity; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; import io.netty.buffer.ByteBuf; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; +import io.netty.handler.codec.http.HttpMethod; +import org.apache.commons.lang3.StringUtils; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.nio.charset.StandardCharsets; class ResponseUtils { private final static int INITIAL_RESPONSE_BUFFER_SIZE = 1024; - private final static Logger logger = LoggerFactory.getLogger(ResponseUtils.class); - public static Observable toString(Observable contentObservable) { + public static Mono toString(Flux contentObservable) { return contentObservable .reduce( new ByteArrayOutputStream(INITIAL_RESPONSE_BUFFER_SIZE), @@ -58,67 +51,30 @@ public static Observable toString(Observable contentObservable) throw new RuntimeException(e); } }) - .map(out -> { - return new String(out.toByteArray(), StandardCharsets.UTF_8); - }); + .map(out -> new String(out.toByteArray(), StandardCharsets.UTF_8)); } - public static Single toStoreResponse(HttpClientResponse clientResponse) { + static Mono toStoreResponse(HttpResponse httpClientResponse, HttpRequest httpRequest) { - HttpResponseHeaders httpResponseHeaders = clientResponse.getHeaders(); - HttpResponseStatus httpResponseStatus = clientResponse.getStatus(); + HttpHeaders httpResponseHeaders = httpClientResponse.headers(); - Observable contentObservable; + Mono contentObservable; - if (clientResponse.getContent() == null) { + if (httpRequest.httpMethod() == HttpMethod.DELETE) { // for delete we don't expect any body - contentObservable = Observable.just(null); + contentObservable = Mono.just(StringUtils.EMPTY); } else { - // transforms the observable to Observable - contentObservable = toString(clientResponse.getContent()); + contentObservable = toString(httpClientResponse.body()); } - Observable storeResponseObservable = contentObservable - .flatMap(content -> { - try { - // transforms to Observable - StoreResponse rsp = new StoreResponse(httpResponseStatus.code(), HttpUtils.unescape(httpResponseHeaders.entries()), content); - return Observable.just(rsp); - } catch (Exception e) { - return Observable.error(e); - } - }); - - return storeResponseObservable.toSingle(); - } - - private static void validateOrThrow(RxDocumentServiceRequest request, HttpResponseStatus status, HttpResponseHeaders headers, String body, - InputStream inputStream) throws CosmosClientException { - - int statusCode = status.code(); - - if (statusCode >= HttpConstants.StatusCodes.MINIMUM_STATUSCODE_AS_ERROR_GATEWAY) { - if (body == null && inputStream != null) { - try { - body = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - } catch (IOException e) { - logger.error("Failed to get content from the http response", e); - throw new IllegalStateException("Failed to get content from the http response", e); - } finally { - IOUtils.closeQuietly(inputStream); - } + return contentObservable.flatMap(content -> { + try { + // transforms to Mono + StoreResponse rsp = new StoreResponse(httpClientResponse.statusCode(), HttpUtils.unescape(httpResponseHeaders.toMap().entrySet()), content); + return Mono.just(rsp); + } catch (Exception e) { + return Mono.error(e); } - - String statusCodeString = status.reasonPhrase() != null - ? status.reasonPhrase().replace(" ", "") - : ""; - Error error = null; - error = (body != null) ? new Error(body) : new Error(); - error = new Error(statusCodeString, - String.format("%s, StatusCode: %s", error.getMessage(), statusCodeString), - error.getPartitionedQueryExecutionInfo()); - - throw new CosmosClientException(statusCode, error, HttpUtils.asMap(headers)); - } + }); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java index 1d116fab21aa9..4de3fdf6a71f3 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.util.Map; @@ -41,26 +41,26 @@ public RetryWithException(Error error, long lsn, String partitionKeyRangeId, Map } public RetryWithException(String message, URI requestUri) { - this(message, (Exception) null, (HttpResponseHeaders) null, requestUri); + this(message, null, null, requestUri); } public RetryWithException(String message, Exception innerException, URI requestUri) { - this(message, innerException, (HttpResponseHeaders) null, requestUri); + this(message, innerException, null, requestUri); } - public RetryWithException(String message, HttpResponseHeaders headers, URI requestUri) { + public RetryWithException(String message, HttpHeaders headers, URI requestUri) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.RETRY_WITH, requestUri != null ? requestUri.toString() : null); } - public RetryWithException(String message, HttpResponseHeaders headers, String requestUri) { - super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.RETRY_WITH, requestUri); + public RetryWithException(String message, HttpHeaders headers, String requestUriString) { + super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.RETRY_WITH, requestUriString); } public RetryWithException(String message, Exception innerException, - HttpResponseHeaders headers, + HttpHeaders headers, URI requestUri) { super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.RETRY_WITH, requestUri != null ? requestUri.toString() : null); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java index 7c8500acb5a7a..666432c1ed545 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java @@ -24,7 +24,6 @@ package com.azure.data.cosmos.directconnectivity; -import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdEndpoint; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdMetrics; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdObjectMapper; @@ -41,8 +40,8 @@ import io.netty.handler.ssl.SslContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; -import rx.SingleEmitter; +import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; import java.io.IOException; import java.net.URI; @@ -50,13 +49,12 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdReporter.reportIssueUnless; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; @JsonSerialize(using = RntbdTransportClient.JsonSerializer.class) -public final class RntbdTransportClient extends TransportClient implements AutoCloseable { +public final class RntbdTransportClient extends TransportClient { // region Fields @@ -106,9 +104,8 @@ public void close() { } @Override - public Single invokeStoreAsync( - final URI physicalAddress, final ResourceOperation unused, final RxDocumentServiceRequest request - ) { + public Mono invokeStoreAsync(final URI physicalAddress, final RxDocumentServiceRequest request) { + checkNotNull(physicalAddress, "physicalAddress"); checkNotNull(request, "request"); this.throwIfClosed(); @@ -125,23 +122,17 @@ public Single invokeStoreAsync( final RntbdRequestRecord requestRecord = endpoint.request(requestArgs); - return Single.fromEmitter((SingleEmitter emitter) -> { - - requestRecord.whenComplete((response, error) -> { - - requestArgs.traceOperation(logger, null, "emitSingle", response, error); - this.metrics.incrementResponseCount(); - - if (error == null) { - emitter.onSuccess(response); - } else { - reportIssueUnless(error instanceof CosmosClientException, logger, requestRecord, "", error); - this.metrics.incrementErrorResponseCount(); - emitter.onError(error); - } + requestRecord.whenComplete((response, error) -> { + this.metrics.incrementResponseCount(); + if (error != null) { + this.metrics.incrementErrorResponseCount(); + } + }); - requestArgs.traceOperation(logger, null, "emitSingleComplete"); - }); + return Mono.fromFuture(requestRecord).doFinally(signal -> { + if (signal == SignalType.CANCEL) { + requestRecord.cancel(false); + } }); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java index 34c25b37f8bad..e39b292c72a89 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java @@ -33,8 +33,8 @@ import com.azure.data.cosmos.internal.RxStoreModel; import com.azure.data.cosmos.internal.Strings; import org.apache.commons.lang3.EnumUtils; -import rx.Observable; -import rx.Single; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; public class ServerStoreModel implements RxStoreModel { private final StoreClient storeClient; @@ -43,7 +43,7 @@ public ServerStoreModel(StoreClient storeClient) { this.storeClient = storeClient; } - public Observable processMessage(RxDocumentServiceRequest request) { + public Flux processMessage(RxDocumentServiceRequest request) { String requestConsistencyLevelHeaderValue = request.getHeaders().get(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL); request.requestContext.originalRequestConsistencyLevel = null; @@ -52,7 +52,7 @@ public Observable processMessage(RxDocumentServiceReq ConsistencyLevel requestConsistencyLevel; if ((requestConsistencyLevel = EnumUtils.getEnum(ConsistencyLevel.class, Strings.fromCamelCaseToUpperCase(requestConsistencyLevelHeaderValue))) == null) { - return Observable.error(new BadRequestException( + return Flux.error(new BadRequestException( String.format( RMResources.InvalidHeaderValue, requestConsistencyLevelHeaderValue, @@ -66,7 +66,7 @@ public Observable processMessage(RxDocumentServiceReq request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, ConsistencyLevel.STRONG.toString()); } - Single response = this.storeClient.processMessageAsync(request); - return response.toObservable(); + Mono response = this.storeClient.processMessageAsync(request); + return response.flux(); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java index d6253cd27e46a..18bce5b766c6c 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.util.Map; @@ -45,14 +45,14 @@ public ServiceUnavailableException(Error error, long lsn, String partitionKeyRan } public ServiceUnavailableException(String message) { - this(message, (Exception) null, (HttpResponseHeaders) null, null); + this(message, null, null, null); } - public ServiceUnavailableException(String message, HttpResponseHeaders headers, String requestUri) { - this(message, null, headers, requestUri); + public ServiceUnavailableException(String message, HttpHeaders headers, String requestUriString) { + this(message, null, headers, requestUriString); } - public ServiceUnavailableException(String message, HttpResponseHeaders headers, URI requestUri) { + public ServiceUnavailableException(String message, HttpHeaders headers, URI requestUri) { this(message, headers, requestUri != null ? requestUri.toString() : null); } @@ -62,12 +62,12 @@ public ServiceUnavailableException(Exception innerException) { public ServiceUnavailableException(String message, Exception innerException, - HttpResponseHeaders headers, - String requestUri) { + HttpHeaders headers, + String requestUriString) { super(String.format("%s: %s", RMResources.ServiceUnavailable, message), innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, - requestUri != null ? requestUri.toString() : null); + requestUriString); } } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java index 31760f1dbfd67..d782ccdc3aa0c 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java @@ -45,12 +45,12 @@ import org.apache.commons.lang3.math.NumberUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; -import rx.functions.Func0; -import rx.functions.Func1; +import reactor.core.publisher.Mono; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.Callable; +import java.util.function.Function; /** * Instantiated to issue direct connectivity requests to the backend on: @@ -89,16 +89,21 @@ public StoreClient( } @Override - public Single processMessageAsync(RxDocumentServiceRequest request, IRetryPolicy retryPolicy, Func1> prepareRequestAsyncDelegate) { + public Mono processMessageAsync(RxDocumentServiceRequest request, IRetryPolicy retryPolicy, Function> prepareRequestAsyncDelegate) { if (request == null) { throw new NullPointerException("request"); } - Func0> storeResponseDelegate = () -> this.replicatedResourceClient.invokeAsync(request, prepareRequestAsyncDelegate); + Callable> storeResponseDelegate = () -> this.replicatedResourceClient.invokeAsync(request, prepareRequestAsyncDelegate); - Single storeResponse = retryPolicy != null - ? BackoffRetryUtility.executeRetry(storeResponseDelegate, retryPolicy) - : storeResponseDelegate.call(); + Mono storeResponse; + try { + storeResponse = retryPolicy != null + ? BackoffRetryUtility.executeRetry(storeResponseDelegate, retryPolicy) + : storeResponseDelegate.call(); + } catch (Exception e) { + return Mono.error(e); + } storeResponse = storeResponse.doOnError(e -> { try { @@ -120,9 +125,9 @@ public Single processMessageAsync(RxDocumentServiceRe return storeResponse.flatMap(sr -> { try { - return Single.just(this.completeResponse(sr, request)); + return Mono.just(this.completeResponse(sr, request)); } catch (Exception e) { - return Single.error(e); + return Mono.error(e); } }); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java index eb35800cf190c..14396dd22d3d0 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java @@ -45,10 +45,10 @@ import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; -import rx.exceptions.CompositeException; -import rx.schedulers.Schedulers; +import reactor.core.Exceptions; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import java.net.URI; import java.util.ArrayList; @@ -76,7 +76,7 @@ public StoreReader( this.sessionContainer = sessionContainer; } - public Single> readMultipleReplicaAsync( + public Mono> readMultipleReplicaAsync( RxDocumentServiceRequest entity, boolean includePrimary, int replicaCountToRead, @@ -98,7 +98,7 @@ public Single> readMultipleReplicaAsync( * @param forceReadAll reads from all available replicas to gather result from readsToRead number of replicas * @return ReadReplicaResult which indicates the LSN and whether Quorum was Met / Not Met etc */ - public Single> readMultipleReplicaAsync( + public Mono> readMultipleReplicaAsync( RxDocumentServiceRequest entity, boolean includePrimary, int replicaCountToRead, @@ -109,7 +109,7 @@ public Single> readMultipleReplicaAsync( boolean forceReadAll) { if (entity.requestContext.timeoutHelper.isElapsed()) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } String originalSessionToken = entity.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); @@ -118,7 +118,7 @@ public Single> readMultipleReplicaAsync( entity.requestContext.clientSideRequestStatistics = new ClientSideRequestStatistics(); } - Single readQuorumResultObs = this.readMultipleReplicasInternalAsync( + Mono readQuorumResultObs = this.readMultipleReplicasInternalAsync( entity, includePrimary, replicaCountToRead, requiresValidLsn, useSessionToken, readMode, checkMinLSN, forceReadAll); return readQuorumResultObs.flatMap(readQuorumResult -> { @@ -126,7 +126,7 @@ public Single> readMultipleReplicaAsync( readQuorumResult.retryWithForceRefresh && !entity.requestContext.forceRefreshAddressCache) { if (entity.requestContext.timeoutHelper.isElapsed()) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } entity.requestContext.forceRefreshAddressCache = true; @@ -135,31 +135,29 @@ public Single> readMultipleReplicaAsync( entity, includePrimary, replicaCountToRead, requiresValidLsn, useSessionToken, readMode, false /*checkMinLSN*/, forceReadAll) .map(r -> r.responses); } else { - return Single.just(readQuorumResult.responses); + return Mono.just(readQuorumResult.responses); } - }).toObservable().doAfterTerminate(() -> { - SessionTokenHelper.setOriginalSessionToken(entity, originalSessionToken); - }).toSingle(); + }).flux().doAfterTerminate(() -> SessionTokenHelper.setOriginalSessionToken(entity, originalSessionToken)).single(); } - private Observable earlyResultIfNotEnoughReplicas(List replicaAddresses, - RxDocumentServiceRequest request, - int replicaCountToRead) { + private Flux earlyResultIfNotEnoughReplicas(List replicaAddresses, + RxDocumentServiceRequest request, + int replicaCountToRead) { if (replicaAddresses.size() < replicaCountToRead) { // if not enough replicas, return ReadReplicaResult if (!request.requestContext.forceRefreshAddressCache) { - return Observable.just(new ReadReplicaResult(true /*retryWithForceRefresh*/, Collections.emptyList())); + return Flux.just(new ReadReplicaResult(true /*retryWithForceRefresh*/, Collections.emptyList())); } else { - return Observable.just(new ReadReplicaResult(false /*retryWithForceRefresh*/, Collections.emptyList())); + return Flux.just(new ReadReplicaResult(false /*retryWithForceRefresh*/, Collections.emptyList())); } } else { // if there are enough replicas, move on - return Observable.empty(); + return Flux.empty(); } } - private Observable toStoreResult(RxDocumentServiceRequest request, - Pair, URI> storeRespAndURI, + private Flux toStoreResult(RxDocumentServiceRequest request, + Pair, URI> storeRespAndURI, ReadMode readMode, boolean requiresValidLsn) { @@ -173,19 +171,19 @@ private Observable toStoreResult(RxDocumentServiceRequest request, storeRespAndURI.getRight()); request.requestContext.clientSideRequestStatistics.getContactedReplicas().add(storeRespAndURI.getRight()); - return Observable.just(storeResult); + return Flux.just(storeResult); } catch (Exception e) { // RxJava1 doesn't allow throwing checked exception from Observable operators - return Observable.error(e); + return Flux.error(e); } } - ).onErrorResumeNext(t -> { + ).onErrorResume(t -> { try { logger.debug("Exception {} is thrown while doing readMany", t); Exception storeException = Utils.as(t, Exception.class); if (storeException == null) { - return Observable.error(t); + return Flux.error(t); } // Exception storeException = readTask.Exception != null ? readTask.Exception.InnerException : null; @@ -197,15 +195,15 @@ private Observable toStoreResult(RxDocumentServiceRequest request, if (storeException instanceof TransportException) { request.requestContext.clientSideRequestStatistics.getFailedReplicas().add(storeRespAndURI.getRight()); } - return Observable.just(storeResult); + return Flux.just(storeResult); } catch (Exception e) { // RxJava1 doesn't allow throwing checked exception from Observable operators - return Observable.error(e); + return Flux.error(e); } }); } - private Observable> readFromReplicas(List resultCollector, + private Flux> readFromReplicas(List resultCollector, List resolveApiResults, final AtomicInteger replicasToRead, RxDocumentServiceRequest entity, @@ -221,24 +219,24 @@ private Observable> readFromReplicas(List resultC boolean enforceSessionCheck, final MutableVolatile shortCircut) { if (entity.requestContext.timeoutHelper.isElapsed()) { - return Observable.error(new GoneException()); + return Flux.error(new GoneException()); } - List, URI>> readStoreTasks = new ArrayList<>(); + List, URI>> readStoreTasks = new ArrayList<>(); int uriIndex = StoreReader.generateNextRandom(resolveApiResults.size()); while (resolveApiResults.size() > 0) { uriIndex = uriIndex % resolveApiResults.size(); URI uri = resolveApiResults.get(uriIndex); - Pair, URI> res; + Pair, URI> res; try { res = this.readFromStoreAsync(resolveApiResults.get(uriIndex), entity); } catch (Exception e) { - res = Pair.of(Single.error(e), uri); + res = Pair.of(Mono.error(e), uri); } - readStoreTasks.add(Pair.of(res.getLeft().toObservable(), res.getRight())); + readStoreTasks.add(Pair.of(res.getLeft().flux(), res.getRight())); resolveApiResults.remove(uriIndex); @@ -250,22 +248,21 @@ private Observable> readFromReplicas(List resultC replicasToRead.set(readStoreTasks.size() >= replicasToRead.get() ? 0 : replicasToRead.get() - readStoreTasks.size()); - List> storeResult = readStoreTasks + List> storeResult = readStoreTasks .stream() .map(item -> toStoreResult(entity, item, readMode, requiresValidLsn)) .collect(Collectors.toList()); - Observable allStoreResults = Observable.merge(storeResult); + Flux allStoreResults = Flux.merge(storeResult); - return allStoreResults.toList().onErrorResumeNext(e -> { - if (e instanceof CompositeException) { + return allStoreResults.collectList().onErrorResume(e -> { + if (Exceptions.isMultiple(e)) { logger.info("Captured composite exception"); - CompositeException compositeException = (CompositeException) e; - List exceptions = compositeException.getExceptions(); - assert exceptions != null && !exceptions.isEmpty(); - return Observable.error(exceptions.get(0)); + List exceptions = Exceptions.unwrapMultiple(e); + assert !exceptions.isEmpty(); + return Mono.error(exceptions.get(0)); } - return Observable.error(e); + return Mono.error(e); }).map(newStoreResults -> { for (StoreResult srr : newStoreResults) { @@ -303,7 +300,7 @@ private Observable> readFromReplicas(List resultC replicasToRead.set(replicaCountToRead - resultCollector.size()); } return resultCollector; - }); + }).flux(); } private ReadReplicaResult createReadReplicaResult(List responseResult, @@ -346,7 +343,7 @@ private ReadReplicaResult createReadReplicaResult(List responseResu * @param forceReadAll will read from all available replicas to put together result from readsToRead number of replicas * @return ReadReplicaResult which indicates the LSN and whether Quorum was Met / Not Met etc */ - private Single readMultipleReplicasInternalAsync(RxDocumentServiceRequest entity, + private Mono readMultipleReplicasInternalAsync(RxDocumentServiceRequest entity, boolean includePrimary, int replicaCountToRead, boolean requiresValidLsn, @@ -355,7 +352,7 @@ private Single readMultipleReplicasInternalAsync(RxDocumentSe boolean checkMinLSN, boolean forceReadAll) { if (entity.requestContext.timeoutHelper.isElapsed()) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } String requestedCollectionId = null; @@ -364,7 +361,7 @@ private Single readMultipleReplicasInternalAsync(RxDocumentSe requestedCollectionId = entity.requestContext.resolvedCollectionRid; } - Single> resolveApiResultsObs = this.addressSelector.resolveAllUriAsync( + Mono> resolveApiResultsObs = this.addressSelector.resolveAllUriAsync( entity, includePrimary, entity.requestContext.forceRefreshAddressCache); @@ -375,7 +372,7 @@ private Single readMultipleReplicasInternalAsync(RxDocumentSe } } - return resolveApiResultsObs.toObservable() + return resolveApiResultsObs.flux() .map(list -> Collections.synchronizedList(new ArrayList<>(list))) .flatMap( resolveApiResults -> { @@ -390,9 +387,9 @@ private Single readMultipleReplicasInternalAsync(RxDocumentSe entity.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } - Observable y = earlyResultIfNotEnoughReplicas(resolveApiResults, entity, replicaCountToRead); + Flux y = earlyResultIfNotEnoughReplicas(resolveApiResults, entity, replicaCountToRead); return y.switchIfEmpty( - Observable.defer(() -> { + Flux.defer(() -> { List storeResultList = Collections.synchronizedList(new ArrayList<>()); AtomicInteger replicasToRead = new AtomicInteger(replicaCountToRead); @@ -405,7 +402,7 @@ private Single readMultipleReplicasInternalAsync(RxDocumentSe MutableVolatile hasGoneException = new MutableVolatile(false); MutableVolatile shortCircuitResult = new MutableVolatile(); - return Observable.defer(() -> + return Flux.defer(() -> readFromReplicas( storeResultList, resolveApiResults, @@ -434,31 +431,30 @@ private Single readMultipleReplicasInternalAsync(RxDocumentSe return true; } }) - .toCompletable() - .andThen( - Observable.defer(() -> { - try { - // TODO: some fields which get updated need to be thread-safe - return Observable.just(createReadReplicaResult(storeResultList, replicaCountToRead, resolveApiResults.size(), hasGoneException.v, entity)); - } catch (Exception e) { - return Observable.error(e); - } + .thenMany( + Flux.defer(() -> { + try { + // TODO: some fields which get updated need to be thread-safe + return Flux.just(createReadReplicaResult(storeResultList, replicaCountToRead, resolveApiResults.size(), hasGoneException.v, entity)); + } catch (Exception e) { + return Flux.error(e); + } } )); })); } catch (Exception e) { - return Observable.error(e); + return Flux.error(e); } } - ).toSingle(); + ).single(); } - public Single readPrimaryAsync( + public Mono readPrimaryAsync( RxDocumentServiceRequest entity, boolean requiresValidLsn, boolean useSessionToken) { if (entity.requestContext.timeoutHelper.isElapsed()) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } String originalSessionToken = entity.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); @@ -474,13 +470,13 @@ public Single readPrimaryAsync( readQuorumResult.retryWithForceRefresh && !entity.requestContext.forceRefreshAddressCache) { if (entity.requestContext.timeoutHelper.isElapsed()) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } entity.requestContext.forceRefreshAddressCache = true; return this.readPrimaryInternalAsync(entity, requiresValidLsn, useSessionToken); } else { - return Single.just(readQuorumResult); + return Mono.just(readQuorumResult); } } ).flatMap(readQuorumResult -> { @@ -492,10 +488,10 @@ public Single readPrimaryAsync( // once we switch to RxJava2 we can move to Observable.map(.) // https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#functional-interfaces if (readQuorumResult.responses.size() == 0) { - return Single.error(new GoneException(RMResources.Gone)); + return Mono.error(new GoneException(RMResources.Gone)); } - return Single.just(readQuorumResult.responses.get(0)); + return Mono.just(readQuorumResult.responses.get(0)); }).doOnEach(arg -> { try { @@ -507,19 +503,19 @@ public Single readPrimaryAsync( ); } - private Single readPrimaryInternalAsync( + private Mono readPrimaryInternalAsync( RxDocumentServiceRequest entity, boolean requiresValidLsn, boolean useSessionToken) { if (entity.requestContext.timeoutHelper.isElapsed()) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } - Single primaryUriObs = this.addressSelector.resolvePrimaryUriAsync( + Mono primaryUriObs = this.addressSelector.resolvePrimaryUriAsync( entity, entity.requestContext.forceRefreshAddressCache); - Single storeResultObs = primaryUriObs.flatMap( + Mono storeResultObs = primaryUriObs.flatMap( primaryUri -> { try { if (useSessionToken) { @@ -532,7 +528,7 @@ private Single readPrimaryInternalAsync( } - Pair, URI> storeResponseObsAndUri = this.readFromStoreAsync(primaryUri, entity); + Pair, URI> storeResponseObsAndUri = this.readFromStoreAsync(primaryUri, entity); return storeResponseObsAndUri.getLeft().flatMap( storeResponse -> { @@ -543,9 +539,9 @@ private Single readPrimaryInternalAsync( null, requiresValidLsn, true, storeResponse != null ? storeResponseObsAndUri.getRight() : null); - return Single.just(storeResult); + return Mono.just(storeResult); } catch (CosmosClientException e) { - return Single.error(e); + return Mono.error(e); } } @@ -553,16 +549,16 @@ private Single readPrimaryInternalAsync( } catch (CosmosClientException e) { // RxJava1 doesn't allow throwing checked exception from Observable:map - return Single.error(e); + return Mono.error(e); } } - ).onErrorResumeNext(t -> { + ).onErrorResume(t -> { logger.debug("Exception {} is thrown while doing READ Primary", t); Exception storeTaskException = Utils.as(t, Exception.class); if (storeTaskException == null) { - return Single.error(t); + return Mono.error(t); } try { @@ -571,10 +567,10 @@ private Single readPrimaryInternalAsync( storeTaskException, requiresValidLsn, true, null); - return Single.just(storeResult); + return Mono.just(storeResult); } catch (CosmosClientException e) { // RxJava1 doesn't allow throwing checked exception from Observable operators - return Single.error(e); + return Mono.error(e); } }); @@ -590,7 +586,7 @@ private Single readPrimaryInternalAsync( }); } - private Pair, URI> readFromStoreAsync( + private Pair, URI> readFromStoreAsync( URI physicalAddress, RxDocumentServiceRequest request) throws CosmosClientException { @@ -634,7 +630,7 @@ private Pair, URI> readFromStoreAsync( switch (request.getOperationType()) { case Read: case Head: { - Single storeResponseObs = this.transportClient.invokeResourceOperationAsync( + Mono storeResponseObs = this.transportClient.invokeResourceOperationAsync( physicalAddress, request); @@ -647,7 +643,7 @@ private Pair, URI> readFromStoreAsync( case Query: case SqlQuery: case ExecuteJavaScript: { - Single storeResponseObs = StoreReader.completeActivity(this.transportClient.invokeResourceOperationAsync( + Mono storeResponseObs = StoreReader.completeActivity(this.transportClient.invokeResourceOperationAsync( physicalAddress, request), null); // TODO activity); @@ -661,7 +657,7 @@ private Pair, URI> readFromStoreAsync( } - private static Single completeActivity(Single task, Object activity) { + private static Mono completeActivity(Mono task, Object activity) { // TODO: client statistics // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/258624 return task; @@ -843,7 +839,7 @@ StoreResult createStoreResult(StoreResponse storeResponse, void startBackgroundAddressRefresh(RxDocumentServiceRequest request) { this.addressSelector.resolveAllUriAsync(request, true, true) - .observeOn(Schedulers.io()) + .publishOn(Schedulers.elastic()) .subscribe( r -> { }, diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportClient.java index 6123d6d7bf196..a4c0c259c809a 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportClient.java @@ -24,19 +24,18 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import rx.Single; +import reactor.core.publisher.Mono; import java.net.URI; public abstract class TransportClient implements AutoCloseable { // Uses requests's ResourceOperation to determine the operation - public Single invokeResourceOperationAsync(URI physicalAddress, RxDocumentServiceRequest request) { - return this.invokeStoreAsync(physicalAddress, new ResourceOperation(request.getOperationType(), request.getResourceType()), request); + public Mono invokeResourceOperationAsync(URI physicalAddress, RxDocumentServiceRequest request) { + return this.invokeStoreAsync(physicalAddress, request); } - protected abstract Single invokeStoreAsync( + protected abstract Mono invokeStoreAsync( URI physicalAddress, - ResourceOperation resourceOperation, RxDocumentServiceRequest request); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java index 7607d3a467d3c..6c13f5529f296 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.util.Map; @@ -46,14 +46,14 @@ public UnauthorizedException(Error error, long lsn, String partitionKeyRangeId, } public UnauthorizedException(String message) { - this(message, (Exception) null, (HttpResponseHeaders) null, null); + this(message, null, null, null); } - public UnauthorizedException(String message, HttpResponseHeaders headers, String requestUri) { - this(message, null, headers, requestUri); + public UnauthorizedException(String message, HttpHeaders headers, String requestUriString) { + this(message, null, headers, requestUriString); } - public UnauthorizedException(String message, HttpResponseHeaders headers, URI requestUri) { + public UnauthorizedException(String message, HttpHeaders headers, URI requestUri) { this(message, headers, requestUri != null ? requestUri.toString() : null); } @@ -63,12 +63,12 @@ public UnauthorizedException(Exception innerException) { public UnauthorizedException(String message, Exception innerException, - HttpResponseHeaders headers, + HttpHeaders headers, String requestUri) { super(String.format("%s: %s", RMResources.Unauthorized, message), innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.UNAUTHORIZED, - requestUri != null ? requestUri.toString() : null); + requestUri); } } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java index 3146f28ef5078..399eecaf7605e 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java @@ -48,14 +48,11 @@ import org.apache.commons.lang3.mutable.MutableObject; import org.apache.commons.lang3.tuple.ImmutablePair; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Single; -import rx.functions.Func1; +import reactor.core.publisher.Mono; import java.net.URI; import java.util.ArrayList; @@ -65,6 +62,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Function; import java.util.stream.Collectors; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; @@ -108,7 +106,7 @@ public void setup() throws Exception { partitionKeyDef.paths(ImmutableList.of("/field1")); this.collection2.setPartitionKey(partitionKeyDef); - Func1>, Void> addPartitionKeyRangeFunc = listArg -> { + Function>, Void> addPartitionKeyRangeFunc = listArg -> { listArg.forEach(tuple -> ((ServiceIdentity) tuple.right).partitionKeyRangeIds.add(new PartitionKeyRangeIdentity(collection1.resourceId(), tuple.left.id()))); return null; }; @@ -121,7 +119,7 @@ public void setup() throws Exception { ImmutablePair.of(new PartitionKeyRange("0", PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey), serverServiceIdentity)); - addPartitionKeyRangeFunc.call(rangesBeforeSplit1); + addPartitionKeyRangeFunc.apply(rangesBeforeSplit1); this.routingMapCollection1BeforeSplit = @@ -144,7 +142,7 @@ public void setup() throws Exception { new PartitionKeyRange("2", "5E", PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey, ImmutableList.of("0")), serverServiceIdentity3)); - addPartitionKeyRangeFunc.call(rangesAfterSplit1); + addPartitionKeyRangeFunc.apply(rangesAfterSplit1); this.routingMapCollection1AfterSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesAfterSplit1, collection1.resourceId()); @@ -157,7 +155,7 @@ public void setup() throws Exception { new PartitionKeyRange("0", PartitionKeyInternalHelper.MinimumInclusiveEffectivePartitionKey, PartitionKeyInternalHelper.MaximumExclusiveEffectivePartitionKey), serverServiceIdentity4)); - addPartitionKeyRangeFunc.call(rangesBeforeSplit2); + addPartitionKeyRangeFunc.apply(rangesBeforeSplit2); this.routingMapCollection2BeforeSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesBeforeSplit2, collection2.resourceId()); @@ -178,7 +176,7 @@ public void setup() throws Exception { serverServiceIdentity6)); - addPartitionKeyRangeFunc.call(rangesAfterSplit2); + addPartitionKeyRangeFunc.apply(rangesAfterSplit2); this.routingMapCollection2AfterSplit = InMemoryCollectionRoutingMap.tryCreateCompleteRoutingMap(rangesAfterSplit2, collection2.resourceId()); @@ -232,9 +230,9 @@ private void TestCacheRefreshWhileRouteByPartitionKey( request.forceNameCacheRefresh = forceNameCacheRefresh; request.forcePartitionKeyRangeRefresh = forceRoutingMapRefresh; request.getHeaders().put(HttpConstants.HttpHeaders.PARTITION_KEY, new PartitionKey("foo").toString()); - AddressInformation[] resolvedAddresses = null; + AddressInformation[] resolvedAddresses; try { - resolvedAddresses = this.addressResolver.resolveAsync(request, forceAddressRefresh).toBlocking().value(); + resolvedAddresses = this.addressResolver.resolveAsync(request, forceAddressRefresh).block(); } catch (RuntimeException e) { throw (Exception) e.getCause(); } finally { @@ -301,9 +299,8 @@ private void TestCacheRefreshWhileRouteByPartitionKeyRangeId( request.routeTo(rangeIdentity); AddressInformation[] resolvedAddresses; try { - resolvedAddresses = this.addressResolver.resolveAsync(request, forceAddressRefresh).toBlocking().value(); + resolvedAddresses = this.addressResolver.resolveAsync(request, forceAddressRefresh).block(); } catch (RuntimeException e) { - e.printStackTrace(); throw (Exception) e.getCause(); } finally { assertThat(collectionCacheRefreshed).isEqualTo(collectionCacheRefreshedCount).describedAs("collection cache refresh count mismath"); @@ -335,35 +332,32 @@ private void initializeMocks( MutableObject currentCollection = new MutableObject(collectionBeforeRefresh); this.collectionCacheRefreshedCount = 0; - Mockito.doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { - RxDocumentServiceRequest request = invocationOnMock.getArgumentAt(0, RxDocumentServiceRequest.class); - if (request.forceNameCacheRefresh && collectionAfterRefresh != null) { - currentCollection.setValue(collectionAfterRefresh); - AddressResolverTest.this.collectionCacheRefreshedCount++; - request.forceNameCacheRefresh = false; - return Single.just(currentCollection.getValue()); - } - - if (request.forceNameCacheRefresh && collectionAfterRefresh == null) { - currentCollection.setValue(null); - AddressResolverTest.this.collectionCacheRefreshedCount++; - request.forceNameCacheRefresh = false; - return Single.error(new NotFoundException()); - } + Mockito.doAnswer(invocationOnMock -> { + RxDocumentServiceRequest request = invocationOnMock.getArgumentAt(0, RxDocumentServiceRequest.class); + if (request.forceNameCacheRefresh && collectionAfterRefresh != null) { + currentCollection.setValue(collectionAfterRefresh); + AddressResolverTest.this.collectionCacheRefreshedCount++; + request.forceNameCacheRefresh = false; + return Mono.just(currentCollection.getValue()); + } - if (!request.forceNameCacheRefresh && currentCollection.getValue() == null) { - return Single.error(new NotFoundException()); + if (request.forceNameCacheRefresh && collectionAfterRefresh == null) { + currentCollection.setValue(null); + AddressResolverTest.this.collectionCacheRefreshedCount++; + request.forceNameCacheRefresh = false; + return Mono.error(new NotFoundException()); + } - } + if (!request.forceNameCacheRefresh && currentCollection.getValue() == null) { + return Mono.error(new NotFoundException()); - if (!request.forceNameCacheRefresh && currentCollection.getValue() != null) { - return Single.just(currentCollection.getValue()); - } + } - return null; + if (!request.forceNameCacheRefresh && currentCollection.getValue() != null) { + return Mono.just(currentCollection.getValue()); } + + return Mono.empty(); }).when(this.collectionCache).resolveCollectionAsync(Mockito.any(RxDocumentServiceRequest.class)); // Routing map cache @@ -371,53 +365,47 @@ public Object answer(InvocationOnMock invocationOnMock) throws Throwable { new HashMap<>(routingMapBeforeRefresh); this.routingMapRefreshCount = new HashMap<>(); - Mockito.doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { - String collectionRid = invocationOnMock.getArgumentAt(0, String.class); - CollectionRoutingMap previousValue = invocationOnMock.getArgumentAt(1, CollectionRoutingMap.class); + Mockito.doAnswer(invocationOnMock -> { + String collectionRid = invocationOnMock.getArgumentAt(0, String.class); + CollectionRoutingMap previousValue = invocationOnMock.getArgumentAt(1, CollectionRoutingMap.class); - return collectionRoutingMapCache.tryLookupAsync(collectionRid, previousValue, false, null); - } + return collectionRoutingMapCache.tryLookupAsync(collectionRid, previousValue, false, null); }).when(this.collectionRoutingMapCache).tryLookupAsync(Mockito.anyString(), Mockito.any(CollectionRoutingMap.class), Mockito.anyMap()); // Refresh case - Mockito.doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { - String collectionRid = invocationOnMock.getArgumentAt(0, String.class); - CollectionRoutingMap previousValue = invocationOnMock.getArgumentAt(1, CollectionRoutingMap.class); - - if (previousValue == null) { - return Single.just(currentRoutingMap.containsKey(collectionRid) ? currentRoutingMap.get(collectionRid) : null); - } - - if (previousValue != null && currentRoutingMap.containsKey(previousValue.getCollectionUniqueId()) && - currentRoutingMap.get(previousValue.getCollectionUniqueId()) == previousValue) { + Mockito.doAnswer(invocationOnMock -> { + String collectionRid = invocationOnMock.getArgumentAt(0, String.class); + CollectionRoutingMap previousValue = invocationOnMock.getArgumentAt(1, CollectionRoutingMap.class); + if (previousValue == null) { + return Mono.justOrEmpty(currentRoutingMap.get(collectionRid)); + } - if (previousValue != null && previousValue.getCollectionUniqueId() != collectionRid) { - throw new RuntimeException("InvalidOperation"); - } + if (previousValue != null && currentRoutingMap.containsKey(previousValue.getCollectionUniqueId()) && + currentRoutingMap.get(previousValue.getCollectionUniqueId()) == previousValue) { - if (routingMapAfterRefresh.containsKey(collectionRid)) { - currentRoutingMap.put(collectionRid, routingMapAfterRefresh.get(collectionRid)); - } else { - currentRoutingMap.remove(collectionRid); - } - if (!routingMapRefreshCount.containsKey(collectionRid)) { - routingMapRefreshCount.put(collectionRid, 1); - } else { - routingMapRefreshCount.put(collectionRid, routingMapRefreshCount.get(collectionRid) + 1); - } + if (previousValue != null && previousValue.getCollectionUniqueId() != collectionRid) { + throw new RuntimeException("InvalidOperation"); + } + if (routingMapAfterRefresh.containsKey(collectionRid)) { + currentRoutingMap.put(collectionRid, routingMapAfterRefresh.get(collectionRid)); + } else { + currentRoutingMap.remove(collectionRid); + } - return Single.just(currentRoutingMap.containsKey(collectionRid) ? currentRoutingMap.get(collectionRid) : null); + if (!routingMapRefreshCount.containsKey(collectionRid)) { + routingMapRefreshCount.put(collectionRid, 1); + } else { + routingMapRefreshCount.put(collectionRid, routingMapRefreshCount.get(collectionRid) + 1); } - return Single.error(new NotImplementedException("not mocked")); + + return Mono.justOrEmpty(currentRoutingMap.get(collectionRid)); } + + return Mono.error(new NotImplementedException("not mocked")); }).when(this.collectionRoutingMapCache).tryLookupAsync(Mockito.anyString(), Mockito.any(CollectionRoutingMap.class), Mockito.anyBoolean(), Mockito.anyMap()); @@ -427,43 +415,39 @@ public Object answer(InvocationOnMock invocationOnMock) throws Throwable { this.addressesRefreshCount = new HashMap<>(); // No refresh case - Mockito.doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Exception { - RxDocumentServiceRequest request = invocationOnMock.getArgumentAt(0, RxDocumentServiceRequest.class); - PartitionKeyRangeIdentity pkri = invocationOnMock.getArgumentAt(1, PartitionKeyRangeIdentity.class); - Boolean forceRefresh = invocationOnMock.getArgumentAt(2, Boolean.class); - - if (!forceRefresh) { - return Single.just(currentAddresses.get(findMatchingServiceIdentity(currentAddresses, pkri))); - } else { + // + Mockito.doAnswer(invocationOnMock -> { + RxDocumentServiceRequest request = invocationOnMock.getArgumentAt(0, RxDocumentServiceRequest.class); + PartitionKeyRangeIdentity pkri = invocationOnMock.getArgumentAt(1, PartitionKeyRangeIdentity.class); + Boolean forceRefresh = invocationOnMock.getArgumentAt(2, Boolean.class); - ServiceIdentity si; + if (!forceRefresh) { + return Mono.justOrEmpty(currentAddresses.get(findMatchingServiceIdentity(currentAddresses, pkri))); + } else { - if ((si = findMatchingServiceIdentity(addressesAfterRefresh, pkri)) != null) { - currentAddresses.put(si, addressesAfterRefresh.get(si)); - } else { + ServiceIdentity si; - si = findMatchingServiceIdentity(currentAddresses, pkri); - currentAddresses.remove(si); - } - - if (si == null) { - si = ServiceIdentity.dummyInstance; - } + if ((si = findMatchingServiceIdentity(addressesAfterRefresh, pkri)) != null) { + currentAddresses.put(si, addressesAfterRefresh.get(si)); + } else { - if (!addressesRefreshCount.containsKey(si)) { - addressesRefreshCount.put(si, 1); - } else { - addressesRefreshCount.put(si, addressesRefreshCount.get(si) + 1); - } + si = findMatchingServiceIdentity(currentAddresses, pkri); + currentAddresses.remove(si); + } + if (si == null) { + si = ServiceIdentity.dummyInstance; + } - // TODO: what to return in this case if it is null!! - return Single.just(currentAddresses.containsKey(si) ? currentAddresses.get(si) : null); + if (!addressesRefreshCount.containsKey(si)) { + addressesRefreshCount.put(si, 1); + } else { + addressesRefreshCount.put(si, addressesRefreshCount.get(si) + 1); } + + // TODO: what to return in this case if it is null!! + return Mono.justOrEmpty(currentAddresses.get(si)); } - // }).when(fabricAddressCache).tryGetAddresses(Mockito.any(RxDocumentServiceRequest.class), Mockito.any(PartitionKeyRangeIdentity.class), Mockito.anyBoolean()); } @@ -869,7 +853,7 @@ public void testCacheRefreshesWhileRoutingByPartitionKeyRangeId() throws Excepti } catch (PartitionKeyRangeGoneException e) { } - logger.info("Name Based.Routing map cache is outdated because split happend."); + logger.info("Name Based.Routing map cache is outdated because split happened."); this.TestCacheRefreshWhileRouteByPartitionKeyRangeId( this.collection1, this.collection1, diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java index 2404ed08cf2e7..5c761c385ac79 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java @@ -28,7 +28,7 @@ import org.mockito.Matchers; import org.mockito.Mockito; import org.testng.annotations.Test; -import rx.Single; +import reactor.core.publisher.Mono; import java.net.URI; import java.util.ArrayList; @@ -110,9 +110,9 @@ public void resolvePrimaryUriAsync() { replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.HTTPS)); replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.HTTPS)); - Mockito.doReturn(Single.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); + Mockito.doReturn(Mono.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); - URI res = selector.resolvePrimaryUriAsync(request, false).toBlocking().value(); + URI res = selector.resolvePrimaryUriAsync(request, false).block(); assertThat(res).isEqualTo(URI.create("https://cosmos2")); } @@ -133,9 +133,9 @@ public void resolveAllUriAsync() { replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.HTTPS)); replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.HTTPS)); - Mockito.doReturn(Single.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); + Mockito.doReturn(Mono.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); - List res = selector.resolveAllUriAsync(request, true, false).toBlocking().value(); + List res = selector.resolveAllUriAsync(request, true, false).block(); assertThat(res).isEqualTo(ImmutableList.of(URI.create("https://cosmos1"), URI.create("https://cosmos2"), URI.create("https://cosmos3"))); } @@ -156,9 +156,9 @@ public void resolveAddressesAsync() { replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.HTTPS)); replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.HTTPS)); - Mockito.doReturn(Single.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); + Mockito.doReturn(Mono.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); - List res = selector.resolveAddressesAsync(request, false).toBlocking().value(); + List res = selector.resolveAddressesAsync(request, false).block(); assertThat(res).isEqualTo(replicaAddresses.stream().filter(a -> a.getProtocolName().equals(Protocol.HTTPS.toString())).collect(Collectors.toList())); } @@ -179,9 +179,9 @@ public void resolveAllUriAsync_RNTBD() { replicaAddresses.add(new AddressInformation(true, true, "https://cosmos2", Protocol.HTTPS)); replicaAddresses.add(new AddressInformation(true, false, "https://cosmos3", Protocol.HTTPS)); - Mockito.doReturn(Single.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); + Mockito.doReturn(Mono.just(replicaAddresses.toArray(new AddressInformation[0]))).when(addressResolver).resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Matchers.eq(false)); - List res = selector.resolveAllUriAsync(request, true, false).toBlocking().value(); + List res = selector.resolveAllUriAsync(request, true, false).block(); assertThat(res).isEqualTo(ImmutableList.of(URI.create("rntbd://cosmos1"), URI.create("rntbd://cosmos2"))); } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java index 54061ed1b8561..0698078c9f115 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java @@ -32,7 +32,7 @@ import org.assertj.core.api.Condition; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import rx.Single; +import reactor.core.publisher.Mono; import java.net.URI; import java.util.ArrayList; @@ -321,10 +321,10 @@ public PrimaryReplicaMoveBuilder withPrimaryReplicaMove(URI primaryURIBeforeForc if (forceRefresh || refreshed.get()) { refreshed.set(true); - return Single.just(primaryURIAfterForceRefresh); + return Mono.just(primaryURIAfterForceRefresh); } - return Single.just(primaryURIBeforeForceRefresh); + return Mono.just(primaryURIBeforeForceRefresh); }).when(addressSelector).resolvePrimaryUriAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.anyBoolean()); Mockito.doAnswer((invocation -> { @@ -396,9 +396,9 @@ public AddressSelectorWrapper build() { } if (forceRefresh || refreshed.get()) { refreshed.set(true); - return Single.just(primary.getRight()); + return Mono.just(primary.getRight()); } else { - return Single.just(primary.getLeft()); + return Mono.just(primary.getLeft()); } }).when(addressSelector).resolvePrimaryUriAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.anyBoolean()); @@ -420,14 +420,14 @@ public AddressSelectorWrapper build() { b.add(primary.getRight()); } b.addAll(secondary.stream().map(s -> s.getRight()).collect(Collectors.toList())); - return Single.just(b.build()); + return Mono.just(b.build()); } else { // old if (includePrimary) { b.add(primary.getLeft()); } b.addAll(secondary.stream().map(s -> s.getLeft()).collect(Collectors.toList())); - return Single.just(b.build()); + return Mono.just(b.build()); } })).when(addressSelector).resolveAllUriAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.anyBoolean(), Mockito.anyBoolean()); @@ -447,12 +447,12 @@ public AddressSelectorWrapper build() { refreshed.set(true); b.add(primary.getRight()); b.addAll(secondary.stream().map(s -> s.getRight()).collect(Collectors.toList())); - return Single.just(b.build()); + return Mono.just(b.build()); } else { // old b.add(primary.getLeft()); b.addAll(secondary.stream().map(s -> s.getLeft()).collect(Collectors.toList())); - return Single.just(b.build()); + return Mono.just(b.build()); } })).when(addressSelector).resolveAddressesAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.anyBoolean()); @@ -485,7 +485,7 @@ public Simple withSecondary(List secondaryAddresses) { public AddressSelectorWrapper build() { Mockito.doAnswer((invocation) -> { capture(invocation); - return Single.just(primaryAddress); + return Mono.just(primaryAddress); }).when(addressSelector).resolvePrimaryUriAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.anyBoolean()); Mockito.doAnswer((invocation -> { @@ -495,15 +495,15 @@ public AddressSelectorWrapper build() { boolean forceRefresh = invocation.getArgumentAt(2, Boolean.class); if (includePrimary) { - return Single.just(ImmutableList.builder().addAll(secondaryAddresses).add(primaryAddress).build()); + return Mono.just(ImmutableList.builder().addAll(secondaryAddresses).add(primaryAddress).build()); } else { - return Single.just(secondaryAddresses); + return Mono.just(secondaryAddresses); } })).when(addressSelector).resolveAllUriAsync(Mockito.any(), Mockito.anyBoolean(), Mockito.anyBoolean()); Mockito.doAnswer((invocation -> { capture(invocation); - return Single.just(ImmutableList.builder() + return Mono.just(ImmutableList.builder() .addAll(secondaryAddresses.stream() .map(uri -> toAddressInformation(uri, false, protocol)) .collect(Collectors.toList())) diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java index 89c104c10c6bf..bff642f62df92 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java @@ -41,11 +41,11 @@ import com.azure.data.cosmos.internal.VectorSessionToken; import com.azure.data.cosmos.rx.FailureValidator; import com.google.common.collect.ImmutableList; +import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Single; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Mono; import java.math.BigDecimal; import java.math.RoundingMode; @@ -206,7 +206,7 @@ public void readAny() { TimeoutHelper timeout = Mockito.mock(TimeoutHelper.class); boolean forceRefresh = false; boolean isInRetry = false; - Single storeResponseSingle = consistencyReader.readAsync(request, timeout, isInRetry, forceRefresh); + Mono storeResponseSingle = consistencyReader.readAsync(request, timeout, isInRetry, forceRefresh); StoreResponseValidator validator = StoreResponseValidator.create() .withBELSNGreaterThanOrEqualTo(51) @@ -324,7 +324,7 @@ public void readSessionConsistency_SomeReplicasLagBehindAndReturningResponseWith TimeoutHelper timeout = Mockito.mock(TimeoutHelper.class); boolean forceRefresh = false; boolean isInRetry = false; - Single storeResponseSingle = consistencyReader.readAsync(request, timeout, isInRetry, forceRefresh); + Mono storeResponseSingle = consistencyReader.readAsync(request, timeout, isInRetry, forceRefresh); StoreResponseValidator validator = StoreResponseValidator.create() .withBELSN(fasterReplicaLSN) @@ -435,7 +435,7 @@ public void sessionNotAvailableFromSomeReplicasThrowingNotFound_FindReplicaSatis Mockito.doReturn(sessionToken.v).when(sessionContainer).resolvePartitionLocalSessionToken(Mockito.eq(dsr), Mockito.anyString()); - Single storeResponseSingle = consistencyReader.readAsync(dsr, timeoutHelper, false, false); + Mono storeResponseSingle = consistencyReader.readAsync(dsr, timeoutHelper, false, false); StoreResponseValidator validator = StoreResponseValidator.create().isSameAs(storeResponse).isSameAs(storeResponse).build(); validateSuccess(storeResponseSingle, validator); @@ -502,7 +502,7 @@ public void sessionRead_LegitimateNotFound() { gatewayServiceConfigurationReaderWrapper.gatewayServiceConfigurationReader, authTokenProvider); - Single storeResponseSingle = consistencyReader.readAsync(dsr, timeoutHelper, false, false); + Mono storeResponseSingle = consistencyReader.readAsync(dsr, timeoutHelper, false, false); FailureValidator failureValidator = FailureValidator.builder().resourceNotFound().instanceOf(NotFoundException.class).unknownSubStatusCode().build(); validateException(storeResponseSingle, failureValidator); @@ -568,7 +568,7 @@ public void sessionRead_ReplicasDoNotHaveTheRequestedLSN() { gatewayServiceConfigurationReaderWrapper.gatewayServiceConfigurationReader, authTokenProvider); - Single storeResponseSingle = consistencyReader.readAsync(dsr, timeoutHelper, false, false); + Mono storeResponseSingle = consistencyReader.readAsync(dsr, timeoutHelper, false, false); FailureValidator failureValidator = FailureValidator.builder().resourceNotFound().instanceOf(NotFoundException.class).subStatusCode(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE).build(); validateException(storeResponseSingle, failureValidator); @@ -632,7 +632,7 @@ public void requestRateTooLarge_BubbleUp() { gatewayServiceConfigurationReaderWrapper.gatewayServiceConfigurationReader, authTokenProvider); - Single storeResponseSingle = consistencyReader.readAsync(dsr, timeoutHelper, false, false); + Mono storeResponseSingle = consistencyReader.readAsync(dsr, timeoutHelper, false, false); FailureValidator failureValidator = FailureValidator.builder().instanceOf(RequestRateTooLargeException.class).unknownSubStatusCode().build(); @@ -701,7 +701,7 @@ public void basicReadStrong_AllReplicasSameLSN(int replicaCountToRead, ReadMode IAuthorizationTokenProvider authTokenProvider = Mockito.mock(IAuthorizationTokenProvider.class); QuorumReader quorumReader = new QuorumReader(configs, transportClientWrapper.transportClient, addressSelectorWrapper.addressSelector, storeReader, serviceConfigurator, authTokenProvider); - Single storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); + Mono storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); StoreResponseValidator validator = StoreResponseValidator.create() .withBELSN(51) @@ -719,57 +719,57 @@ public void basicReadStrong_AllReplicasSameLSN(int replicaCountToRead, ReadMode // TODO: add more mocking tests for when one replica lags behind and we need to do barrier request. - public static void validateSuccess(Single> single, + public static void validateSuccess(Mono> single, MultiStoreResultValidator validator) { validateSuccess(single, validator, 10000); } - public static void validateSuccess(Single> single, + public static void validateSuccess(Mono> single, MultiStoreResultValidator validator, long timeout) { TestSubscriber> testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResponseValidator validator) { validateSuccess(single, validator, 10000); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResponseValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public static void validateException(Single single, + public static void validateException(Mono single, FailureValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + assertThat(testSubscriber.errorCount()).isEqualTo(1); + validator.validate(testSubscriber.errors().get(0)); } - public static void validateException(Single single, + public static void validateException(Mono single, FailureValidator validator) { validateException(single, validator, TIMEOUT); } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java index e1df184dc08a5..9592a9f64de05 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java @@ -33,14 +33,13 @@ import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.rx.FailureValidator; import com.google.common.collect.ImmutableList; +import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Single; -import rx.observers.TestSubscriber; -import rx.subjects.PublishSubject; +import reactor.core.publisher.DirectProcessor; +import reactor.core.publisher.Mono; import java.net.URI; import java.util.AbstractMap; @@ -108,7 +107,7 @@ public void exception(Exception ex, Class klass, int expectedStatusCo RxDocumentServiceRequest dsr = Mockito.mock(RxDocumentServiceRequest.class); dsr.requestContext = Mockito.mock(DocumentServiceRequestContext.class); - Single res = consistencyWriter.writeAsync(dsr, timeoutHelper, false); + Mono res = consistencyWriter.writeAsync(dsr, timeoutHelper, false); FailureValidator failureValidator = FailureValidator.builder() .instanceOf(klass) @@ -119,9 +118,9 @@ public void exception(Exception ex, Class klass, int expectedStatusCo TestSubscriber subscriber = new TestSubscriber<>(); res.subscribe(subscriber); subscriber.awaitTerminalEvent(); - subscriber.assertNotCompleted(); - assertThat(subscriber.getOnErrorEvents()).hasSize(1); - failureValidator.validate(subscriber.getOnErrorEvents().get(0)); + subscriber.assertNotComplete(); + assertThat(subscriber.errorCount()).isEqualTo(1); + failureValidator.validate(subscriber.errors().get(0)); } @Test(groups = "unit") @@ -129,35 +128,30 @@ public void startBackgroundAddressRefresh() throws Exception { initializeConsistencyWriter(false); CyclicBarrier b = new CyclicBarrier(2); - PublishSubject subject = PublishSubject.create(); + DirectProcessor directProcessor = DirectProcessor.create(); CountDownLatch c = new CountDownLatch(1); URI uri = URI.create("https://localhost:5050"); List invocationOnMocks = Collections.synchronizedList(new ArrayList<>()); - Mockito.doAnswer(new Answer() { - @Override - public Single answer(InvocationOnMock invocationOnMock) { - invocationOnMocks.add(invocationOnMock); - return subject.toSingle().doOnSuccess(x -> c.countDown()).doAfterTerminate(() -> { - new Thread() { - @Override - public void run() { - try { - b.await(); - } catch (Exception e) { - - } - } - }.start(); - }); - } + Mockito.doAnswer(invocationOnMock -> { + invocationOnMocks.add(invocationOnMock); + return directProcessor.single().doOnSuccess(x -> c.countDown()).doAfterTerminate(() -> new Thread() { + @Override + public void run() { + try { + b.await(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start()); }).when(addressSelector).resolvePrimaryUriAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.anyBoolean()); RxDocumentServiceRequest request = Mockito.mock(RxDocumentServiceRequest.class); consistencyWriter.startBackgroundAddressRefresh(request); - subject.onNext(uri); - subject.onCompleted(); + directProcessor.onNext(uri); + directProcessor.onComplete(); TimeUnit.MILLISECONDS.sleep(1000); assertThat(c.getCount()).isEqualTo(0); @@ -192,7 +186,6 @@ public void timeout1() throws Exception { TestSubscriber subscriber = new TestSubscriber(); spyConsistencyWriter.writeAsync(Mockito.mock(RxDocumentServiceRequest.class), timeoutHelper, false) - .toObservable() .subscribe(subscriber); subscriber.awaitTerminalEvent(10, TimeUnit.MILLISECONDS); @@ -210,7 +203,6 @@ public void timeout2() throws Exception { TestSubscriber subscriber = new TestSubscriber(); spyConsistencyWriter.writeAsync(Mockito.mock(RxDocumentServiceRequest.class), timeoutHelper, false) - .toObservable() .subscribe(subscriber); subscriber.awaitTerminalEvent(10, TimeUnit.MILLISECONDS); diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java index f2cd8fa529fc9..4181a71a27e2e 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.DatabaseAccount; import com.azure.data.cosmos.ReplicationPolicy; import org.mockito.Mockito; -import rx.Single; +import reactor.core.publisher.Mono; public class GatewayServiceConfiguratorReaderMock { @@ -67,7 +67,7 @@ public GatewayServiceConfiguratorReaderMock(ReplicationPolicy userReplicationPol ConsistencyLevel defaultConsistencyLevel) { this.gatewayServiceConfigurationReader = Mockito.mock(GatewayServiceConfigurationReader.class); - Mockito.doReturn(Single.just(Mockito.mock(DatabaseAccount.class))).when(this.gatewayServiceConfigurationReader).initializeReaderAsync(); + Mockito.doReturn(Mono.just(Mockito.mock(DatabaseAccount.class))).when(this.gatewayServiceConfigurationReader).initializeReaderAsync(); Mockito.doReturn(defaultConsistencyLevel).when(this.gatewayServiceConfigurationReader).getDefaultConsistencyLevel(); Mockito.doReturn(systemReplicationPolicy).when(this.gatewayServiceConfigurationReader).getSystemReplicationPolicy(); Mockito.doReturn(userReplicationPolicy).when(this.gatewayServiceConfigurationReader).getUserReplicationPolicy(); diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java index 8b8b8ae018032..66dbeebb28e67 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java @@ -35,7 +35,7 @@ import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.testng.annotations.Test; -import rx.Single; +import reactor.core.publisher.Mono; import static org.assertj.core.api.Assertions.assertThat; @@ -54,30 +54,30 @@ public class GoneAndRetryWithRetryPolicyTest { public void shouldRetryWithGoneException() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document); GoneAndRetryWithRetryPolicy goneAndRetryWithRetryPolicy = new GoneAndRetryWithRetryPolicy(request, 30); - Single singleShouldRetry = goneAndRetryWithRetryPolicy + Mono singleShouldRetry = goneAndRetryWithRetryPolicy .shouldRetry(new GoneException()); - IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.toBlocking().value(); + IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.block(); assertThat(shouldRetryResult.shouldRetry).isTrue(); assertThat(shouldRetryResult.policyArg.getValue0()).isTrue(); assertThat(shouldRetryResult.policyArg.getValue3()).isEqualTo(1); assertThat(shouldRetryResult.backOffTime.getSeconds()).isEqualTo(0); singleShouldRetry = goneAndRetryWithRetryPolicy.shouldRetry(new GoneException()); - shouldRetryResult = singleShouldRetry.toBlocking().value(); + shouldRetryResult = singleShouldRetry.block(); assertThat(shouldRetryResult.shouldRetry).isTrue(); assertThat(shouldRetryResult.policyArg.getValue0()).isTrue(); assertThat(shouldRetryResult.policyArg.getValue3()).isEqualTo(2); assertThat(shouldRetryResult.backOffTime.getSeconds()).isEqualTo(1); singleShouldRetry = goneAndRetryWithRetryPolicy.shouldRetry(new GoneException()); - shouldRetryResult = singleShouldRetry.toBlocking().value(); + shouldRetryResult = singleShouldRetry.block(); assertThat(shouldRetryResult.shouldRetry).isTrue(); assertThat(shouldRetryResult.policyArg.getValue0()).isTrue(); assertThat(shouldRetryResult.policyArg.getValue3()).isEqualTo(3); assertThat(shouldRetryResult.backOffTime.getSeconds()).isEqualTo(2); singleShouldRetry = goneAndRetryWithRetryPolicy.shouldRetry(new GoneException()); - shouldRetryResult = singleShouldRetry.toBlocking().value(); + shouldRetryResult = singleShouldRetry.block(); assertThat(shouldRetryResult.shouldRetry).isTrue(); assertThat(shouldRetryResult.policyArg.getValue0()).isTrue(); assertThat(shouldRetryResult.policyArg.getValue3()).isEqualTo(4); @@ -92,9 +92,9 @@ public void shouldRetryWithGoneException() { public void shouldRetryWithPartitionIsMigratingException() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document); GoneAndRetryWithRetryPolicy goneAndRetryWithRetryPolicy = new GoneAndRetryWithRetryPolicy(request, 30); - Single singleShouldRetry = goneAndRetryWithRetryPolicy + Mono singleShouldRetry = goneAndRetryWithRetryPolicy .shouldRetry(new PartitionIsMigratingException()); - IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.toBlocking().value(); + IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.block(); assertThat(shouldRetryResult.shouldRetry).isTrue(); assertThat(request.forceCollectionRoutingMapRefresh).isTrue(); assertThat(shouldRetryResult.policyArg.getValue0()).isTrue(); @@ -107,9 +107,9 @@ public void shouldRetryWithPartitionIsMigratingException() { public void shouldRetryWithInvalidPartitionException() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document); GoneAndRetryWithRetryPolicy goneAndRetryWithRetryPolicy = new GoneAndRetryWithRetryPolicy(request, 30); - Single singleShouldRetry = goneAndRetryWithRetryPolicy + Mono singleShouldRetry = goneAndRetryWithRetryPolicy .shouldRetry(new InvalidPartitionException()); - IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.toBlocking().value(); + IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.block(); assertThat(shouldRetryResult.shouldRetry).isTrue(); assertThat(request.requestContext.quorumSelectedLSN).isEqualTo(-1); assertThat(request.requestContext.resolvedPartitionKeyRange).isNull(); @@ -118,8 +118,7 @@ public void shouldRetryWithInvalidPartitionException() { goneAndRetryWithRetryPolicy.shouldRetry(new InvalidPartitionException()); // It will retry max till 3 attempts - shouldRetryResult = goneAndRetryWithRetryPolicy.shouldRetry(new InvalidPartitionException()).toBlocking() - .value(); + shouldRetryResult = goneAndRetryWithRetryPolicy.shouldRetry(new InvalidPartitionException()).block(); assertThat(shouldRetryResult.shouldRetry).isFalse(); CosmosClientException clientException = (CosmosClientException) shouldRetryResult.exception; assertThat(clientException.statusCode()).isEqualTo(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE); @@ -133,9 +132,9 @@ public void shouldRetryWithInvalidPartitionException() { public void shouldRetryWithPartitionKeyRangeIsSplittingException() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document); GoneAndRetryWithRetryPolicy goneAndRetryWithRetryPolicy = new GoneAndRetryWithRetryPolicy(request, 30); - Single singleShouldRetry = goneAndRetryWithRetryPolicy + Mono singleShouldRetry = goneAndRetryWithRetryPolicy .shouldRetry(new PartitionKeyRangeIsSplittingException()); - IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.toBlocking().value(); + IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.block(); assertThat(shouldRetryResult.shouldRetry).isTrue(); assertThat(request.forcePartitionKeyRangeRefresh).isTrue(); assertThat(request.requestContext.resolvedPartitionKeyRange).isNull(); @@ -151,9 +150,9 @@ public void shouldRetryWithPartitionKeyRangeIsSplittingException() { public void shouldRetryWithGenericException() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document); GoneAndRetryWithRetryPolicy goneAndRetryWithRetryPolicy = new GoneAndRetryWithRetryPolicy(request, 30); - Single singleShouldRetry = goneAndRetryWithRetryPolicy + Mono singleShouldRetry = goneAndRetryWithRetryPolicy .shouldRetry(new BadRequestException()); - IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.toBlocking().value(); + IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.block(); assertThat(shouldRetryResult.shouldRetry).isFalse(); } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpClientMockWrapper.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpClientMockWrapper.java index 692cb5af6fcbd..a6ae047c493fd 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpClientMockWrapper.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpClientMockWrapper.java @@ -23,32 +23,23 @@ package com.azure.data.cosmos.directconnectivity; -import io.netty.buffer.ByteBuf; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufUtil; -import io.netty.handler.codec.http.DefaultHttpHeaders; -import io.netty.handler.codec.http.DefaultHttpResponse; -import io.netty.handler.codec.http.HttpHeaders; -import io.netty.handler.codec.http.HttpResponse; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.netty.handler.codec.http.HttpVersion; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; -import org.apache.commons.lang3.tuple.ImmutablePair; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import rx.Observable; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.concurrent.TimeUnit; + +; public class HttpClientMockWrapper { public static HttpClientBehaviourBuilder httpClientBehaviourBuilder() { @@ -58,7 +49,7 @@ public static HttpClientBehaviourBuilder httpClientBehaviourBuilder() { public static class HttpClientBehaviourBuilder { private int status; private String content; - private HttpHeaders httpHeaders = new DefaultHttpHeaders(); + private HttpHeaders httpHeaders = new HttpHeaders(); private Exception networkFailure; public HttpClientBehaviourBuilder withNetworkFailure(Exception networkFailure) { @@ -82,7 +73,7 @@ public HttpClientBehaviourBuilder withHeaders(String... pairs) { } for(int i = 0; i < pairs.length/ 2; i++) { - this.httpHeaders.add(pairs[2*i], pairs[2*i +1]); + this.httpHeaders.set(pairs[2*i], pairs[2*i +1]); } return this; @@ -94,42 +85,30 @@ public HttpClientBehaviourBuilder withContent(String content) { } public HttpClientBehaviourBuilder withHeaderLSN(long lsn) { - this.httpHeaders.add(WFConstants.BackendHeaders.LSN, Long.toString(lsn)); + this.httpHeaders.set(WFConstants.BackendHeaders.LSN, Long.toString(lsn)); return this; } public HttpClientBehaviourBuilder withHeaderPartitionKeyRangeId(String partitionKeyRangeId) { - this.httpHeaders.add(WFConstants.BackendHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId); + this.httpHeaders.set(WFConstants.BackendHeaders.PARTITION_KEY_RANGE_ID, partitionKeyRangeId); return this; } public HttpClientBehaviourBuilder withHeaderSubStatusCode(int subStatusCode) { - this.httpHeaders.add(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(subStatusCode)); + this.httpHeaders.set(WFConstants.BackendHeaders.SUB_STATUS, Integer.toString(subStatusCode)); return this; } - public HttpClientResponse asHttpClientResponse() { + public HttpResponse asHttpResponse() { if (this.networkFailure != null) { return null; } - HttpClientResponse resp = Mockito.mock(HttpClientResponse.class); - Mockito.doReturn(HttpResponseStatus.valueOf(status)).when(resp).getStatus(); - Mockito.doReturn(Observable.just(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, content))).when(resp).getContent(); - - DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status), httpHeaders); - - try { - Constructor constructor = HttpResponseHeaders.class.getDeclaredConstructor(HttpResponse.class); - constructor.setAccessible(true); - HttpResponseHeaders httpResponseHeaders = constructor.newInstance(httpResponse); - Mockito.doReturn(httpResponseHeaders).when(resp).getHeaders(); - - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | NoSuchMethodException | SecurityException e) { - throw new IllegalStateException("Failed to instantiate class object.", e); - } - + HttpResponse resp = Mockito.mock(HttpResponse.class); + Mockito.doReturn(this.status).when(resp).statusCode(); + Mockito.doReturn(Flux.just(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, this.content))).when(resp).body(); + Mockito.doReturn(Mono.just(this.content)).when(resp).bodyAsString(StandardCharsets.UTF_8); + Mockito.doReturn(this.httpHeaders).when(resp).headers(); return resp; } @@ -148,60 +127,54 @@ public String toString() { } } - private final CompositeHttpClient httpClient; - private final List, RxClient.ServerInfo>> requests = Collections.synchronizedList(new ArrayList<>()); + private final HttpClient httpClient; + private final List requests = Collections.synchronizedList(new ArrayList<>()); - public HttpClientMockWrapper(long responseAfterMillis, HttpClientResponse httpClientResponse) { - this(responseAfterMillis, httpClientResponse, null); + public HttpClientMockWrapper(long responseAfterMillis, HttpResponse httpResponse) { + this(responseAfterMillis, httpResponse, null); } - private static Observable> httpClientResponseOrException(HttpClientResponse httpClientResponse, Exception e) { - assert ((httpClientResponse != null && e == null) || (httpClientResponse == null && e != null)); - return httpClientResponse != null ? Observable.just(httpClientResponse) : Observable.error(e); + private static Mono httpResponseOrException(HttpResponse httpResponse, Exception e) { + assert ((httpResponse != null && e == null) || (httpResponse == null && e != null)); + return httpResponse != null ? Mono.just(httpResponse) : Mono.error(e); } public HttpClientMockWrapper(long responseAfterMillis, Exception e) { this(responseAfterMillis, null, e); } - public HttpClientMockWrapper(HttpClientResponse httpClientResponse) { - this(0, httpClientResponse); + public HttpClientMockWrapper(HttpResponse httpResponse) { + this(0, httpResponse); } - private HttpClientMockWrapper(long responseAfterMillis, final HttpClientResponse httpClientResponse, final Exception e) { - httpClient = Mockito.mock(CompositeHttpClient.class); - assert httpClientResponse == null || e == null; - - Mockito.doAnswer(new Answer() { - @Override - public Observable> answer(InvocationOnMock invocationOnMock) throws Throwable { - RxClient.ServerInfo serverInfo = invocationOnMock.getArgumentAt(0, RxClient.ServerInfo.class); - HttpClientRequest req = invocationOnMock.getArgumentAt(1, HttpClientRequest.class); - - requests.add(new ImmutablePair<>(req, serverInfo)); - - if (responseAfterMillis <= 0) { - return httpClientResponseOrException(httpClientResponse, e); - } else { - return Observable.timer(responseAfterMillis, TimeUnit.MILLISECONDS).flatMap(t -> httpClientResponseOrException(httpClientResponse, e)); - } + private HttpClientMockWrapper(long responseAfterMillis, final HttpResponse httpResponse, final Exception e) { + httpClient = Mockito.mock(HttpClient.class); + assert httpResponse == null || e == null; + + Mockito.doAnswer(invocationOnMock -> { + HttpRequest httpRequest = invocationOnMock.getArgumentAt(0, HttpRequest.class); + requests.add(httpRequest); + if (responseAfterMillis <= 0) { + return httpResponseOrException(httpResponse, e); + } else { + return Mono.delay(Duration.ofMillis(responseAfterMillis)).flatMap(t -> httpResponseOrException(httpResponse, e)); } - }).when(httpClient).submit(Mockito.any(RxClient.ServerInfo.class), Mockito.any(HttpClientRequest.class)); + }).when(httpClient).send(Mockito.any(HttpRequest.class)); } public HttpClientMockWrapper(HttpClientBehaviourBuilder builder) { - this(0, builder.asHttpClientResponse(), builder.asNetworkFailure()); + this(0, builder.asHttpResponse(), builder.asNetworkFailure()); } public HttpClientMockWrapper(Exception e) { this(0, e); } - public CompositeHttpClient getClient() { + public HttpClient getClient() { return httpClient; } - public List, RxClient.ServerInfo>> getCapturedInvocation() { + public List getCapturedInvocation() { return requests; } } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java index 2883734c97097..c96762623ffe9 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java @@ -35,20 +35,17 @@ import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; import com.azure.data.cosmos.rx.FailureValidator; -import io.netty.buffer.ByteBuf; import io.netty.channel.ConnectTimeoutException; -import io.netty.handler.codec.http.EmptyHttpHeaders; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; -import org.apache.commons.lang3.tuple.ImmutablePair; +import io.reactivex.subscribers.TestSubscriber; import org.assertj.core.api.Assertions; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Single; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Mono; import java.net.URI; import java.net.UnknownHostException; @@ -57,6 +54,8 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +; + /** * Tests validating {@link HttpTransportClient} */ @@ -114,14 +113,14 @@ public void getResourceFeedUri_Database() throws Exception { public static HttpTransportClient getHttpTransportClientUnderTest(int requestTimeout, UserAgentContainer userAgent, - CompositeHttpClient httpClient) { + HttpClient httpClient) { class HttpTransportClientUnderTest extends HttpTransportClient { public HttpTransportClientUnderTest(int requestTimeout, UserAgentContainer userAgent) { super(configs, requestTimeout, userAgent); } @Override - CompositeHttpClient createHttpClient(int requestTimeout) { + HttpClient createHttpClient(int requestTimeout) { return httpClient; } } @@ -131,10 +130,10 @@ CompositeHttpClient createHttpClient(int requestTimeout) { @Test(groups = "unit") public void validateDefaultHeaders() { - HttpClientResponse mockedResponse = new HttpClientMockWrapper.HttpClientBehaviourBuilder() + HttpResponse mockedResponse = new HttpClientMockWrapper.HttpClientBehaviourBuilder() .withContent("").withStatus(200) - .withHeaders(EmptyHttpHeaders.INSTANCE) - .asHttpClientResponse(); + .withHeaders(new HttpHeaders()) + .asHttpResponse(); HttpClientMockWrapper httpClientMockWrapper = new HttpClientMockWrapper(mockedResponse); UserAgentContainer userAgentContainer = new UserAgentContainer(); @@ -148,17 +147,15 @@ public void validateDefaultHeaders() { OperationType.Create, "dbs/db/colls/col", ResourceType.Document); request.setContentBytes(new byte[0]); - transportClient.invokeStoreAsync(physicalAddress, - new ResourceOperation(OperationType.Create, ResourceType.Document), - request).toBlocking().value(); + transportClient.invokeStoreAsync(physicalAddress, request).block(); assertThat(httpClientMockWrapper.getCapturedInvocation()).asList().hasSize(1); - ImmutablePair, RxClient.ServerInfo> httpClientInvocation = httpClientMockWrapper.getCapturedInvocation().get(0); + HttpRequest httpRequest = httpClientMockWrapper.getCapturedInvocation().get(0); - assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.USER_AGENT)).endsWith("i am suffix"); - assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.CACHE_CONTROL)).isEqualTo("no-cache"); - assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.ACCEPT)).isEqualTo("application/json"); - assertThat(httpClientInvocation.left.getHeaders().get(HttpConstants.HttpHeaders.VERSION)).isEqualTo(HttpConstants.Versions.CURRENT_VERSION); + assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.USER_AGENT)).endsWith("i am suffix"); + assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.CACHE_CONTROL)).isEqualTo("no-cache"); + assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.ACCEPT)).isEqualTo("application/json"); + assertThat(httpRequest.headers().value(HttpConstants.HttpHeaders.VERSION)).isEqualTo(HttpConstants.Versions.CURRENT_VERSION); } @@ -467,9 +464,8 @@ public void failuresWithHttpStatusCodes(HttpClientMockWrapper.HttpClientBehaviou OperationType.Create, "dbs/db/colls/col", ResourceType.Document); request.setContentBytes(new byte[0]); - Single storeResp = transportClient.invokeStoreAsync( + Mono storeResp = transportClient.invokeStoreAsync( physicalAddress, - new ResourceOperation(OperationType.Create, ResourceType.Document), request); validateFailure(storeResp, failureValidatorBuilder.build()); @@ -576,9 +572,8 @@ public void networkFailures(RxDocumentServiceRequest request, userAgentContainer, httpClientMockWrapper.getClient()); - Single storeResp = transportClient.invokeStoreAsync( + Mono storeResp = transportClient.invokeStoreAsync( physicalAddress, - new ResourceOperation(OperationType.Create, ResourceType.Document), request); validateFailure(storeResp, failureValidatorBuilder.build()); @@ -606,36 +601,36 @@ private static RxDocumentServiceRequest createRequestFromName( return req; } - public void validateSuccess(Single single, StoreResponseValidator validator) { + public void validateSuccess(Mono single, StoreResponseValidator validator) { validateSuccess(single, validator, TIMEOUT); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResponseValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public void validateFailure(Single single, + public void validateFailure(Mono single, FailureValidator validator) { validateFailure(single, validator, TIMEOUT); } - public static void validateFailure(Single single, + public static void validateFailure(Mono single, FailureValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + Assertions.assertThat(testSubscriber.errorCount()).isEqualTo(1); + validator.validate(testSubscriber.errors().get(0)); } } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java index 2663cda588fb4..58c714560fbbc 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java @@ -36,9 +36,9 @@ import com.google.common.collect.Lists; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.functions.Func2; import java.util.ArrayList; +import java.util.function.BiFunction; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.fail; @@ -273,22 +273,22 @@ public void invalidPartitionKeyValue() { */ @Test(groups="unit") public void contains() { - Func2 verifyContains = (parentPartitionKey, childPartitionKey) -> + BiFunction verifyContains = (parentPartitionKey, childPartitionKey) -> PartitionKeyInternal.fromJsonString(parentPartitionKey) .contains(PartitionKeyInternal.fromJsonString(childPartitionKey)); - assertThat(verifyContains.call("[]", "[]")).isTrue(); - assertThat(verifyContains.call("[]", "[{}]")).isTrue(); - assertThat(verifyContains.call("[]", "[null]")).isTrue(); - assertThat(verifyContains.call("[]", "[true]")).isTrue(); - assertThat(verifyContains.call("[]", "[false]")).isTrue(); - assertThat(verifyContains.call("[]", "[2]")).isTrue(); - assertThat(verifyContains.call("[]", "[\"fdfd\"]")).isTrue(); - - assertThat(verifyContains.call("[2]", "[]")).isFalse(); - assertThat(verifyContains.call("[2]", "[2]")).isTrue(); - assertThat(verifyContains.call("[2]", "[2, \"USA\"]")).isTrue(); - assertThat(verifyContains.call("[1]", "[2, \"USA\"]")).isFalse(); + assertThat(verifyContains.apply("[]", "[]")).isTrue(); + assertThat(verifyContains.apply("[]", "[{}]")).isTrue(); + assertThat(verifyContains.apply("[]", "[null]")).isTrue(); + assertThat(verifyContains.apply("[]", "[true]")).isTrue(); + assertThat(verifyContains.apply("[]", "[false]")).isTrue(); + assertThat(verifyContains.apply("[]", "[2]")).isTrue(); + assertThat(verifyContains.apply("[]", "[\"fdfd\"]")).isTrue(); + + assertThat(verifyContains.apply("[2]", "[]")).isFalse(); + assertThat(verifyContains.apply("[2]", "[2]")).isTrue(); + assertThat(verifyContains.apply("[2]", "[2, \"USA\"]")).isTrue(); + assertThat(verifyContains.apply("[1]", "[2, \"USA\"]")).isFalse(); } @Test(groups="unit") diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java index 9069d3e81f3c9..c8ba601f93fd3 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java @@ -36,11 +36,11 @@ import com.azure.data.cosmos.rx.DocumentServiceRequestValidator; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; +import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Single; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Mono; import java.math.BigDecimal; import java.math.RoundingMode; @@ -130,7 +130,7 @@ public void basicReadStrong_AllReplicasSameLSN(int replicaCountToRead, ReadMode IAuthorizationTokenProvider authTokenProvider = Mockito.mock(IAuthorizationTokenProvider.class); QuorumReader quorumReader = new QuorumReader(configs, transportClientWrapper.transportClient, addressSelectorWrapper.addressSelector, storeReader, serviceConfigurator, authTokenProvider); - Single storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); + Mono storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); StoreResponseValidator.Builder validatorBuilder = StoreResponseValidator.create() .withBELocalLSN(localLSN) @@ -256,7 +256,7 @@ public void readStrong_OnlySecondary_RequestBarrier_Success(int numberOfBarrierR Stopwatch stopwatch = Stopwatch.createStarted(); - Single storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); + Mono storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); StoreResponseValidator validator = StoreResponseValidator.create() .withBELSN(expectedQuorumLsn) @@ -408,7 +408,7 @@ public void readStrong_SecondaryReadBarrierExhausted_ReadBarrierOnPrimary_Succes Stopwatch stopwatch = Stopwatch.createStarted(); - Single storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); + Mono storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); StoreResponseValidator validator = StoreResponseValidator.create() .withBELSN(expectedQuorumLsn) @@ -526,7 +526,7 @@ public void readStrong_QuorumNotSelected_ReadPrimary() { .add(requestChargePerHead.multiply(BigDecimal.valueOf(0))) .setScale(4, RoundingMode.FLOOR).doubleValue(); - Single storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); + Mono storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); StoreResponseValidator validator = StoreResponseValidator.create() .withBELSN(primaryLSN) @@ -633,45 +633,45 @@ public void readPrimary(EndpointMock endpointMock, int replicaCountToRead = 1; ReadMode readMode = ReadMode.Strong; - Single storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); + Mono storeResponseSingle = quorumReader.readStrongAsync(request, replicaCountToRead, readMode); validateSuccess(storeResponseSingle, storeResponseValidator); endpointMock.validate(verification); } - public static void validateSuccess(Single> single, + public static void validateSuccess(Mono> single, MultiStoreResultValidator validator) { validateSuccess(single, validator, 10000); } - public static void validateSuccess(Single> single, + public static void validateSuccess(Mono> single, MultiStoreResultValidator validator, long timeout) { TestSubscriber> testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResponseValidator validator) { validateSuccess(single, validator, 10000); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResponseValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java index 10af24360da49..78b2d875cc556 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java @@ -36,17 +36,17 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.SessionContainer; import com.azure.data.cosmos.rx.FailureValidator; +import io.reactivex.subscribers.TestSubscriber; import org.assertj.core.api.Assertions; import org.mockito.Mockito; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Single; -import rx.functions.Func1; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Mono; import java.net.URI; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.function.Function; public class ReplicatedResourceClientPartitionSplitTest { protected static final int TIMEOUT = 120000; @@ -145,8 +145,8 @@ public void partitionSplit_RefreshCache_Read(ConsistencyLevel consistencyLevel, request.requestContext.resolvedPartitionKeyRange = partitionKeyRangeWithId(partitionKeyRangeIdBeforeSplit); request.getHeaders().put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, consistencyLevel.toString()); - Func1> prepareRequestAsyncDelegate = null; - Single storeResponseObs = resourceClient.invokeAsync(request, prepareRequestAsyncDelegate); + Function> prepareRequestAsyncDelegate = null; + Mono storeResponseObs = resourceClient.invokeAsync(request, prepareRequestAsyncDelegate); if (partitionIsSplitting < Integer.MAX_VALUE) { @@ -164,50 +164,50 @@ public void partitionSplit_RefreshCache_Read(ConsistencyLevel consistencyLevel, } } - public static void validateSuccess(Single> single, + public static void validateSuccess(Mono> single, MultiStoreResultValidator validator) { validateSuccess(single, validator, TIMEOUT); } - public static void validateSuccess(Single> single, + public static void validateSuccess(Mono> single, MultiStoreResultValidator validator, long timeout) { TestSubscriber> testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResponseValidator validator) { validateSuccess(single, validator, TIMEOUT); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResponseValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public static void validateFailure(Single single, FailureValidator validator, long timeout) { + public static void validateFailure(Mono single, FailureValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + Assertions.assertThat(testSubscriber.errorCount()).isEqualTo(1); + validator.validate(testSubscriber.errors().get(0)); } private PartitionKeyRange partitionKeyRangeWithId(String id) { diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java index 61da80e08983e..fa63170e95ed2 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java @@ -31,13 +31,13 @@ import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.rx.FailureValidator; +import io.reactivex.subscribers.TestSubscriber; import org.assertj.core.api.Assertions; import org.mockito.Matchers; import org.mockito.Mockito; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Single; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Mono; import java.util.concurrent.TimeUnit; @@ -71,22 +71,22 @@ public void invokeAsyncWithGoneException() { RxDocumentServiceRequest request = Mockito.spy(RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Document)); Mockito.when(addressResolver.resolveAsync(Matchers.any(), Matchers.anyBoolean())) - .thenReturn(Single.error(new GoneException())); - Single response = resourceClient.invokeAsync(request, null); + .thenReturn(Mono.error(new GoneException())); + Mono response = resourceClient.invokeAsync(request, null); validateFailure(response, validator, TIMEOUT); //method will fail 7 time (first try ,last try , and 5 retries within 30 sec(1,2,4,8,15 wait)) Mockito.verify(addressResolver, Mockito.times(7)).resolveAsync(Matchers.any(), Matchers.anyBoolean()); } - public static void validateFailure(Single single, FailureValidator validator, long timeout) { + public static void validateFailure(Mono single, FailureValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + Assertions.assertThat(testSubscriber.errorCount()).isEqualTo(1); + validator.validate(testSubscriber.errors().get(0)); } } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java index 4ff28b3431c77..5c3932ee9840e 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java @@ -61,15 +61,13 @@ import io.netty.handler.logging.LogLevel; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; +import io.reactivex.subscribers.TestSubscriber; import org.apache.commons.lang3.StringUtils; -import org.assertj.core.api.Assertions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Single; -import rx.Subscriber; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Mono; import java.net.ConnectException; import java.net.URI; @@ -83,6 +81,7 @@ import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; import static com.azure.data.cosmos.internal.HttpConstants.HttpMethods; import static com.azure.data.cosmos.internal.HttpConstants.SubStatusCodes; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @@ -647,27 +646,15 @@ public void verifyGoneResponseMapsToGoneException() throws Exception { builder.build() ); - final Single responseSingle = transportClient.invokeStoreAsync(physicalAddress, null, request); + final Mono responseMono = transportClient.invokeStoreAsync(physicalAddress, request); - responseSingle.toObservable().toBlocking().subscribe(new Subscriber() { - @Override - public void onCompleted() { - } - - @Override - public void onError(final Throwable error) { - final String format = "Expected %s, not %s"; - assertTrue(error instanceof GoneException, String.format(format, GoneException.class, error.getClass())); - final Throwable cause = error.getCause(); - if (cause != null) { - // assumption: cosmos isn't listening on 10251 - assertTrue(cause instanceof ConnectException, String.format(format, ConnectException.class, error.getClass())); - } - } - - @Override - public void onNext(final StoreResponse response) { - fail(String.format("Expected GoneException, not a StoreResponse: %s", response)); + responseMono.subscribe(response -> { }, error -> { + final String format = "Expected %s, not %s"; + assertTrue(error instanceof GoneException, String.format(format, GoneException.class, error.getClass())); + final Throwable cause = error.getCause(); + if (cause != null) { + // assumption: cosmos isn't listening on 10251 + assertTrue(cause instanceof ConnectException, String.format(format, ConnectException.class, error.getClass())); } }); @@ -717,15 +704,15 @@ public void verifyRequestFailures( try (final RntbdTransportClient client = getRntbdTransportClientUnderTest(userAgent, timeout, response)) { - final Single responseSingle; + final Mono responseMono; try { - responseSingle = client.invokeStoreAsync(physicalAddress, null, request); + responseMono = client.invokeStoreAsync(physicalAddress, request); } catch (final Exception error) { throw new AssertionError(String.format("%s: %s", error.getClass(), error)); } - this.validateFailure(responseSingle, builder.build()); + this.validateFailure(responseMono, builder.build()); } } @@ -750,21 +737,22 @@ private static RntbdTransportClient getRntbdTransportClientUnderTest( return new RntbdTransportClient(new FakeEndpoint.Provider(options, sslContext, expected)); } - private void validateFailure(final Single single, final FailureValidator validator) { - validateFailure(single, validator, requestTimeout.toMillis()); + private void validateFailure(final Mono responseMono, final FailureValidator validator) { + validateFailure(responseMono, validator, requestTimeout.toMillis()); } private static void validateFailure( - final Single single, final FailureValidator validator, final long timeout + final Mono mono, final FailureValidator validator, final long timeout ) { - final TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - Assertions.assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); + final TestSubscriber subscriber = new TestSubscriber<>(); + mono.subscribe(subscriber); + + subscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); + assertThat(subscriber.errorCount()).isEqualTo(1); + subscriber.assertSubscribed(); + subscriber.assertNoValues(); + validator.validate(subscriber.errors().get(0)); } // region Types diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java index 5bd7a1fac7838..ef286b6f78ab4 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java @@ -42,14 +42,14 @@ import com.azure.data.cosmos.internal.SessionContainer; import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.rx.FailureValidator; +import io.reactivex.subscribers.TestSubscriber; import org.apache.commons.lang3.StringUtils; import org.mockito.Matchers; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Test; -import rx.Single; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Mono; import java.net.URI; import java.net.URISyntaxException; @@ -77,12 +77,12 @@ public void addressCache() { IAddressResolver mockAddressCache = Mockito.mock(IAddressResolver.class); - Mockito.doReturn(Single.just(addressInformation)) + Mockito.doReturn(Mono.just(addressInformation)) .when(mockAddressCache) .resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.eq(false)); // validate that the mock works - AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).toBlocking().value(); + AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).block(); assertThat(addressInfo[0]).isEqualTo(addressInformation[0]); } @@ -119,7 +119,7 @@ public void transportClient() { srb.withHeader(WFConstants.BackendHeaders.LSN, "50"); // setup mock transport client - Mockito.doReturn(Single.just(srb.build())) + Mockito.doReturn(Mono.just(srb.build())) .when(mockTransportClient) .invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[0].getPhysicalUri())), @@ -128,7 +128,7 @@ public void transportClient() { // get response from mock object - StoreResponse response = mockTransportClient.invokeResourceOperationAsync(URI.create(addressInformation[0].getPhysicalUri()), entity).toBlocking().value(); + StoreResponse response = mockTransportClient.invokeResourceOperationAsync(URI.create(addressInformation[0].getPhysicalUri()), entity).block(); // validate that the LSN matches // validate that the ActivityId Matches @@ -154,20 +154,20 @@ private TransportClient getMockTransportClientDuringUpgrade(AddressInformation[] .build(); // setup mock transport client for the first replica - Mockito.doReturn(Single.just(mockStoreResponseFast)) + Mockito.doReturn(Mono.just(mockStoreResponseFast)) .when(mockTransportClient) .invokeResourceOperationAsync(Mockito.eq(URI.create(addressInformation[0].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); // setup mock transport client with a sequence of outputs - Mockito.doReturn(Single.just(mockStoreResponseFast)) // initial read response - .doReturn(Single.just(mockStoreResponseFast)) // barrier retry, count 1 - .doReturn(Single.just(mockStoreResponseFast)) // barrier retry, count 2 - .doReturn(Single.error(new InvalidPartitionException())) // throw invalid partition exception to simulate collection recreate with same name - .doReturn(Single.just(mockStoreResponseFast)) // new read - .doReturn(Single.just(mockStoreResponseFast)) // subsequent barriers - .doReturn(Single.just(mockStoreResponseFast)) - .doReturn(Single.just(mockStoreResponseFast)) + Mockito.doReturn(Mono.just(mockStoreResponseFast)) // initial read response + .doReturn(Mono.just(mockStoreResponseFast)) // barrier retry, count 1 + .doReturn(Mono.just(mockStoreResponseFast)) // barrier retry, count 2 + .doReturn(Mono.error(new InvalidPartitionException())) // throw invalid partition exception to simulate collection recreate with same name + .doReturn(Mono.just(mockStoreResponseFast)) // new read + .doReturn(Mono.just(mockStoreResponseFast)) // subsequent barriers + .doReturn(Mono.just(mockStoreResponseFast)) + .doReturn(Mono.just(mockStoreResponseFast)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[1].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); @@ -187,7 +187,7 @@ private TransportClient getMockTransportClientDuringUpgrade(AddressInformation[] // 2nd time: returns InvalidPartitionException // initial read response - Mockito.doAnswer((params) -> Single.just(queueOfResponses.poll())) + Mockito.doAnswer((params) -> Mono.just(queueOfResponses.poll())) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[2].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); @@ -253,26 +253,26 @@ private TransportClient getMockTransportClientForGlobalStrongReads(AddressInform if(result == ReadQuorumResultKind.QuorumMet) { // setup mock transport client for the first replica - Mockito.doReturn(Single.just(mockStoreResponse5)) + Mockito.doReturn(Mono.just(mockStoreResponse5)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[0].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); - Mockito.doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse5)) + Mockito.doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse5)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[1].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); - Mockito.doReturn(Single.just(mockStoreResponse2)) - .doReturn(Single.just(mockStoreResponse2)) - .doReturn(Single.just(mockStoreResponse2)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse4)) - .doReturn(Single.just(mockStoreResponse5)) + Mockito.doReturn(Mono.just(mockStoreResponse2)) + .doReturn(Mono.just(mockStoreResponse2)) + .doReturn(Mono.just(mockStoreResponse2)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse4)) + .doReturn(Mono.just(mockStoreResponse5)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[2].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); @@ -280,32 +280,32 @@ private TransportClient getMockTransportClientForGlobalStrongReads(AddressInform if (result == ReadQuorumResultKind.QuorumSelected) { // setup mock transport client for the first replica - Mockito.doReturn(Single.just(mockStoreResponse2)) + Mockito.doReturn(Mono.just(mockStoreResponse2)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[0].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); // setup mock transport client with a sequence of outputs - Mockito.doReturn(Single.just(mockStoreResponse1)) + Mockito.doReturn(Mono.just(mockStoreResponse1)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[1].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); // setup mock transport client with a sequence of outputs - Mockito.doReturn(Single.just(mockStoreResponse2)) + Mockito.doReturn(Mono.just(mockStoreResponse2)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[2].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); } else if (result == ReadQuorumResultKind.QuorumNotSelected) { // setup mock transport client for the first replica - Mockito.doReturn(Single.just(mockStoreResponse5)) + Mockito.doReturn(Mono.just(mockStoreResponse5)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[0].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); - Mockito.doReturn(Single.just(mockStoreResponse5)) + Mockito.doReturn(Mono.just(mockStoreResponse5)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[1].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); - Mockito.doReturn(Single.error(new GoneException("test"))) + Mockito.doReturn(Mono.error(new GoneException("test"))) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[2].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); } @@ -381,21 +381,21 @@ private TransportClient getMockTransportClientForGlobalStrongWrites( for (int i = 0; i < addressInformation.length; i++) { if (i == indexOfCaughtUpReplica) { - Mockito.doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(finalResponse)) + Mockito.doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(finalResponse)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[i].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); } else { - Mockito.doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) - .doReturn(Single.just(mockStoreResponse1)) + Mockito.doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) + .doReturn(Mono.just(mockStoreResponse1)) .when(mockTransportClient).invokeResourceOperationAsync( Mockito.eq(URI.create(addressInformation[i].getPhysicalUri())), Mockito.any(RxDocumentServiceRequest.class)); } @@ -437,10 +437,10 @@ private IAddressResolver getMockAddressCache(AddressInformation[] addressInforma // AddressCache can be mocked. IAddressResolver mockAddressCache = Mockito.mock(IAddressResolver.class); - Mockito.doReturn(Single.just(addressInformation)).when(mockAddressCache) + Mockito.doReturn(Mono.just(addressInformation)).when(mockAddressCache) .resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.eq(false) /*forceRefresh*/); - Mockito.doReturn(Single.just(new AddressInformation[0])).when(mockAddressCache) + Mockito.doReturn(Mono.just(new AddressInformation[0])).when(mockAddressCache) .resolveAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.eq(true) /*forceRefresh*/); return mockAddressCache; @@ -473,12 +473,12 @@ public void storeReaderBarrier() { IAddressResolver mockAddressCache = getMockAddressCache(addressInformation); // validate that the mock works - AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).toBlocking().value(); + AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).block(); assertThat(addressInfo[0]).isEqualTo(addressInformation[0]); AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.TCP); - URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false /*forceAddressRefresh*/).toBlocking().value(); + URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false /*forceAddressRefresh*/).block(); // check if the address return from Address Selector matches the original address info assertThat(primaryAddress.toString()).isEqualTo(addressInformation[0].getPhysicalUri()); @@ -487,7 +487,7 @@ public void storeReaderBarrier() { TransportClient mockTransportClient = getMockTransportClientDuringUpgrade(addressInformation); // get response from mock object - StoreResponse response = mockTransportClient.invokeResourceOperationAsync(URI.create(addressInformation[0].getPhysicalUri()), entity).toBlocking().value(); + StoreResponse response = mockTransportClient.invokeResourceOperationAsync(URI.create(addressInformation[0].getPhysicalUri()), entity).block(); // validate that the LSN matches assertThat(response.getLSN()).isEqualTo(50); @@ -515,61 +515,61 @@ public void storeReaderBarrier() { replicaCountToRead, true /*requiresValidLSN*/, false /*useSessionToken*/, - ReadMode.Strong).toBlocking().value(); + ReadMode.Strong).block(); // make sure we got 2 responses from the store reader assertThat(result).hasSize(2); } - public static void validateSuccess(Single> single, + public static void validateSuccess(Mono> single, MultiStoreResultValidator validator) { validateSuccess(single, validator, 10000); } - public static void validateSuccess(Single> single, + public static void validateSuccess(Mono> single, MultiStoreResultValidator validator, long timeout) { TestSubscriber> testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResultValidator validator) { validateSuccess(single, validator, 10000); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResultValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public static void validateException(Single single, + public static void validateException(Mono single, FailureValidator validator) { validateException(single, validator, 10000); } - public static void validateException(Single single, + public static void validateException(Mono single, FailureValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + assertThat(testSubscriber.errorCount()).isEqualTo(1); + validator.validate(testSubscriber.errors().get(0)); } /** @@ -602,11 +602,11 @@ public void storeClient() throws URISyntaxException { IAddressResolver mockAddressCache = getMockAddressCache(addressInformations); // validate that the mock works - AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).toBlocking().value(); + AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).block(); assertThat(addressInfo[0]).isEqualTo(addressInformations[0]); AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.TCP); - URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false).toBlocking().value(); + URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false).block(); // check if the address return from Address Selector matches the original address info assertThat(primaryAddress.toString()).isEqualTo(addressInformations[0].getPhysicalUri()); @@ -615,7 +615,7 @@ public void storeClient() throws URISyntaxException { TransportClient mockTransportClient = getMockTransportClientDuringUpgrade(addressInformations); // get response from mock object - StoreResponse response = mockTransportClient.invokeResourceOperationAsync(new URI(addressInformations[0].getPhysicalUri()), entity).toBlocking().value(); + StoreResponse response = mockTransportClient.invokeResourceOperationAsync(new URI(addressInformations[0].getPhysicalUri()), entity).block(); // validate that the LSN matches assertThat(response.getLSN()).isEqualTo(50); @@ -643,8 +643,8 @@ public void storeClient() throws URISyntaxException { StoreClient storeClient = new StoreClient(new Configs(),mockAddressCache, sessionContainer, mockServiceConfigReader, mockAuthorizationTokenProvider, mockTransportClient, false); ServerStoreModel storeModel = new ServerStoreModel(storeClient); - Single result = storeModel.processMessage(entity).toSingle(); - result.toBlocking().value(); + Mono result = storeModel.processMessage(entity).single(); + result.block(); // if we have reached this point, there was a successful request. // validate if the target identity has been cleared out. @@ -690,11 +690,11 @@ public void globalStrongConsistentWrite() { IAddressResolver mockAddressCache = getMockAddressCache(addressInformations); // validate that the mock works - AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).toBlocking().value(); + AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).block(); assertThat(addressInformations[0]).isEqualTo(addressInfo[0]); AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.TCP); - URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false).toBlocking().value(); + URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false).block(); // check if the address return from Address Selector matches the original address info assertThat(primaryAddress.toString()).isEqualTo(addressInformations[0].getPhysicalUri()); @@ -711,14 +711,14 @@ public void globalStrongConsistentWrite() { TransportClient mockTransportClient = getMockTransportClientForGlobalStrongWrites(addressInformations, i, false, false, false); StoreReader storeReader = new StoreReader(mockTransportClient, addressSelector, sessionContainer); ConsistencyWriter consistencyWriter = new ConsistencyWriter(addressSelector, sessionContainer, mockTransportClient, mockAuthorizationTokenProvider, serviceConfigurationReader, false); - StoreResponse response = consistencyWriter.writeAsync(entity, new TimeoutHelper(Duration.ofSeconds(30)), false).toBlocking().value(); + StoreResponse response = consistencyWriter.writeAsync(entity, new TimeoutHelper(Duration.ofSeconds(30)), false).block(); assertThat(response.getLSN()).isEqualTo(100); //globalCommittedLsn never catches up in this case mockTransportClient = getMockTransportClientForGlobalStrongWrites(addressInformations, i, true, false, false); consistencyWriter = new ConsistencyWriter(addressSelector, sessionContainer, mockTransportClient, mockAuthorizationTokenProvider, serviceConfigurationReader, false); try { - response = consistencyWriter.writeAsync(entity, new TimeoutHelper(Duration.ofSeconds(30)), false).toBlocking().value(); + response = consistencyWriter.writeAsync(entity, new TimeoutHelper(Duration.ofSeconds(30)), false).block(); // fail("it should throw exception"); } catch (Exception e) { } @@ -726,20 +726,20 @@ public void globalStrongConsistentWrite() { mockTransportClient = getMockTransportClientForGlobalStrongWrites(addressInformations, i, false, true, false); storeReader = new StoreReader(mockTransportClient, addressSelector, sessionContainer); consistencyWriter = new ConsistencyWriter(addressSelector, sessionContainer, mockTransportClient, mockAuthorizationTokenProvider, serviceConfigurationReader, false); - response = consistencyWriter.writeAsync(entity, new TimeoutHelper(Duration.ofSeconds(30)), false).toBlocking().value(); + response = consistencyWriter.writeAsync(entity, new TimeoutHelper(Duration.ofSeconds(30)), false).block(); assertThat(response.getLSN()).isEqualTo(100); mockTransportClient = getMockTransportClientForGlobalStrongWrites(addressInformations, i, false, true, true); storeReader = new StoreReader(mockTransportClient, addressSelector, sessionContainer); consistencyWriter = new ConsistencyWriter(addressSelector, sessionContainer, mockTransportClient, mockAuthorizationTokenProvider, serviceConfigurationReader, false); - response = consistencyWriter.writeAsync(entity, new TimeoutHelper(Duration.ofSeconds(30)), false).toBlocking().value(); + response = consistencyWriter.writeAsync(entity, new TimeoutHelper(Duration.ofSeconds(30)), false).block(); assertThat(response.getLSN()).isEqualTo(100); mockTransportClient = getMockTransportClientForGlobalStrongWrites(addressInformations, i, false, false, true); storeReader = new StoreReader(mockTransportClient, addressSelector, sessionContainer); consistencyWriter = new ConsistencyWriter(addressSelector, sessionContainer, mockTransportClient, mockAuthorizationTokenProvider, serviceConfigurationReader, false); - response = consistencyWriter.writeAsync(entity, new TimeoutHelper(Duration.ofSeconds(30)), false).toBlocking().value(); + response = consistencyWriter.writeAsync(entity, new TimeoutHelper(Duration.ofSeconds(30)), false).block(); assertThat(response.getLSN()).isEqualTo(100); } @@ -776,11 +776,11 @@ public void globalStrongConsistency() { IAddressResolver mockAddressCache = getMockAddressCache(addressInformations); // validate that the mock works - AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).toBlocking().value(); + AddressInformation[] addressInfo = mockAddressCache.resolveAsync(entity, false).block(); assertThat(addressInfo[0]).isEqualTo(addressInformations[0]); AddressSelector addressSelector = new AddressSelector(mockAddressCache, Protocol.TCP); - URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false).toBlocking().value(); + URI primaryAddress = addressSelector.resolvePrimaryUriAsync(entity, false).block(); // check if the address return from Address Selector matches the original address info assertThat(primaryAddress.toString()).isEqualTo(addressInformations[0].getPhysicalUri()); @@ -809,7 +809,7 @@ public void globalStrongConsistency() { entity.requestContext.originalRequestConsistencyLevel = ConsistencyLevel.STRONG; - StoreResponse result = reader.readStrongAsync(entity, 2, ReadMode.Strong).toBlocking().value(); + StoreResponse result = reader.readStrongAsync(entity, 2, ReadMode.Strong).block(); assertThat(result.getLSN()).isEqualTo(100); String globalCommitedLSN = result.getHeaderValue(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN); @@ -846,7 +846,7 @@ public void globalStrongConsistency() { entity.requestContext.quorumSelectedLSN = -1; entity.requestContext.globalCommittedSelectedLSN = -1; try { - StoreResponse result = reader.readStrongAsync(entity, 2, ReadMode.Strong).toBlocking().value(); + StoreResponse result = reader.readStrongAsync(entity, 2, ReadMode.Strong).block(); assertThat(false).isTrue(); } catch (Exception ex) { if (ex.getCause() instanceof GoneException) { @@ -887,7 +887,7 @@ public void globalStrongConsistency() { entity.requestContext.originalRequestConsistencyLevel = ConsistencyLevel.STRONG; entity.requestContext.performLocalRefreshOnGoneException = true; - StoreResponse result = reader.readStrongAsync(entity, 2, ReadMode.Strong).toBlocking().value(); + StoreResponse result = reader.readStrongAsync(entity, 2, ReadMode.Strong).block(); assertThat(result.getLSN()).isEqualTo(100); String globalCommitedLSN; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java index 9b9da76166cd7..87e2cf8d05866 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java @@ -41,15 +41,13 @@ import com.azure.data.cosmos.internal.VectorSessionToken; import com.azure.data.cosmos.rx.FailureValidator; import com.google.common.collect.ImmutableList; +import io.reactivex.subscribers.TestSubscriber; import org.assertj.core.api.AssertionsForClassTypes; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Single; -import rx.observers.TestSubscriber; -import rx.subjects.PublishSubject; +import reactor.core.publisher.DirectProcessor; +import reactor.core.publisher.Mono; import java.net.URI; import java.util.List; @@ -79,35 +77,27 @@ public void startBackgroundAddressRefresh() throws Exception { StoreReader storeReader = new StoreReader(transportClient, addressSelector, sessionContainer); CyclicBarrier b = new CyclicBarrier(2); - PublishSubject> subject = PublishSubject.create(); + DirectProcessor> subject = DirectProcessor.create(); CountDownLatch c = new CountDownLatch(1); List uris = ImmutableList.of(URI.create("https://localhost:5050"), URI.create("https://localhost:5051"), URI.create("https://localhost:50502"), URI.create("https://localhost:5053")); - Mockito.doAnswer(new Answer() { + Mockito.doAnswer(invocationOnMock -> subject.single().doOnSuccess(x -> c.countDown()).doAfterTerminate(() -> new Thread() { @Override - public Single> answer(InvocationOnMock invocationOnMock) throws Throwable { - - return subject.toSingle().doOnSuccess(x -> c.countDown()).doAfterTerminate(() -> { - new Thread() { - @Override - public void run() { - try { - b.await(); - } catch (Exception e) { - - } - } - }.start(); - }); + public void run() { + try { + b.await(); + } catch (Exception e) { + e.printStackTrace(); + } } - }).when(addressSelector).resolveAllUriAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.eq(true), Mockito.eq(true)); + }.start())).when(addressSelector).resolveAllUriAsync(Mockito.any(RxDocumentServiceRequest.class), Mockito.eq(true), Mockito.eq(true)); RxDocumentServiceRequest request = Mockito.mock(RxDocumentServiceRequest.class); storeReader.startBackgroundAddressRefresh(request); subject.onNext(uris); - subject.onCompleted(); + subject.onComplete(); TimeUnit.MILLISECONDS.sleep(100); AssertionsForClassTypes.assertThat(c.getCount()).isEqualTo(0); @@ -180,7 +170,7 @@ public void exception(Exception ex, Class klass, int expectedStatusCo dsr.requestContext = Mockito.mock(DocumentServiceRequestContext.class); dsr.requestContext.timeoutHelper = timeoutHelper; dsr.requestContext.resolvedPartitionKeyRange = partitionKeyRangeWithId("1"); - Single> res = storeReader.readMultipleReplicaAsync(dsr, true, 3, true, true, ReadMode.Strong); + Mono> res = storeReader.readMultipleReplicaAsync(dsr, true, 3, true, true, ReadMode.Strong); FailureValidator failureValidator = FailureValidator.builder() .instanceOf(klass) @@ -191,9 +181,9 @@ public void exception(Exception ex, Class klass, int expectedStatusCo TestSubscriber> subscriber = new TestSubscriber<>(); res.subscribe(subscriber); subscriber.awaitTerminalEvent(); - subscriber.assertNotCompleted(); - assertThat(subscriber.getOnErrorEvents()).hasSize(1); - failureValidator.validate(subscriber.getOnErrorEvents().get(0)); + subscriber.assertNotComplete(); + assertThat(subscriber.errorCount()).isEqualTo(1); + failureValidator.validate(subscriber.errors().get(0)); } /** @@ -258,7 +248,7 @@ public void sessionNotAvailableFromSomeReplicas_FindReplicaSatisfyingRequestedSe Mockito.doReturn(sessionToken.v).when(sessionContainer).resolvePartitionLocalSessionToken(Mockito.eq(dsr), Mockito.anyString()); - Single> readResult = storeReader.readMultipleReplicaAsync( + Mono> readResult = storeReader.readMultipleReplicaAsync( dsr, /* includePrimary */ true, /* replicaCountToRead */ 1, @@ -335,7 +325,7 @@ public void sessionRead_LegitimateNotFound() { Mockito.doReturn(sessionToken.v).when(sessionContainer).resolvePartitionLocalSessionToken(Mockito.eq(dsr), Mockito.anyString()); - Single> readResult = storeReader.readMultipleReplicaAsync( + Mono> readResult = storeReader.readMultipleReplicaAsync( dsr, /* includePrimary */ true, /* replicaCountToRead */ 1, @@ -404,7 +394,7 @@ public void sessionRead_ReplicasDoNotHaveTheRequestedLSN_NoResult() { Mockito.doReturn(sessionToken.v).when(sessionContainer).resolvePartitionLocalSessionToken(Mockito.eq(dsr), Mockito.anyString()); - Single> readResult = storeReader.readMultipleReplicaAsync( + Mono> readResult = storeReader.readMultipleReplicaAsync( dsr, /* includePrimary */ true, /* replicaCountToRead */ 1, @@ -466,7 +456,7 @@ public void requestRateTooLarge_BubbleUp() { Mockito.doReturn(sessionToken.v).when(sessionContainer).resolvePartitionLocalSessionToken(Mockito.eq(dsr), Mockito.anyString()); - Single> readResult = storeReader.readMultipleReplicaAsync( + Mono> readResult = storeReader.readMultipleReplicaAsync( dsr, /* includePrimary */ true, /* replicaCountToRead */ 1, @@ -499,15 +489,15 @@ public void readPrimaryAsync() { request.requestContext.resolvedPartitionKeyRange = partitionKeyRangeWithId("12"); request.requestContext.requestChargeTracker = new RequestChargeTracker(); - Mockito.doReturn(Single.just(primaryURI)).when(addressSelector).resolvePrimaryUriAsync( + Mockito.doReturn(Mono.just(primaryURI)).when(addressSelector).resolvePrimaryUriAsync( Mockito.eq(request) , Mockito.eq(false)); StoreResponse storeResponse = Mockito.mock(StoreResponse.class); - Mockito.doReturn(Single.just(storeResponse)).when(transportClient).invokeResourceOperationAsync(Mockito.eq(primaryURI), Mockito.eq(request)); + Mockito.doReturn(Mono.just(storeResponse)).when(transportClient).invokeResourceOperationAsync(Mockito.eq(primaryURI), Mockito.eq(request)); StoreReader storeReader = new StoreReader(transportClient, addressSelector, sessionContainer); - Single readResult = storeReader.readPrimaryAsync(request, true, true); + Mono readResult = storeReader.readPrimaryAsync(request, true, true); StoreResultValidator validator = StoreResultValidator.create() .withStoreResponse(StoreResponseValidator.create().isSameAs(storeResponse).build()) .build(); @@ -530,12 +520,12 @@ public void readPrimaryAsync_GoneFromReplica() { request.requestContext.resolvedPartitionKeyRange = partitionKeyRangeWithId("12"); request.requestContext.requestChargeTracker = new RequestChargeTracker(); - Mockito.doReturn(Single.just(primaryURI)).when(addressSelector).resolvePrimaryUriAsync( + Mockito.doReturn(Mono.just(primaryURI)).when(addressSelector).resolvePrimaryUriAsync( Mockito.eq(request) , Mockito.eq(false)); - Mockito.doReturn(Single.error(ExceptionBuilder.create().asGoneException())).when(transportClient).invokeResourceOperationAsync(Mockito.eq(primaryURI), Mockito.eq(request)); + Mockito.doReturn(Mono.error(ExceptionBuilder.create().asGoneException())).when(transportClient).invokeResourceOperationAsync(Mockito.eq(primaryURI), Mockito.eq(request)); StoreReader storeReader = new StoreReader(transportClient, addressSelector, sessionContainer); - Single readResult = storeReader.readPrimaryAsync(request, true, true); + Mono readResult = storeReader.readPrimaryAsync(request, true, true); FailureValidator validator = FailureValidator.builder().instanceOf(GoneException.class).build(); validateException(readResult, validator); @@ -558,15 +548,15 @@ public void readPrimaryAsync_GoneExceptionOnTimeout() { request.requestContext.resolvedPartitionKeyRange = partitionKeyRangeWithId("12"); request.requestContext.requestChargeTracker = new RequestChargeTracker(); - Mockito.doReturn(Single.just(primaryURI)).when(addressSelector).resolvePrimaryUriAsync( + Mockito.doReturn(Mono.just(primaryURI)).when(addressSelector).resolvePrimaryUriAsync( Mockito.eq(request) , Mockito.eq(false)); StoreResponse storeResponse = Mockito.mock(StoreResponse.class); - Mockito.doReturn(Single.just(storeResponse)).when(transportClient).invokeResourceOperationAsync(Mockito.eq(primaryURI), Mockito.eq(request)); + Mockito.doReturn(Mono.just(storeResponse)).when(transportClient).invokeResourceOperationAsync(Mockito.eq(primaryURI), Mockito.eq(request)); StoreReader storeReader = new StoreReader(transportClient, addressSelector, sessionContainer); - Single readResult = storeReader.readPrimaryAsync(request, true, true); + Mono readResult = storeReader.readPrimaryAsync(request, true, true); FailureValidator validator = FailureValidator.builder().instanceOf(GoneException.class).build(); validateException(readResult, validator); } @@ -643,7 +633,7 @@ public void readPrimaryAsync_RetryOnPrimaryReplicaMove(Exception firstExceptionF .withPrimaryReplicaMove(primaryURIPriorToRefresh, primaryURIAfterRefresh).build(); StoreReader storeReader = new StoreReader(transportClientWrapper.transportClient, addressSelectorWrapper.addressSelector, sessionContainer); - Single readResult = storeReader.readPrimaryAsync(request, true, true); + Mono readResult = storeReader.readPrimaryAsync(request, true, true); if (failureFromSingle == null) { StoreResultValidator validator; @@ -740,7 +730,7 @@ public void readMultipleReplicasAsync(boolean includePrimary, int replicaCountTo StoreReader storeReader = new StoreReader(transportClientWrapper.transportClient, addressSelectorWrapper.addressSelector, sessionContainer); - Single> readResult = storeReader.readMultipleReplicaAsync(request, includePrimary, replicaCountToRead, true, true, readMode); + Mono> readResult = storeReader.readMultipleReplicaAsync(request, includePrimary, replicaCountToRead, true, true, readMode); long expectedMinLsn = responseList @@ -772,53 +762,53 @@ public void readMultipleReplicasAsync(boolean includePrimary, int replicaCountTo .verifyTotalInvocations(1); } - public static void validateSuccess(Single> single, + public static void validateSuccess(Mono> single, MultiStoreResultValidator validator) { validateSuccess(single, validator, 10000); } - public static void validateSuccess(Single> single, + public static void validateSuccess(Mono> single, MultiStoreResultValidator validator, long timeout) { TestSubscriber> testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.flux().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResultValidator validator) { validateSuccess(single, validator, 10000); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, StoreResultValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public static void validateException(Single single, + public static void validateException(Mono single, FailureValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.flux().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + assertThat(testSubscriber.errorCount()).isEqualTo(1); + validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } - public static void validateException(Single single, + public static void validateException(Mono single, FailureValidator validator) { validateException(single, validator, TIMEOUT); } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java index f5ca74b627471..659058e1d20fd 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.tuple.Pair; -import rx.Single; +import reactor.core.publisher.Mono; import java.lang.reflect.Method; import java.util.ArrayList; @@ -43,7 +43,7 @@ public StoreReaderUnderTest(TransportClient transportClient, AddressSelector add } @Override - public Single> readMultipleReplicaAsync(RxDocumentServiceRequest entity, boolean includePrimary, int replicaCountToRead, boolean requiresValidLsn, boolean useSessionToken, ReadMode readMode) { + public Mono> readMultipleReplicaAsync(RxDocumentServiceRequest entity, boolean includePrimary, int replicaCountToRead, boolean requiresValidLsn, boolean useSessionToken, ReadMode readMode) { Method method = new Object(){}.getClass().getEnclosingMethod(); ImmutableList list = ImmutableList.of(entity, includePrimary, replicaCountToRead, requiresValidLsn, useSessionToken, readMode); invocations.add(Pair.of(method, list)); @@ -52,7 +52,7 @@ public Single> readMultipleReplicaAsync(RxDocumentServiceReque } @Override - public Single> readMultipleReplicaAsync(RxDocumentServiceRequest entity, boolean includePrimary, int replicaCountToRead, boolean requiresValidLsn, boolean useSessionToken, ReadMode readMode, boolean checkMinLSN, boolean forceReadAll) { + public Mono> readMultipleReplicaAsync(RxDocumentServiceRequest entity, boolean includePrimary, int replicaCountToRead, boolean requiresValidLsn, boolean useSessionToken, ReadMode readMode, boolean checkMinLSN, boolean forceReadAll) { Method method = new Object(){}.getClass().getEnclosingMethod(); ImmutableList list = ImmutableList.of(entity, includePrimary, replicaCountToRead, requiresValidLsn, useSessionToken, readMode, checkMinLSN, forceReadAll); invocations.add(Pair.of(method, list)); @@ -60,7 +60,7 @@ public Single> readMultipleReplicaAsync(RxDocumentServiceReque } @Override - public Single readPrimaryAsync(RxDocumentServiceRequest entity, boolean requiresValidLsn, boolean useSessionToken) { + public Mono readPrimaryAsync(RxDocumentServiceRequest entity, boolean requiresValidLsn, boolean useSessionToken) { Method method = new Object(){}.getClass().getEnclosingMethod(); ImmutableList list = ImmutableList.of(entity, requiresValidLsn, useSessionToken); invocations.add(Pair.of(method, list)); diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TransportClientWrapper.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TransportClientWrapper.java index ad62c85a2e960..6d0f54a273305 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TransportClientWrapper.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TransportClientWrapper.java @@ -32,7 +32,7 @@ import org.mockito.invocation.InvocationOnMock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; +import reactor.core.publisher.Mono; import java.net.URI; import java.util.ArrayList; @@ -142,7 +142,7 @@ public TransportClientWrapper build() { Function2WithCheckedException function = responseFunctionDictionary.get(physicalUri); if (function == null) { valid.set(false); - return Single.error(new IllegalStateException("no registered function for replica " + physicalUri)); + return Mono.error(new IllegalStateException("no registered function for replica " + physicalUri)); } int current; synchronized (transportClient) { @@ -158,9 +158,9 @@ public TransportClientWrapper build() { } try { - return Single.just(function.apply(current, request)); + return Mono.just(function.apply(current, request)); } catch (Exception e) { - return Single.error(e); + return Mono.error(e); } }).when(transportClient).invokeResourceOperationAsync(Mockito.any(URI.class), Mockito.any(RxDocumentServiceRequest.class)); @@ -199,14 +199,14 @@ public TransportClientWrapper build() { int current = i.getAndIncrement(); if (current >= list.size()) { valid.set(false); - return Single.error(new IllegalStateException()); + return Mono.error(new IllegalStateException()); } Object obj = list.get(current); StoreResponse response = Utils.as(obj, StoreResponse.class); if (response != null) { - return Single.just(response); + return Mono.just(response); } else { - return Single.error((Exception) obj); + return Mono.error((Exception) obj); } }).when(transportClient).invokeResourceOperationAsync(Mockito.any(URI.class), Mockito.any(RxDocumentServiceRequest.class)); @@ -307,7 +307,7 @@ public TransportClientWrapper build() { if (list == null || list.isEmpty()) { // unknown valid.set(false); - return Single.error(new IllegalStateException(tuple.toString())); + return Mono.error(new IllegalStateException(tuple.toString())); } Result result = list.get(0); @@ -316,9 +316,9 @@ public TransportClientWrapper build() { list.remove(0); } if (result.storeResponse != null) { - return Single.just(result.storeResponse); + return Mono.just(result.storeResponse); } else { - return Single.error(result.exception); + return Mono.error(result.exception); } }).when(transportClient).invokeResourceOperationAsync(Mockito.any(URI.class), Mockito.any(RxDocumentServiceRequest.class)); diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtilityTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtilityTest.java index 9badc630da439..039dfaddc1218 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtilityTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtilityTest.java @@ -26,7 +26,6 @@ import io.netty.channel.ChannelException; import io.netty.channel.ConnectTimeoutException; import io.netty.handler.timeout.ReadTimeoutException; -import io.reactivex.netty.client.PoolExhaustedException; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -74,9 +73,6 @@ public Object[][] exceptionToIsRetriable() { }, { new SocketTimeoutException(), false - }, - { - new PoolExhaustedException(), true } }; } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java index c651ed6584047..d6d80a7a4f7ec 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java @@ -27,26 +27,26 @@ import com.azure.data.cosmos.directconnectivity.StoreResponseBuilder; import com.azure.data.cosmos.directconnectivity.StoreResponseValidator; import com.azure.data.cosmos.internal.IRetryPolicy.ShouldRetryResult; +import io.reactivex.subscribers.TestSubscriber; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Single; -import rx.functions.Func1; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Mono; import java.time.Duration; import java.util.concurrent.TimeUnit; +import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; public class RetryUtilsTest { IRetryPolicy retryPolicy; - Func1, Single> callbackMethod; - Func1, Single> inBackoffAlternateCallbackMethod; + Function, Mono> callbackMethod; + Function, Mono> inBackoffAlternateCallbackMethod; private static final Duration minBackoffForInBackoffCallback = Duration.ofMillis(10); private static final int TIMEOUT = 30000; private static final Duration BACK_OFF_DURATION = Duration.ofMillis(20); @@ -55,8 +55,8 @@ public class RetryUtilsTest { @BeforeClass(groups = { "unit" }) public void beforeClass() throws Exception { retryPolicy = Mockito.mock(IRetryPolicy.class); - callbackMethod = Mockito.mock(Func1.class); - inBackoffAlternateCallbackMethod = Mockito.mock(Func1.class); + callbackMethod = Mockito.mock(Function.class); + inBackoffAlternateCallbackMethod = Mockito.mock(Function.class); storeResponse = getStoreResponse(); } @@ -66,10 +66,10 @@ public void beforeClass() throws Exception { */ @Test(groups = { "unit" }, timeOut = TIMEOUT) public void toRetryWithAlternateFuncWithNoRetry() { - Func1> onErrorFunc = RetryUtils.toRetryWithAlternateFunc(callbackMethod, + Function> onErrorFunc = RetryUtils.toRetryWithAlternateFunc(callbackMethod, retryPolicy, inBackoffAlternateCallbackMethod, minBackoffForInBackoffCallback); - Mockito.when(retryPolicy.shouldRetry(Matchers.any())).thenReturn(Single.just(ShouldRetryResult.noRetry())); - Single response = onErrorFunc.call(new GoneException()); + Mockito.when(retryPolicy.shouldRetry(Matchers.any())).thenReturn(Mono.just(ShouldRetryResult.noRetry())); + Mono response = onErrorFunc.apply(new GoneException()); validateFailure(response, TIMEOUT, GoneException.class); } @@ -80,17 +80,17 @@ public void toRetryWithAlternateFuncWithNoRetry() { */ @Test(groups = { "unit" }, timeOut = TIMEOUT) public void toRetryWithAlternateFuncTestingMethodOne() { - Func1> onErrorFunc = RetryUtils.toRetryWithAlternateFunc(callbackMethod, + Function> onErrorFunc = RetryUtils.toRetryWithAlternateFunc(callbackMethod, retryPolicy, null, minBackoffForInBackoffCallback); toggleMockFuncBtwFailureSuccess(callbackMethod); Mockito.when(retryPolicy.shouldRetry(Matchers.any())) - .thenReturn(Single.just(ShouldRetryResult.retryAfter(BACK_OFF_DURATION))); - Single response = onErrorFunc.call(new GoneException()); + .thenReturn(Mono.just(ShouldRetryResult.retryAfter(BACK_OFF_DURATION))); + Mono response = onErrorFunc.apply(new GoneException()); StoreResponseValidator validator = StoreResponseValidator.create().withStatus(storeResponse.getStatus()) .withContent(storeResponse.getResponseBody()).build(); validateSuccess(response, validator, TIMEOUT); - Mockito.verify(callbackMethod, Mockito.times(4)).call(Matchers.any()); + Mockito.verify(callbackMethod, Mockito.times(4)).apply(Matchers.any()); } /** @@ -100,53 +100,53 @@ public void toRetryWithAlternateFuncTestingMethodOne() { */ @Test(groups = { "unit" }, timeOut = TIMEOUT) public void toRetryWithAlternateFuncTestingMethodTwo() { - Func1> onErrorFunc = RetryUtils.toRetryWithAlternateFunc(callbackMethod, + Function> onErrorFunc = RetryUtils.toRetryWithAlternateFunc(callbackMethod, retryPolicy, inBackoffAlternateCallbackMethod, minBackoffForInBackoffCallback); - Mockito.when(callbackMethod.call(Matchers.any())).thenReturn(Single.error(new GoneException())); + Mockito.when(callbackMethod.apply(Matchers.any())).thenReturn(Mono.error(new GoneException())); toggleMockFuncBtwFailureSuccess(inBackoffAlternateCallbackMethod); Mockito.when(retryPolicy.shouldRetry(Matchers.any())) - .thenReturn(Single.just(ShouldRetryResult.retryAfter(BACK_OFF_DURATION))); - Single response = onErrorFunc.call(new GoneException()); + .thenReturn(Mono.just(ShouldRetryResult.retryAfter(BACK_OFF_DURATION))); + Mono response = onErrorFunc.apply(new GoneException()); StoreResponseValidator validator = StoreResponseValidator.create().withStatus(storeResponse.getStatus()) .withContent(storeResponse.getResponseBody()).build(); validateSuccess(response, validator, TIMEOUT); - Mockito.verify(inBackoffAlternateCallbackMethod, Mockito.times(4)).call(Matchers.any()); + Mockito.verify(inBackoffAlternateCallbackMethod, Mockito.times(4)).apply(Matchers.any()); } - private void validateFailure(Single single, long timeout, Class class1) { + private void validateFailure(Mono single, long timeout, Class class1) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - if (!(testSubscriber.getOnErrorEvents().get(0).getClass().equals(class1))) { - fail("Not expecting " + testSubscriber.getOnErrorEvents().get(0)); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + assertThat(testSubscriber.errorCount()).isEqualTo(1); + if (!(testSubscriber.getEvents().get(1).get(0).getClass().equals(class1))) { + fail("Not expecting " + testSubscriber.getEvents().get(1).get(0)); } } - private void validateSuccess(Single single, StoreResponseValidator validator, long timeout) { + private void validateSuccess(Mono single, StoreResponseValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - assertThat(testSubscriber.getOnNextEvents()).hasSize(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + assertThat(testSubscriber.valueCount()).isEqualTo(1); + validator.validate(testSubscriber.values().get(0)); } private void toggleMockFuncBtwFailureSuccess( - Func1, Single> method) { - Mockito.when(method.call(Matchers.any())).thenAnswer(new Answer>() { + Function, Mono> method) { + Mockito.when(method.apply(Matchers.any())).thenAnswer(new Answer>() { private int count = 0; @Override - public Single answer(InvocationOnMock invocation) throws Throwable { + public Mono answer(InvocationOnMock invocation) throws Throwable { if (count++ < 3) { - return Single.error(new GoneException()); + return Mono.error(new GoneException()); } - return Single.just(storeResponse); + return Mono.just(storeResponse); } }); } diff --git a/examples/pom.xml b/examples/pom.xml index 299b1f815143c..e8f52dac5361e 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -141,13 +141,6 @@ slf4j-log4j12 ${slf4j.version} - - - io.reactivex - rxjava-guava - ${rxjava-guava.version} - test - org.hamcrest hamcrest-all diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java b/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java index d82a72e6dcaa2..18e5f95c4e2ec 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java @@ -220,4 +220,4 @@ public void setDescription(String description) { this.description = description; } } -} +} \ No newline at end of file diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java index 4e602cf378a85..e20819277860a 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java @@ -28,8 +28,8 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.ResourceResponse; -import rx.Observable; -import rx.Single; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; public class Helpers { @@ -41,10 +41,10 @@ static public String createDatabaseUri(String databaseName) { return String.format("/dbs/%s", databaseName); } - static public Single createDatabaseIfNotExists(AsyncDocumentClient client, String databaseName) { + static public Mono createDatabaseIfNotExists(AsyncDocumentClient client, String databaseName) { return client.readDatabase("/dbs/" + databaseName, null) - .onErrorResumeNext( + .onErrorResume( e -> { if (e instanceof CosmosClientException) { CosmosClientException dce = (CosmosClientException) e; @@ -58,14 +58,14 @@ static public Single createDatabaseIfNotExists(AsyncDocumentClient cli } } - return Observable.error(e); + return Flux.error(e); } - ).map(ResourceResponse::getResource).toSingle(); + ).map(ResourceResponse::getResource).single(); } - static public Single createCollectionIfNotExists(AsyncDocumentClient client, String databaseName, String collectionName) { + static public Mono createCollectionIfNotExists(AsyncDocumentClient client, String databaseName, String collectionName) { return client.readCollection(createDocumentCollectionUri(databaseName, collectionName), null) - .onErrorResumeNext( + .onErrorResume( e -> { if (e instanceof CosmosClientException) { CosmosClientException dce = (CosmosClientException) e; @@ -79,14 +79,14 @@ static public Single createCollectionIfNotExists(AsyncDocume } } - return Observable.error(e); + return Flux.error(e); } - ).map(ResourceResponse::getResource).toSingle(); + ).map(ResourceResponse::getResource).single(); } - static public Single createCollectionIfNotExists(AsyncDocumentClient client, String databaseName, DocumentCollection collection) { + static public Mono createCollectionIfNotExists(AsyncDocumentClient client, String databaseName, DocumentCollection collection) { return client.readCollection(createDocumentCollectionUri(databaseName, collection.id()), null) - .onErrorResumeNext( + .onErrorResume( e -> { if (e instanceof CosmosClientException) { CosmosClientException dce = (CosmosClientException) e; @@ -97,8 +97,8 @@ static public Single createCollectionIfNotExists(AsyncDocume } } - return Observable.error(e); + return Flux.error(e); } - ).map(ResourceResponse::getResource).toSingle(); + ).map(ResourceResponse::getResource).single(); } } diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java index 3a77790ce968e..bb4df7cf23990 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java @@ -41,9 +41,9 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Scheduler; -import rx.schedulers.Schedulers; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Scheduler; +import reactor.core.scheduler.Schedulers; import java.util.ArrayList; import java.util.List; @@ -82,7 +82,7 @@ public ConflictWorker(String databaseName, String basicCollectionName, String ma this.udpCollectionName = udpCollectionName; this.executor = Executors.newFixedThreadPool(100); - this.schedulerForBlockingWork = Schedulers.from(executor); + this.schedulerForBlockingWork = Schedulers.fromExecutor(executor); } public void addClient(AsyncDocumentClient client) { @@ -91,13 +91,13 @@ public void addClient(AsyncDocumentClient client) { private DocumentCollection createCollectionIfNotExists(AsyncDocumentClient createClient, String databaseName, DocumentCollection collection) { return Helpers.createCollectionIfNotExists(createClient, this.databaseName, collection) - .subscribeOn(schedulerForBlockingWork).toBlocking().value(); + .subscribeOn(schedulerForBlockingWork).block(); } private DocumentCollection createCollectionIfNotExists(AsyncDocumentClient createClient, String databaseName, String collectionName) { return Helpers.createCollectionIfNotExists(createClient, this.databaseName, this.basicCollectionName) - .subscribeOn(schedulerForBlockingWork).toBlocking().value(); + .subscribeOn(schedulerForBlockingWork).block(); } private DocumentCollection getCollectionDefForManual(String id) { @@ -127,7 +127,7 @@ private DocumentCollection getCollectionDefForCustom(String id, String storedPro public void initialize() throws Exception { AsyncDocumentClient createClient = this.clients.get(0); - Helpers.createDatabaseIfNotExists(createClient, this.databaseName).subscribeOn(schedulerForBlockingWork).toBlocking().value(); + Helpers.createDatabaseIfNotExists(createClient, this.databaseName).subscribeOn(schedulerForBlockingWork).block(); DocumentCollection basic = createCollectionIfNotExists(createClient, this.databaseName, this.basicCollectionName); @@ -152,8 +152,8 @@ public void initialize() throws Exception { } - private T getResource(Observable> obs) { - return obs.subscribeOn(schedulerForBlockingWork).toBlocking().single().getResource(); + private T getResource(Flux> obs) { + return obs.subscribeOn(schedulerForBlockingWork).single().block().getResource(); } public void runManualConflict() throws Exception { @@ -193,7 +193,7 @@ public void runInsertConflictOnManual() throws Exception { do { logger.info("1) Performing conflicting insert across {} regions on {}", this.clients.size(), this.manualCollectionName); - ArrayList> insertTask = new ArrayList>(); + ArrayList> insertTask = new ArrayList<>(); Document conflictDocument = new Document(); conflictDocument.id(UUID.randomUUID().toString()); @@ -203,7 +203,7 @@ public void runInsertConflictOnManual() throws Exception { insertTask.add(this.tryInsertDocument(client, this.manualCollectionUri, conflictDocument, index++)); } - List conflictDocuments = Observable.merge(insertTask).toList().subscribeOn(schedulerForBlockingWork).toBlocking().single(); + List conflictDocuments = Flux.merge(insertTask).collectList().subscribeOn(schedulerForBlockingWork).single().block(); if (conflictDocuments.size() == this.clients.size()) { logger.info("2) Caused {} insert conflicts, verifying conflict resolution", conflictDocuments.size()); @@ -225,21 +225,21 @@ public void runUpdateConflictOnManual() throws Exception { conflictDocument = this.tryInsertDocument(clients.get(0), this.manualCollectionUri, conflictDocument, 0) - .firstOrDefault(null).toBlocking().first(); + .singleOrEmpty().block(); TimeUnit.SECONDS.sleep(1);//1 Second for write to sync. logger.info("1) Performing conflicting update across 3 regions on {}", this.manualCollectionName); - ArrayList> updateTask = new ArrayList>(); + ArrayList> updateTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { updateTask.add(this.tryUpdateDocument(client, this.manualCollectionUri, conflictDocument, index++)); } - List conflictDocuments = Observable.merge(updateTask).toList().toBlocking().single(); + List conflictDocuments = Flux.merge(updateTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} updated conflicts, verifying conflict resolution", conflictDocuments.size()); @@ -260,22 +260,22 @@ public void runDeleteConflictOnManual() throws Exception { conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.manualCollectionUri, conflictDocument, 0) - .firstOrDefault(null).toBlocking().first(); + .singleOrEmpty().block(); TimeUnit.SECONDS.sleep(10);//1 Second for write to sync. logger.info("1) Performing conflicting delete across 3 regions on {}", this.manualCollectionName); - ArrayList> deleteTask = new ArrayList>(); + ArrayList> deleteTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { deleteTask.add(this.tryDeleteDocument(client, this.manualCollectionUri, conflictDocument, index++)); } - List conflictDocuments = Observable.merge(deleteTask).toList() + List conflictDocuments = Flux.merge(deleteTask).collectList() .subscribeOn(schedulerForBlockingWork) - .toBlocking().single(); + .single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} delete conflicts, verifying conflict resolution", conflictDocuments.size()); @@ -295,7 +295,7 @@ public void runInsertConflictOnLWW() throws Exception { do { logger.info("Performing conflicting insert across 3 regions"); - ArrayList> insertTask = new ArrayList>(); + ArrayList> insertTask = new ArrayList<>(); Document conflictDocument = new Document(); conflictDocument.id(UUID.randomUUID().toString()); @@ -305,7 +305,7 @@ public void runInsertConflictOnLWW() throws Exception { insertTask.add(this.tryInsertDocument(client, this.lwwCollectionUri, conflictDocument, index++)); } - List conflictDocuments = Observable.merge(insertTask).toList().toBlocking().single(); + List conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { @@ -326,21 +326,21 @@ public void runUpdateConflictOnLWW() throws Exception { conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.lwwCollectionUri, conflictDocument, 0) - .firstOrDefault(null).toBlocking().first(); + .singleOrEmpty().block(); TimeUnit.SECONDS.sleep(1); //1 Second for write to sync. logger.info("1) Performing conflicting update across {} regions on {}", this.clients.size(), this.lwwCollectionUri); - ArrayList> insertTask = new ArrayList>(); + ArrayList> insertTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { insertTask.add(this.tryUpdateDocument(client, this.lwwCollectionUri, conflictDocument, index++)); } - List conflictDocuments = Observable.merge(insertTask).toList().toBlocking().single(); + List conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { @@ -361,14 +361,14 @@ public void runDeleteConflictOnLWW() throws Exception { conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.lwwCollectionUri, conflictDocument, 0) - .firstOrDefault(null).toBlocking().first(); + .singleOrEmpty().block(); TimeUnit.SECONDS.sleep(1); //1 Second for write to sync. logger.info("1) Performing conflicting delete across {} regions on {}", this.clients.size(), this.lwwCollectionUri); - ArrayList> insertTask = new ArrayList>(); + ArrayList> insertTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { @@ -380,7 +380,7 @@ public void runDeleteConflictOnLWW() throws Exception { } } - List conflictDocuments = Observable.merge(insertTask).toList().toBlocking().single(); + List conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("Inserted {} conflicts, verifying conflict resolution", conflictDocuments.size()); @@ -398,7 +398,7 @@ public void runInsertConflictOnUdp() throws Exception { do { logger.info("1) Performing conflicting insert across 3 regions on {}", this.udpCollectionName); - ArrayList> insertTask = new ArrayList>(); + ArrayList> insertTask = new ArrayList<>(); Document conflictDocument = new Document(); conflictDocument.id(UUID.randomUUID().toString()); @@ -408,7 +408,7 @@ public void runInsertConflictOnUdp() throws Exception { insertTask.add(this.tryInsertDocument(client, this.udpCollectionUri, conflictDocument, index++)); } - List conflictDocuments = Observable.merge(insertTask).toList().toBlocking().single(); + List conflictDocuments = Flux.merge(insertTask).collectList().single().block(); if (conflictDocuments.size() > 1) { @@ -429,20 +429,20 @@ public void runUpdateConflictOnUdp() throws Exception { conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.udpCollectionUri, conflictDocument, 0) - .firstOrDefault(null).toBlocking().first(); + .singleOrEmpty().block(); TimeUnit.SECONDS.sleep(1); //1 Second for write to sync. logger.info("1) Performing conflicting update across 3 regions on {}", this.udpCollectionUri); - ArrayList> updateTask = new ArrayList>(); + ArrayList> updateTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { updateTask.add(this.tryUpdateDocument(client, this.udpCollectionUri, conflictDocument, index++)); } - List conflictDocuments = Observable.merge(updateTask).toList().toBlocking().single(); + List conflictDocuments = Flux.merge(updateTask).collectList().single().block(); if (conflictDocuments.size() > 1) { @@ -463,13 +463,13 @@ public void runDeleteConflictOnUdp() throws Exception { conflictDocument.id(UUID.randomUUID().toString()); conflictDocument = this.tryInsertDocument(clients.get(0), this.udpCollectionUri, conflictDocument, 0) - .firstOrDefault(null).toBlocking().first(); + .singleOrEmpty().block(); TimeUnit.SECONDS.sleep(1); //1 Second for write to sync. logger.info("1) Performing conflicting update/delete across 3 regions on {}", this.udpCollectionUri); - ArrayList> deleteTask = new ArrayList>(); + ArrayList> deleteTask = new ArrayList<>(); int index = 0; for (AsyncDocumentClient client : this.clients) { @@ -481,7 +481,7 @@ public void runDeleteConflictOnUdp() throws Exception { } } - List conflictDocuments = Observable.merge(deleteTask).toList().toBlocking().single(); + List conflictDocuments = Flux.merge(deleteTask).collectList().single().block(); if (conflictDocuments.size() > 1) { logger.info("2) Caused {} delete conflicts, verifying conflict resolution", conflictDocuments.size()); @@ -495,17 +495,17 @@ public void runDeleteConflictOnUdp() throws Exception { } while (true); } - private Observable tryInsertDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { + private Flux tryInsertDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { logger.debug("region: {}", client.getWriteEndpoint()); document.set("regionId", index); document.set("regionEndpoint", client.getReadEndpoint()); return client.createDocument(collectionUri, document, null, false) - .onErrorResumeNext(e -> { + .onErrorResume(e -> { if (hasDocumentClientException(e, 409)) { - return Observable.empty(); + return Flux.empty(); } else { - return Observable.error(e); + return Flux.error(e); } }).map(ResourceResponse::getResource); } @@ -543,7 +543,7 @@ private boolean hasDocumentClientExceptionCause(Throwable e, int statusCode) { return false; } - private Observable tryUpdateDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { + private Flux tryUpdateDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { document.set("regionId", index); document.set("regionEndpoint", client.getReadEndpoint()); @@ -553,19 +553,19 @@ private Observable tryUpdateDocument(AsyncDocumentClient client, Strin options.getAccessCondition().condition(document.etag()); - return client.replaceDocument(document.selfLink(), document, null).onErrorResumeNext(e -> { + return client.replaceDocument(document.selfLink(), document, null).onErrorResume(e -> { // pre condition failed if (hasDocumentClientException(e, 412)) { //Lost synchronously or not document yet. No conflict is induced. - return Observable.empty(); + return Flux.empty(); } - return Observable.error(e); + return Flux.error(e); }).map(ResourceResponse::getResource); } - private Observable tryDeleteDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { + private Flux tryDeleteDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { document.set("regionId", index); document.set("regionEndpoint", client.getReadEndpoint()); @@ -575,15 +575,15 @@ private Observable tryDeleteDocument(AsyncDocumentClient client, Strin options.getAccessCondition().condition(document.etag()); - return client.deleteDocument(document.selfLink(), options).onErrorResumeNext(e -> { + return client.deleteDocument(document.selfLink(), options).onErrorResume(e -> { // pre condition failed if (hasDocumentClientException(e, 412)) { //Lost synchronously. No conflict is induced. - return Observable.empty(); + return Flux.empty(); } - return Observable.error(e); + return Flux.error(e); }).map(rr -> document); } @@ -610,7 +610,7 @@ private boolean equals(String a, String b) { private boolean validateManualConflict(AsyncDocumentClient client, Document conflictDocument) throws Exception { while (true) { FeedResponse response = client.readConflicts(this.manualCollectionUri, null) - .first().toBlocking().single(); + .take(1).single().block(); for (Conflict conflict : response.results()) { if (!isDelete(conflict)) { @@ -627,7 +627,7 @@ private boolean validateManualConflict(AsyncDocumentClient client, Document conf try { //Checking whether this is the winner. Document winnerDocument = client.readDocument(conflictDocument.selfLink(), null) - .toBlocking().single().getResource(); + .single().block().getResource(); logger.info("Document from region {} won the conflict @ {}", conflictDocument.getInt("regionId"), client.getReadEndpoint()); @@ -665,7 +665,7 @@ private boolean validateManualConflict(AsyncDocumentClient client, Document conf private void deleteConflict(Document conflictDocument) { AsyncDocumentClient delClient = clients.get(0); - FeedResponse conflicts = delClient.readConflicts(this.manualCollectionUri, null).first().toBlocking().single(); + FeedResponse conflicts = delClient.readConflicts(this.manualCollectionUri, null).take(1).single().block(); for (Conflict conflict : conflicts.results()) { if (!isDelete(conflict)) { @@ -676,7 +676,7 @@ && equals(conflictContent.etag(), conflictDocument.etag())) { conflict.getSourceResourceId(), conflictContent.getInt("regionId")); delClient.deleteConflict(conflict.selfLink(), null) - .toBlocking().single(); + .single().block(); } } else if (equals(conflict.getSourceResourceId(), conflictDocument.resourceId())) { @@ -684,7 +684,7 @@ && equals(conflictContent.etag(), conflictDocument.etag())) { conflict.getSourceResourceId(), conflictDocument.getInt("regionId")); delClient.deleteConflict(conflict.selfLink(), null) - .toBlocking().single(); + .single().block(); } } } @@ -702,7 +702,7 @@ private void validateLWW(List clients, List confl private void validateLWW(AsyncDocumentClient client, List conflictDocument, boolean hasDeleteConflict) throws Exception { FeedResponse response = client.readConflicts(this.lwwCollectionUri, null) - .first().toBlocking().single(); + .take(1).single().block(); if (response.results().size() != 0) { logger.error("Found {} conflicts in the lww collection", response.results().size()); @@ -712,7 +712,7 @@ private void validateLWW(AsyncDocumentClient client, List conflictDocu if (hasDeleteConflict) { do { try { - client.readDocument(conflictDocument.get(0).selfLink(), null).toBlocking().single(); + client.readDocument(conflictDocument.get(0).selfLink(), null).single().block(); logger.error("DELETE conflict for document {} didnt win @ {}", conflictDocument.get(0).id(), @@ -755,7 +755,7 @@ private void validateLWW(AsyncDocumentClient client, List conflictDocu while (true) { try { Document existingDocument = client.readDocument(winnerDocument.selfLink(), null) - .toBlocking().single().getResource(); + .single().block().getResource(); if (existingDocument.getInt("regionId") == winnerDocument.getInt("regionId")) { logger.info("Winner document from region {} found at {}", @@ -792,7 +792,7 @@ private String documentNameLink(String collectionId, String documentId) { } private void validateUDPAsync(AsyncDocumentClient client, List conflictDocument, boolean hasDeleteConflict) throws Exception { - FeedResponse response = client.readConflicts(this.udpCollectionUri, null).first().toBlocking().single(); + FeedResponse response = client.readConflicts(this.udpCollectionUri, null).take(1).single().block(); if (response.results().size() != 0) { logger.error("Found {} conflicts in the udp collection", response.results().size()); @@ -804,7 +804,7 @@ private void validateUDPAsync(AsyncDocumentClient client, List conflic try { client.readDocument( documentNameLink(udpCollectionName, conflictDocument.get(0).id()), null) - .toBlocking().single(); + .single().block(); logger.error("DELETE conflict for document {} didnt win @ {}", conflictDocument.get(0).id(), @@ -844,7 +844,7 @@ private void validateUDPAsync(AsyncDocumentClient client, List conflic Document existingDocument = client.readDocument( documentNameLink(udpCollectionName, winnerDocument.id()), null) - .toBlocking().single().getResource(); + .single().block().getResource(); if (existingDocument.getInt("regionId") == winnerDocument.getInt( ("regionId"))) { diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java index c41aa76c8dbe0..8604aeabb12b2 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java @@ -30,7 +30,7 @@ import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Completable; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.Collections; @@ -100,7 +100,7 @@ public void runBasic() throws Exception { logger.info("1) Starting insert loops across multiple regions ..."); - List basicTask = new ArrayList(); + List> basicTask = new ArrayList<>(); int documentsToInsertPerWorker = 100; @@ -108,7 +108,7 @@ public void runBasic() throws Exception { basicTask.add(worker.runLoopAsync(documentsToInsertPerWorker)); } - Completable.merge(basicTask).await(); + Mono.when(basicTask).block(); basicTask.clear(); @@ -119,7 +119,7 @@ public void runBasic() throws Exception { basicTask.add(worker.readAllAsync(expectedDocuments)); } - Completable.merge(basicTask).await(); + Mono.when(basicTask).block(); basicTask.clear(); diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java index daf278f43add2..482dfccf3dada 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java @@ -31,9 +31,9 @@ import com.azure.data.cosmos.FeedResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Completable; -import rx.Scheduler; -import rx.schedulers.Schedulers; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Scheduler; +import reactor.core.scheduler.Schedulers; import java.util.ArrayList; import java.util.Collections; @@ -57,11 +57,11 @@ public Worker(AsyncDocumentClient client, String databaseName, String collection this.client = client; this.documentCollectionUri = String.format("/dbs/%s/colls/%s", databaseName, collectionName); this.executor = Executors.newSingleThreadExecutor(); - this.schedulerForBlockingWork = Schedulers.from(executor); + this.schedulerForBlockingWork = Schedulers.fromExecutor(executor); } - public Completable runLoopAsync(int documentsToInsert) { - return Completable.defer(() -> { + public Mono runLoopAsync(int documentsToInsert) { + return Mono.defer(() -> { int iterationCount = 0; @@ -73,7 +73,7 @@ public Completable runLoopAsync(int documentsToInsert) { d.id(UUID.randomUUID().toString()); this.client.createDocument(this.documentCollectionUri, d, null, false) - .subscribeOn(schedulerForBlockingWork).toBlocking().single(); + .subscribeOn(schedulerForBlockingWork).single().block(); long endTick = System.currentTimeMillis(); @@ -88,16 +88,16 @@ public Completable runLoopAsync(int documentsToInsert) { this.client.getWriteEndpoint(), latency.get(p50Index)); - return Completable.complete(); + return Mono.empty(); }); } - public Completable readAllAsync(int expectedNumberOfDocuments) { + public Mono readAllAsync(int expectedNumberOfDocuments) { - return Completable.defer(() -> { + return Mono.defer(() -> { while (true) { int totalItemRead = 0; @@ -107,8 +107,8 @@ public Completable readAllAsync(int expectedNumberOfDocuments) { FeedOptions options = new FeedOptions(); options.requestContinuation(response != null ? response.continuationToken() : null); - response = this.client.readDocuments(this.documentCollectionUri, options).first() - .subscribeOn(schedulerForBlockingWork).toBlocking().single(); + response = this.client.readDocuments(this.documentCollectionUri, options).take(1) + .subscribeOn(schedulerForBlockingWork).single().block(); totalItemRead += response.results().size(); } while (response.continuationToken() != null); @@ -132,7 +132,7 @@ public Completable readAllAsync(int expectedNumberOfDocuments) { } } - return Completable.complete(); + return Mono.empty(); }); } @@ -144,8 +144,8 @@ void deleteAll() { FeedOptions options = new FeedOptions(); options.requestContinuation(response != null ? response.continuationToken() : null); - response = this.client.readDocuments(this.documentCollectionUri, options).first() - .subscribeOn(schedulerForBlockingWork).toBlocking().single(); + response = this.client.readDocuments(this.documentCollectionUri, options).take(1) + .subscribeOn(schedulerForBlockingWork).single().block(); documents.addAll(response.results()); } while (response.continuationToken() != null); @@ -153,7 +153,7 @@ void deleteAll() { for (Document document : documents) { try { this.client.deleteDocument(document.selfLink(), null) - .subscribeOn(schedulerForBlockingWork).toBlocking().single(); + .subscribeOn(schedulerForBlockingWork).single().block(); } catch (RuntimeException exEx) { CosmosClientException dce = getDocumentClientExceptionCause(exEx); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java index 800582be895d5..05ad28422139e 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java @@ -38,20 +38,19 @@ import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.ResourceResponse; -import com.google.common.util.concurrent.ListenableFuture; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import rx.Observable; -import rx.functions.Action1; -import rx.observable.ListenableFutureObservable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; +import java.util.function.Consumer; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -75,9 +74,9 @@ * do the same thing without lambda expression. * *

- * Also if you need to work with Future or ListenableFuture it is possible to - * transform an observable to ListenableFuture. Please see - * {@link #transformObservableToGoogleGuavaListenableFuture()} + * Also if you need to work with Future or CompletableFuture it is possible to + * transform a flux to CompletableFuture. Please see + * {@link #transformObservableToCompletableFuture()} *

* To Modify the Collection's throughput after it has been created, you need to * update the corresponding Offer. Please see @@ -133,7 +132,7 @@ public void shutdown() { public void createCollection_SinglePartition_Async() throws Exception { RequestOptions singlePartitionRequestOptions = new RequestOptions(); singlePartitionRequestOptions.setOfferThroughput(400); - Observable> createCollectionObservable = client + Flux> createCollectionObservable = client .createCollection(getDatabaseLink(), collectionDefinition, singlePartitionRequestOptions); final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -165,7 +164,7 @@ public void createCollection_MultiPartition_Async() throws Exception { RequestOptions multiPartitionRequestOptions = new RequestOptions(); multiPartitionRequestOptions.setOfferThroughput(20000); - Observable> createCollectionObservable = client.createCollection( + Flux> createCollectionObservable = client.createCollection( getDatabaseLink(), getMultiPartitionCollectionDefinition(), multiPartitionRequestOptions); final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -189,23 +188,23 @@ public void createCollection_MultiPartition_Async() throws Exception { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createCollection_Async_withoutLambda() throws Exception { - Observable> createCollectionObservable = client + Flux> createCollectionObservable = client .createCollection(getDatabaseLink(), collectionDefinition, null); final CountDownLatch countDownLatch = new CountDownLatch(1); - Action1> onCollectionCreationAction = new Action1>() { + Consumer> onCollectionCreationAction = new Consumer>() { @Override - public void call(ResourceResponse resourceResponse) { + public void accept(ResourceResponse resourceResponse) { // Collection is created System.out.println(resourceResponse.getActivityId()); countDownLatch.countDown(); } }; - Action1 onError = new Action1() { + Consumer onError = new Consumer() { @Override - public void call(Throwable error) { + public void accept(Throwable error) { System.err.println( "an error occurred while creating the collection: actual cause: " + error.getMessage()); countDownLatch.countDown(); @@ -224,12 +223,12 @@ public void call(Throwable error) { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createCollection_toBlocking() { - Observable> createCollectionObservable = client + Flux> createCollectionObservable = client .createCollection(getDatabaseLink(), collectionDefinition, null); - // toBlocking() converts the observable to a blocking observable. - // single() gets the only result. - createCollectionObservable.toBlocking().single(); + // single() converts the flux to a mono. + // block() gets the only result. + createCollectionObservable.single().block(); } /** @@ -241,15 +240,15 @@ public void createCollection_toBlocking() { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createCollection_toBlocking_CollectionAlreadyExists_Fails() { - client.createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single(); + client.createCollection(getDatabaseLink(), collectionDefinition, null).single().block(); // CREATE the collection for test. - Observable> collectionForTestObservable = client + Flux> collectionForTestObservable = client .createCollection(getDatabaseLink(), collectionDefinition, null); try { - collectionForTestObservable.toBlocking() // Blocks - .single(); // Gets the single result + collectionForTestObservable.single() // Gets the single result + .block(); // Blocks assertThat("Should not reach here", false); } catch (Exception e) { assertThat("Collection already exists.", ((CosmosClientException) e.getCause()).statusCode(), @@ -258,17 +257,13 @@ public void createCollection_toBlocking_CollectionAlreadyExists_Fails() { } /** - * You can convert an Observable to a ListenableFuture. - * ListenableFuture (part of google guava library) is a popular extension - * of Java's Future which allows registering listener callbacks: - * https://github.com/google/guava/wiki/ListenableFutureExplained + * You can convert a Flux to a CompletableFuture. */ @Test(groups = "samples", timeOut = TIMEOUT) - public void transformObservableToGoogleGuavaListenableFuture() throws Exception { - Observable> createCollectionObservable = client + public void transformObservableToCompletableFuture() throws Exception { + Flux> createCollectionObservable = client .createCollection(getDatabaseLink(), collectionDefinition, null); - ListenableFuture> future = ListenableFutureObservable - .to(createCollectionObservable); + CompletableFuture> future = createCollectionObservable.single().toFuture(); ResourceResponse rrd = future.get(); @@ -283,11 +278,11 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception public void createAndReadCollection() throws Exception { // CREATE a Collection DocumentCollection documentCollection = client - .createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single() + .createCollection(getDatabaseLink(), collectionDefinition, null).single().block() .getResource(); // READ the created collection using async api - Observable> readCollectionObservable = client + Flux> readCollectionObservable = client .readCollection(getCollectionLink(documentCollection), null); final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -313,11 +308,11 @@ public void createAndReadCollection() throws Exception { public void createAndDeleteCollection() throws Exception { // CREATE a Collection DocumentCollection documentCollection = client - .createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single() + .createCollection(getDatabaseLink(), collectionDefinition, null).single().block() .getResource(); // DELETE the created collection using async api - Observable> deleteCollectionObservable = client + Flux> deleteCollectionObservable = client .deleteCollection(getCollectionLink(documentCollection), null); final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -343,17 +338,17 @@ public void createAndDeleteCollection() throws Exception { public void collectionCreateAndQuery() throws Exception { // CREATE a Collection DocumentCollection collection = client - .createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single() + .createCollection(getDatabaseLink(), collectionDefinition, null).single().block() .getResource(); // Query the created collection using async api - Observable> queryCollectionObservable = client.queryCollections( + Flux> queryCollectionObservable = client.queryCollections( getDatabaseLink(), String.format("SELECT * FROM r where r.id = '%s'", collection.id()), null); final CountDownLatch countDownLatch = new CountDownLatch(1); - queryCollectionObservable.toList().subscribe(collectionFeedResponseList -> { + queryCollectionObservable.collectList().subscribe(collectionFeedResponseList -> { // toList() should return a list of size 1 assertThat(collectionFeedResponseList.size(), equalTo(1)); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java index ee9baa5ce48a2..b9b90026eb0f3 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java @@ -35,17 +35,17 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.HttpConstants; -import com.google.common.util.concurrent.ListenableFuture; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Observable; -import rx.observable.ListenableFutureObservable; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -56,9 +56,9 @@ * This integration test class demonstrates how to use Async API for * Conflicts. *

- * Also if you need to work with Future or ListenableFuture it is possible to - * transform an observable to ListenableFuture. Please see - * {@link #transformObservableToGoogleGuavaListenableFuture()} + * Also if you need to work with Future or CompletableFuture it is possible to + * transform a flux to CompletableFuture. Please see + * {@link #transformObservableToCompletableFuture()} */ public class ConflictAPITest extends DocumentClientTest { private final static int TIMEOUT = 60000; @@ -94,13 +94,13 @@ public void setUp() { // CREATE collection createdCollection = client .createCollection("/dbs/" + createdDatabase.id(), collectionDefinition, null) - .toBlocking().single().getResource(); + .single().block().getResource(); int numberOfDocuments = 20; // Add documents for (int i = 0; i < numberOfDocuments; i++) { Document doc = new Document(String.format("{ 'id': 'loc%d', 'counter': %d}", i, i)); - client.createDocument(getCollectionLink(), doc, null, true).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, true).single().block(); } } @@ -122,12 +122,11 @@ public void readConflicts_toBlocking_toIterator() { FeedOptions options = new FeedOptions(); options.maxItemCount(requestPageSize); - Observable> conflictReadFeedObservable = client + Flux> conflictReadFeedObservable = client .readConflicts(getCollectionLink(), options); - // Covert the observable to a blocking observable, then convert the blocking - // observable to an iterator - Iterator> it = conflictReadFeedObservable.toBlocking().getIterator(); + // Covert the flux to an iterable, and then to iterator + Iterator> it = conflictReadFeedObservable.toIterable().iterator(); int expectedNumberOfConflicts = 0; @@ -145,25 +144,22 @@ public void readConflicts_toBlocking_toIterator() { } /** - * You can convert an Observable to a ListenableFuture. - * ListenableFuture (part of google guava library) is a popular extension - * of Java's Future which allows registering listener callbacks: - * https://github.com/google/guava/wiki/ListenableFutureExplained + * You can convert a Flux to a CompletableFuture. */ @Test(groups = "samples", timeOut = TIMEOUT) - public void transformObservableToGoogleGuavaListenableFuture() throws Exception { + public void transformObservableToCompletableFuture() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.maxItemCount(requestPageSize); - Observable> conflictReadFeedObservable = client + Flux> conflictReadFeedObservable = client .readConflicts(getCollectionLink(), options); // Convert to observable of list of pages - Observable>> allPagesObservable = conflictReadFeedObservable.toList(); + Mono>> allPagesObservable = conflictReadFeedObservable.collectList(); // Convert the observable of list of pages to a Future - ListenableFuture>> future = ListenableFutureObservable.to(allPagesObservable); + CompletableFuture>> future = allPagesObservable.toFuture(); List> pageList = future.get(); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java index 15407866d34fa..d2f2c94d2a8a7 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java @@ -31,17 +31,16 @@ import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.ResourceResponse; -import com.google.common.util.concurrent.ListenableFuture; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Observable; -import rx.functions.Action1; -import rx.observable.ListenableFutureObservable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; +import java.util.function.Consumer; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -65,9 +64,9 @@ * do the same thing without lambda expression. * *

- * Also if you need to work with Future or ListenableFuture it is possible to - * transform an observable to ListenableFuture. Please see - * {@link #transformObservableToGoogleGuavaListenableFuture()} + * Also if you need to work with Future or CompletableFuture it is possible to + * transform a flux to CompletableFuture. Please see + * {@link #transformObservableToCompletableFuture()} */ public class DatabaseCRUDAsyncAPITest extends DocumentClientTest { private final static int TIMEOUT = 60000; @@ -113,7 +112,7 @@ public void shutdown() { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDatabase_Async() throws Exception { - Observable> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), + Flux> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -137,23 +136,23 @@ public void createDatabase_Async() throws Exception { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDatabase_Async_withoutLambda() throws Exception { - Observable> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), + Flux> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), null); final CountDownLatch completionLatch = new CountDownLatch(1); - Action1> onDatabaseCreationAction = new Action1>() { + Consumer> onDatabaseCreationAction = new Consumer>() { @Override - public void call(ResourceResponse resourceResponse) { + public void accept(ResourceResponse resourceResponse) { // Database is created System.out.println(resourceResponse.getActivityId()); completionLatch.countDown(); } }; - Action1 onError = new Action1() { + Consumer onError = new Consumer() { @Override - public void call(Throwable error) { + public void accept(Throwable error) { System.err .println("an error occurred while creating the database: actual cause: " + error.getMessage()); completionLatch.countDown(); @@ -172,12 +171,12 @@ public void call(Throwable error) { */ @Test(groups = "samples", timeOut = TIMEOUT) public void createDatabase_toBlocking() { - Observable> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), + Flux> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), null); // toBlocking() converts to a blocking observable. // single() gets the only result. - createDatabaseObservable.toBlocking().single(); + createDatabaseObservable.single().block(); } /** @@ -190,15 +189,15 @@ public void createDatabase_toBlocking() { @Test(groups = "samples", timeOut = TIMEOUT) public void createDatabase_toBlocking_DatabaseAlreadyExists_Fails() { Database databaseDefinition = getDatabaseDefinition(); - client.createDatabase(databaseDefinition, null).toBlocking().single(); + client.createDatabase(databaseDefinition, null).single().block(); // CREATE the database for test. - Observable> databaseForTestObservable = client + Flux> databaseForTestObservable = client .createDatabase(databaseDefinition, null); try { - databaseForTestObservable.toBlocking() // Blocks - .single(); // Gets the single result + databaseForTestObservable.single() // Single + .block(); // Blocks to get the result assertThat("Should not reach here", false); } catch (Exception e) { assertThat("Database already exists.", ((CosmosClientException) e.getCause()).statusCode(), @@ -207,16 +206,13 @@ public void createDatabase_toBlocking_DatabaseAlreadyExists_Fails() { } /** - * You can convert an Observable to a ListenableFuture. - * ListenableFuture (part of google guava library) is a popular extension - * of Java's Future which allows registering listener callbacks: - * https://github.com/google/guava/wiki/ListenableFutureExplained + * You can convert a Flux to a CompletableFuture. */ @Test(groups = "samples", timeOut = TIMEOUT) - public void transformObservableToGoogleGuavaListenableFuture() throws Exception { - Observable> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), + public void transformObservableToCompletableFuture() throws Exception { + Flux> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(), null); - ListenableFuture> future = ListenableFutureObservable.to(createDatabaseObservable); + CompletableFuture> future = createDatabaseObservable.single().toFuture(); ResourceResponse rrd = future.get(); @@ -230,10 +226,10 @@ public void transformObservableToGoogleGuavaListenableFuture() throws Exception @Test(groups = "samples", timeOut = TIMEOUT) public void createAndReadDatabase() throws Exception { // CREATE a database - Database database = client.createDatabase(getDatabaseDefinition(), null).toBlocking().single().getResource(); + Database database = client.createDatabase(getDatabaseDefinition(), null).single().block().getResource(); // READ the created database using async api - Observable> readDatabaseObservable = client.readDatabase("dbs/" + database.id(), + Flux> readDatabaseObservable = client.readDatabase("dbs/" + database.id(), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -258,10 +254,10 @@ public void createAndReadDatabase() throws Exception { @Test(groups = "samples", timeOut = TIMEOUT) public void createAndDeleteDatabase() throws Exception { // CREATE a database - Database database = client.createDatabase(getDatabaseDefinition(), null).toBlocking().single().getResource(); + Database database = client.createDatabase(getDatabaseDefinition(), null).single().block().getResource(); // DELETE the created database using async api - Observable> deleteDatabaseObservable = client + Flux> deleteDatabaseObservable = client .deleteDatabase("dbs/" + database.id(), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -287,15 +283,15 @@ public void createAndDeleteDatabase() throws Exception { public void databaseCreateAndQuery() throws Exception { // CREATE a database Database databaseDefinition = getDatabaseDefinition(); - client.createDatabase(databaseDefinition, null).toBlocking().single().getResource(); + client.createDatabase(databaseDefinition, null).single().block().getResource(); // Query the created database using async api - Observable> queryDatabaseObservable = client + Flux> queryDatabaseObservable = client .queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseDefinition.id()), null); final CountDownLatch completionLatch = new CountDownLatch(1); - queryDatabaseObservable.toList().subscribe(databaseFeedResponseList -> { + queryDatabaseObservable.collectList().subscribe(databaseFeedResponseList -> { // toList() should return a list of size 1 assertThat(databaseFeedResponseList.size(), equalTo(1)); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java index 4ce611474f8ae..29ca7655d1b81 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java @@ -41,21 +41,20 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.util.concurrent.ListenableFuture; import org.apache.commons.lang3.RandomUtils; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Observable; -import rx.functions.Action1; -import rx.observable.ListenableFutureObservable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; +import java.util.function.Consumer; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; @@ -83,9 +82,9 @@ * the same thing without lambda expression. * *

- * Also if you need to work with Future or ListenableFuture it is possible to - * transform an observable to ListenableFuture. Please see - * {@link #transformObservableToGoogleGuavaListenableFuture()} + * Also if you need to work with Future or CompletableFuture it is possible to + * transform a flux to CompletableFuture. Please see + * {@link #transformObservableToCompletableFuture()} */ public class DocumentCRUDAsyncAPITest extends DocumentClientTest { @@ -124,7 +123,7 @@ public void setUp() { // CREATE collection createdCollection = client .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) - .toBlocking().single().getResource(); + .single().block().getResource(); } @AfterClass(groups = "samples", timeOut = TIMEOUT) @@ -139,7 +138,7 @@ public void shutdown() { @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_Async() throws Exception { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - Observable> createDocumentObservable = client + Flux> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, true); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -165,23 +164,24 @@ public void createDocument_Async() throws Exception { @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_Async_withoutLambda() throws Exception { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - Observable> createDocumentObservable = client + Flux> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, true); final CountDownLatch completionLatch = new CountDownLatch(1); - Action1> onNext = new Action1>() { + Consumer> onNext = new Consumer>() { @Override - public void call(ResourceResponse documentResourceResponse) { + public void accept(ResourceResponse documentResourceResponse) { System.out.println(documentResourceResponse.getActivityId()); completionLatch.countDown(); } }; - Action1 onError = new Action1() { + Consumer onError = new Consumer() { - public void call(Throwable error) { + @Override + public void accept(Throwable error) { System.err .println("an error occurred while creating the document: actual cause: " + error.getMessage()); completionLatch.countDown(); @@ -202,12 +202,12 @@ public void call(Throwable error) { @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_toBlocking() { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - Observable> createDocumentObservable = client + Flux> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, true); // toBlocking() converts to a blocking observable. // single() gets the only result. - createDocumentObservable.toBlocking().single(); + createDocumentObservable.single().block(); } /** @@ -221,14 +221,14 @@ public void createDocumentWithProgrammableDocumentDefinition() throws Exception // CREATE a document Document createdDocument = client - .createDocument(getCollectionLink(), documentDefinition, null, false).toBlocking().single() + .createDocument(getCollectionLink(), documentDefinition, null, false).single().block() .getResource(); RequestOptions options = new RequestOptions(); options.setPartitionKey(PartitionKey.None); // READ the created document - Observable> readDocumentObservable = client - .readDocument(getDocumentLink(createdDocument), options); + Flux> readDocumentObservable = client + .readDocument(getDocumentLink(createdDocument), null); final CountDownLatch completionLatch = new CountDownLatch(1); @@ -254,24 +254,24 @@ public void createDocumentWithProgrammableDocumentDefinition() throws Exception @Test(groups = "samples", timeOut = TIMEOUT) public void documentCreation_SumUpRequestCharge() throws Exception { // CREATE 10 documents - List>> listOfCreateDocumentObservables = new ArrayList<>(); + List>> listOfCreateDocumentObservables = new ArrayList<>(); for (int i = 0; i < 10; i++) { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), i)); - Observable> createDocumentObservable = client + Flux> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, false); listOfCreateDocumentObservables.add(createDocumentObservable); } // Merge all document creation observables into one observable - Observable> mergedObservable = Observable.merge(listOfCreateDocumentObservables); + Flux> mergedObservable = Flux.merge(listOfCreateDocumentObservables); // CREATE a new observable emitting the total charge of creating all 10 // documents. - Observable totalChargeObservable = mergedObservable + Flux totalChargeObservable = mergedObservable .map(ResourceResponse::getRequestCharge) // Map to request charge - .reduce((totalCharge, charge) -> totalCharge + charge); + .reduce(Double::sum).flux(); // Sum up all the charges final CountDownLatch completionLatch = new CountDownLatch(1); @@ -297,15 +297,15 @@ public void documentCreation_SumUpRequestCharge() throws Exception { @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_toBlocking_DocumentAlreadyExists_Fails() { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - client.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, false).single().block(); // CREATE the document - Observable> createDocumentObservable = client + Flux> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, false); try { - createDocumentObservable.toBlocking() // Converts the observable to a blocking observable - .single(); // Gets the single result + createDocumentObservable.single() // Converts the observable to a single observable + .block(); // Blocks and gets the result Assert.fail("Document Already Exists. Document Creation must fail"); } catch (Exception e) { assertThat("Document already exists.", ((CosmosClientException) e.getCause()).statusCode(), @@ -323,10 +323,10 @@ public void createDocument_toBlocking_DocumentAlreadyExists_Fails() { @Test(groups = "samples", timeOut = TIMEOUT) public void createDocument_Async_DocumentAlreadyExists_Fails() throws Exception { Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - client.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, false).single().block(); // CREATE the document - Observable> createDocumentObservable = client + Flux> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, false); List errorList = Collections.synchronizedList(new ArrayList<>()); @@ -350,13 +350,13 @@ public void createDocument_Async_DocumentAlreadyExists_Fails() throws Exception public void documentReplace_Async() throws Exception { // CREATE a document Document createdDocument = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - createdDocument = client.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() - .single().getResource(); + createdDocument = client.createDocument(getCollectionLink(), createdDocument, null, false).single() + .block().getResource(); // Try to replace the existing document Document replacingDocument = new Document( String.format("{ 'id': 'doc%s', 'counter': '%d', 'new-prop' : '2'}", createdDocument.id(), 1)); - Observable> replaceDocumentObservable = client + Flux> replaceDocumentObservable = client .replaceDocument(getDocumentLink(createdDocument), replacingDocument, null); List> capturedResponse = Collections @@ -379,12 +379,12 @@ public void documentReplace_Async() throws Exception { public void documentUpsert_Async() throws Exception { // CREATE a document Document doc = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d'}", UUID.randomUUID().toString(), 1)); - client.createDocument(getCollectionLink(), doc, null, false).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, false).single().block(); // Upsert the existing document Document upsertingDocument = new Document( String.format("{ 'id': 'doc%s', 'counter': '%d', 'new-prop' : '2'}", doc.id(), 1)); - Observable> upsertDocumentObservable = client + Flux> upsertDocumentObservable = client .upsertDocument(getCollectionLink(), upsertingDocument, null, false); List> capturedResponse = Collections @@ -407,14 +407,14 @@ public void documentUpsert_Async() throws Exception { public void documentDelete_Async() throws Exception { // CREATE a document Document createdDocument = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d', 'mypk' : '%s'}", UUID.randomUUID().toString(), 1, UUID.randomUUID().toString())); - createdDocument = client.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() - .single().getResource(); + createdDocument = client.createDocument(getCollectionLink(), createdDocument, null, false).single() + .block().getResource(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(createdDocument.getString("mypk"))); // DELETE the existing document - Observable> deleteDocumentObservable = client + Flux> deleteDocumentObservable = client .deleteDocument(getDocumentLink(createdDocument), options); List> capturedResponse = Collections @@ -434,10 +434,10 @@ public void documentDelete_Async() throws Exception { List listOfDocuments = client .queryDocuments(getCollectionLink(), String.format("SELECT * FROM r where r.id = '%s'", createdDocument.id()), queryOptions) .map(FeedResponse::results) // Map page to its list of documents - .concatMap(Observable::from) // Flatten the observable - .toList() // Transform to a observable - .toBlocking() // Block - .single(); // Gets the List + .concatMap(Flux::fromIterable) // Flatten the observable + .collectList() // Transform to a observable + .single() // Gets the Mono> + .block(); // Block // Assert that there is no document found assertThat(listOfDocuments, hasSize(0)); @@ -450,13 +450,13 @@ public void documentDelete_Async() throws Exception { public void documentRead_Async() throws Exception { // CREATE a document Document createdDocument = new Document(String.format("{ 'id': 'doc%s', 'counter': '%d', 'mypk' : '%s'}", UUID.randomUUID().toString(), 1, UUID.randomUUID().toString())); - createdDocument = client.createDocument(getCollectionLink(), createdDocument, null, false).toBlocking() - .single().getResource(); + createdDocument = client.createDocument(getCollectionLink(), createdDocument, null, false).single() + .block().getResource(); // READ the document RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(createdDocument.getString("mypk"))); - Observable> readDocumentObservable = client + Flux> readDocumentObservable = client .readDocument(getDocumentLink(createdDocument), options); List> capturedResponse = Collections @@ -498,8 +498,8 @@ public void customSerialization() throws Exception { Document createdDocument = client .createDocument(getCollectionLink(), doc, null, false) - .toBlocking() .single() + .block() .getResource(); RequestOptions options = new RequestOptions(); @@ -507,8 +507,8 @@ public void customSerialization() throws Exception { Document readDocument = client .readDocument(createdDocument.selfLink(), options) - .toBlocking() .single() + .block() .getResource(); TestObject readObject = mapper.readValue(readDocument.toJson(), TestObject.class); @@ -516,18 +516,14 @@ public void customSerialization() throws Exception { } /** - * You can convert an Observable to a ListenableFuture. - * ListenableFuture (part of google guava library) is a popular extension - * of Java's Future which allows registering listener callbacks: - * https://github.com/google/guava/wiki/ListenableFutureExplained + * You can convert a Flux to a CompletableFuture. */ @Test(groups = "samples", timeOut = TIMEOUT) - public void transformObservableToGoogleGuavaListenableFuture() throws Exception { + public void transformObservableToCompletableFuture() throws Exception { Document doc = new Document(String.format("{ 'id': 'doc%d', 'counter': '%d'}", RandomUtils.nextInt(), 1)); - Observable> createDocumentObservable = client + Flux> createDocumentObservable = client .createDocument(getCollectionLink(), doc, null, false); - ListenableFuture> listenableFuture = ListenableFutureObservable - .to(createDocumentObservable); + CompletableFuture> listenableFuture = createDocumentObservable.single().toFuture(); ResourceResponse rrd = listenableFuture.get(); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java index 3a4052103b95f..8f44e3aaf95d4 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java @@ -34,27 +34,29 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; -import com.google.common.util.concurrent.ListenableFuture; import org.apache.commons.lang3.RandomStringUtils; +import org.reactivestreams.Subscription; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Observable; -import rx.Subscriber; -import rx.functions.Action1; -import rx.functions.Func1; -import rx.observable.ListenableFutureObservable; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.function.Predicate; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -79,9 +81,9 @@ * the same thing without lambda expression. * *

- * Also if you need to work with Future or ListenableFuture it is possible to - * transform an observable to ListenableFuture. Please see - * {@link #transformObservableToGoogleGuavaListenableFuture()} + * Also if you need to work with Future or CompletableFuture it is possible to + * transform a flux to CompletableFuture. Please see + * {@link #transformObservableToCompletableFuture()} */ public class DocumentQueryAsyncAPITest extends DocumentClientTest { @@ -120,13 +122,13 @@ public void setUp() { // CREATE collection createdCollection = client .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) - .toBlocking().single().getResource(); + .single().block().getResource(); numberOfDocuments = 20; // Add documents for (int i = 0; i < numberOfDocuments; i++) { Document doc = new Document(String.format("{ 'id': 'loc%d', 'counter': %d}", i, i)); - client.createDocument(getCollectionLink(), doc, null, true).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, true).single().block(); } } @@ -148,15 +150,14 @@ public void queryDocuments_Async() throws Exception { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable> documentQueryObservable = client + Flux> documentQueryObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); final CountDownLatch mainThreadBarrier = new CountDownLatch(1); final CountDownLatch resultsCountDown = new CountDownLatch(numberOfDocuments); - // forEach(.) is an alias for subscribe(.) - documentQueryObservable.forEach(page -> { + documentQueryObservable.subscribe(page -> { try { // Waits on the barrier mainThreadBarrier.await(); @@ -195,18 +196,18 @@ public void queryDocuments_Async_withoutLambda() throws Exception { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable> documentQueryObservable = client + Flux> documentQueryObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); final CountDownLatch mainThreadBarrier = new CountDownLatch(1); final CountDownLatch resultsCountDown = new CountDownLatch(numberOfDocuments); - Action1> actionPerPage = new Action1>() { + Consumer> actionPerPage = new Consumer>() { @SuppressWarnings("unused") @Override - public void call(FeedResponse t) { + public void accept(FeedResponse t) { try { // waits on the barrier @@ -220,8 +221,7 @@ public void call(FeedResponse t) { } }; - // forEach(.) is an alias for subscribe(.) - documentQueryObservable.forEach(actionPerPage); + documentQueryObservable.subscribe(actionPerPage); // The following code will run concurrently System.out.println("action is subscribed to the observable"); @@ -245,14 +245,13 @@ public void queryDocuments_findTotalRequestCharge() throws Exception { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable totalChargeObservable = client + Flux totalChargeObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options) .map(FeedResponse::requestCharge) // Map the page to its request charge - .reduce((totalCharge, charge) -> totalCharge + charge); // Sum up all the request charges + .reduce(Double::sum).flux(); // Sum up all the request charges final CountDownLatch successfulCompletionLatch = new CountDownLatch(1); - // subscribe(.) is the same as forEach(.) totalChargeObservable.subscribe(totalCharge -> { System.out.println(totalCharge); successfulCompletionLatch.countDown(); @@ -271,7 +270,7 @@ public void queryDocuments_unsubscribeAfterFirstPage() throws Exception { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable> requestChargeObservable = client + Flux> requestChargeObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); AtomicInteger onNextCounter = new AtomicInteger(); @@ -279,23 +278,15 @@ public void queryDocuments_unsubscribeAfterFirstPage() throws Exception { AtomicInteger onErrorCounter = new AtomicInteger(); // Subscribe to the pages of Documents emitted by the observable - requestChargeObservable.subscribe(new Subscriber>() { - - @Override - public void onCompleted() { - onCompletedCounter.incrementAndGet(); - } - - @Override - public void onError(Throwable e) { - onErrorCounter.incrementAndGet(); - } - - @Override - public void onNext(FeedResponse page) { - onNextCounter.incrementAndGet(); - unsubscribe(); - } + AtomicReference s = new AtomicReference<>(); + requestChargeObservable.subscribe(documentFeedResponse -> { + onNextCounter.incrementAndGet(); + s.get().cancel(); + }, error -> { + onErrorCounter.incrementAndGet(); + }, onCompletedCounter::incrementAndGet, subscription -> { + s.set(subscription); + subscription.request(1); }); Thread.sleep(4000); @@ -316,10 +307,10 @@ public void queryDocuments_filterFetchedResults() throws Exception { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Func1 isPrimeNumber = new Func1() { + Predicate isPrimeNumber = new Predicate() { @Override - public Boolean call(Document doc) { + public boolean test(Document doc) { int n = doc.getInt("counter"); if (n <= 1) return false; @@ -335,7 +326,7 @@ public Boolean call(Document doc) { client.queryDocuments(getCollectionLink(), "SELECT * FROM root", options) .map(FeedResponse::results) // Map the page to the list of documents - .concatMap(Observable::from) // Flatten the observable> to observable + .concatMap(Flux::fromIterable) // Flatten the Flux> to Flux .filter(isPrimeNumber) // Filter documents using isPrimeNumber predicate .subscribe(doc -> resultList.add(doc)); // Collect the results @@ -376,12 +367,12 @@ public void queryDocuments_toBlocking_toIterator() { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable> documentQueryObservable = client + Flux> documentQueryObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); // Covert the observable to a blocking observable, then convert the blocking // observable to an iterator - Iterator> it = documentQueryObservable.toBlocking().getIterator(); + Iterator> it = documentQueryObservable.toIterable().iterator(); int pageCounter = 0; int numberOfResults = 0; @@ -417,7 +408,7 @@ public void qrderBy_Async() throws Exception { Document doc = new Document(String.format("{\"id\":\"documentId%d\",\"key\":\"%s\",\"prop\":%d}", i, RandomStringUtils.randomAlphabetic(2), i)); client.createDocument("dbs/" + createdDatabase.id() + "/colls/" + multiPartitionCollection.id(), - doc, null, true).toBlocking().single(); + doc, null, true).single().block(); } // Query for the documents order by the prop field @@ -431,16 +422,16 @@ public void qrderBy_Async() throws Exception { options.maxDegreeOfParallelism(2); // Get the observable order by query documents - Observable> documentQueryObservable = client.queryDocuments( + Flux> documentQueryObservable = client.queryDocuments( "dbs/" + createdDatabase.id() + "/colls/" + multiPartitionCollection.id(), query, options); List resultList = Collections.synchronizedList(new ArrayList<>()); documentQueryObservable.map(FeedResponse::results) // Map the logical page to the list of documents in the page - .concatMap(Observable::from) // Flatten the list of documents - .map(doc -> doc.id()) // Map to the document Id - .forEach(docId -> resultList.add(docId)); // Add each document Id to the resultList + .concatMap(Flux::fromIterable) // Flatten the list of documents + .map(Resource::id) // Map to the document Id + .subscribe(resultList::add); // Add each document Id to the resultList Thread.sleep(4000); @@ -454,26 +445,23 @@ public void qrderBy_Async() throws Exception { } /** - * You can convert an Observable to a ListenableFuture. - * ListenableFuture (part of google guava library) is a popular extension - * of Java's Future which allows registering listener callbacks: - * https://github.com/google/guava/wiki/ListenableFutureExplained + * You can convert a Flux to a CompletableFuture. */ @Test(groups = "samples", timeOut = TIMEOUT) - public void transformObservableToGoogleGuavaListenableFuture() throws Exception { + public void transformObservableToCompletableFuture() throws Exception { int requestPageSize = 3; FeedOptions options = new FeedOptions(); options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable> documentQueryObservable = client + Flux> documentQueryObservable = client .queryDocuments(getCollectionLink(), "SELECT * FROM root", options); // Convert to observable of list of pages - Observable>> allPagesObservable = documentQueryObservable.toList(); + Mono>> allPagesObservable = documentQueryObservable.collectList(); // Convert the observable of list of pages to a Future - ListenableFuture>> future = ListenableFutureObservable.to(allPagesObservable); + CompletableFuture>> future = allPagesObservable.toFuture(); List> pageList = future.get(); @@ -501,7 +489,7 @@ private DocumentCollection createMultiPartitionCollection(String databaseLink, S collectionDefinition.id(collectionId); collectionDefinition.setPartitionKey(partitionKeyDef); DocumentCollection createdCollection = client.createCollection(databaseLink, collectionDefinition, options) - .toBlocking().single().getResource(); + .single().block().getResource(); return createdCollection; } diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java index 571f1cc78d6f2..f295ccea9ae99 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java @@ -38,8 +38,8 @@ import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Observable; -import rx.observables.GroupedObservable; +import reactor.core.publisher.Flux; +import reactor.core.publisher.GroupedFlux; import java.time.LocalDateTime; import java.util.ArrayList; @@ -54,7 +54,7 @@ public class InMemoryGroupbyTest extends DocumentClientTest { private Database createdDatabase; private DocumentCollection createdCollection; - @BeforeClass(groups = "samples", timeOut = TIMEOUT) + @BeforeClass(groups = "samples", timeOut = 2 * TIMEOUT) public void setUp() throws Exception { ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT); @@ -81,7 +81,7 @@ public void setUp() throws Exception { // CREATE collection createdCollection = client .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) - .toBlocking().single().getResource(); + .single().block().getResource(); int numberOfPayers = 10; int numberOfDocumentsPerPayer = 10; @@ -98,7 +98,7 @@ public void setUp() throws Exception { + "'payer_id': %d, " + " 'created_time' : %d " + "}", UUID.randomUUID().toString(), i, currentTime.getSecond())); - client.createDocument(getCollectionLink(), doc, null, true).toBlocking().single(); + client.createDocument(getCollectionLink(), doc, null, true).single().block(); Thread.sleep(100); } @@ -117,7 +117,7 @@ public void shutdown() { * If you want to understand the steps in more details see {@link #groupByInMemory_MoreDetail()} * @throws Exception */ - @Test(groups = "samples", timeOut = TIMEOUT) + @Test(groups = "samples", timeOut = 2 * TIMEOUT) public void groupByInMemory() { // If you want to understand the steps in more details see groupByInMemoryMoreDetail() int requestPageSize = 3; @@ -125,21 +125,20 @@ public void groupByInMemory() { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable documentsObservable = client + Flux documentsObservable = client .queryDocuments(getCollectionLink(), new SqlQuerySpec("SELECT * FROM root r WHERE r.site_id=@site_id", new SqlParameterCollection(new SqlParameter("@site_id", "ABC"))), options) - .flatMap(page -> Observable.from(page.results())); + .flatMap(page -> Flux.fromIterable(page.results())); final LocalDateTime now = LocalDateTime.now(); List> resultsGroupedAsLists = documentsObservable .filter(doc -> Math.abs(now.getSecond() - doc.getInt("created_time")) <= 90) - .groupBy(doc -> doc.getInt("payer_id")).flatMap(grouped -> grouped.toList()) - .toList() - .toBlocking() - .single(); + .groupBy(doc -> doc.getInt("payer_id")).flatMap(Flux::collectList) + .collectList() + .block(); for(List resultsForEachPayer :resultsGroupedAsLists) { System.out.println("documents with payer_id : " + resultsForEachPayer.get(0).getInt("payer_id") + " are " + resultsForEachPayer); @@ -150,7 +149,7 @@ public void groupByInMemory() { * This does the same thing as {@link #groupByInMemory_MoreDetail()} but with pedagogical details * @throws Exception */ - @Test(groups = "samples", timeOut = TIMEOUT) + @Test(groups = "samples", timeOut = 2 * TIMEOUT) public void groupByInMemory_MoreDetail() { int requestPageSize = 3; @@ -158,25 +157,25 @@ public void groupByInMemory_MoreDetail() { options.maxItemCount(requestPageSize); options.enableCrossPartitionQuery(true); - Observable documentsObservable = client + Flux documentsObservable = client .queryDocuments(getCollectionLink(), new SqlQuerySpec("SELECT * FROM root r WHERE r.site_id=@site_id", new SqlParameterCollection(new SqlParameter("@site_id", "ABC"))), options) - .flatMap(page -> Observable.from(page.results())); + .flatMap(page -> Flux.fromIterable(page.results())); final LocalDateTime now = LocalDateTime.now(); - Observable> groupedByPayerIdObservable = documentsObservable + Flux> groupedByPayerIdObservable = documentsObservable .filter(doc -> Math.abs(now.getSecond() - doc.getInt("created_time")) <= 90) .groupBy(doc -> doc.getInt("payer_id")); - Observable> docsGroupedAsList = groupedByPayerIdObservable.flatMap(grouped -> { - Observable> list = grouped.toList(); + Flux> docsGroupedAsList = groupedByPayerIdObservable.flatMap(grouped -> { + Flux> list = grouped.collectList().flux(); return list; }); - List> resultsGroupedAsLists = docsGroupedAsList.toList().toBlocking().single(); + List> resultsGroupedAsLists = docsGroupedAsList.collectList().single().block(); for(List resultsForEachPayer : resultsGroupedAsLists) { System.out.println("documents with payer_id : " + resultsForEachPayer.get(0).getInt("payer_id") + " are " + resultsForEachPayer); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java index 39a1a21497dd6..8572869e0399b 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java @@ -98,7 +98,7 @@ public void updateOffer() throws Exception { // CREATE the collection DocumentCollection createdCollection = client.createCollection("dbs/" + createdDatabase.id(), - getMultiPartitionCollectionDefinition(), multiPartitionRequestOptions).toBlocking().single() + getMultiPartitionCollectionDefinition(), multiPartitionRequestOptions).single().block() .getResource(); final CountDownLatch successfulCompletionLatch = new CountDownLatch(1); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java index 0549f86f152c1..09a9aef2772d7 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java @@ -83,7 +83,7 @@ public void setUp() { createdCollection = client .createCollection("dbs/" + createdDatabase.id(), getMultiPartitionCollectionDefinition(), null) - .toBlocking().single().getResource(); + .single().block().getResource(); } @AfterClass(groups = "samples", timeOut = TIMEOUT) @@ -116,7 +116,7 @@ public void scriptConsoleLogEnabled() throws Exception { "}"); storedProcedure = client.createStoredProcedure(getCollectionLink(), storedProcedure, null) - .toBlocking().single().getResource(); + .single().block().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setScriptLoggingEnabled(true); @@ -162,7 +162,7 @@ public void executeStoredProcWithArgs() throws Exception { "}"); storedProcedure = client.createStoredProcedure(getCollectionLink(), storedProcedure, null) - .toBlocking().single().getResource(); + .single().block().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey("Seattle")); @@ -202,7 +202,7 @@ public void executeStoredProcWithPojoArgs() throws Exception { "}"); storedProcedure = client.createStoredProcedure(getCollectionLink(), storedProcedure, null) - .toBlocking().single().getResource(); + .single().block().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey("Seattle")); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java index 2f2e36953f05b..b99f32c256d86 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java @@ -44,7 +44,7 @@ import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.Collections; @@ -60,7 +60,7 @@ public class TokenResolverTest extends DocumentClientTest { - private final static int TIMEOUT = 60000; + private final static int TIMEOUT = 180000; private final static String USER_ID = "userId"; private AsyncDocumentClient client; private Database createdDatabase; @@ -103,18 +103,18 @@ public void setUp() { // CREATE collection createdCollection = client .createCollection("dbs/" + createdDatabase.id(), collectionDefinition, null) - .toBlocking().single().getResource(); + .single().block().getResource(); for (int i = 0; i < 10; i++) { // CREATE a document Document documentDefinition = new Document(); documentDefinition.id(UUID.randomUUID().toString()); - Document createdDocument = client.createDocument(createdCollection.selfLink(), documentDefinition, null, true).toBlocking().first().getResource(); + Document createdDocument = client.createDocument(createdCollection.selfLink(), documentDefinition, null, true).blockFirst().getResource(); // CREATE a User who is meant to only read this document User readUserDefinition = new User(); readUserDefinition.id(UUID.randomUUID().toString()); - User createdReadUser = client.createUser(createdDatabase.selfLink(), readUserDefinition, null).toBlocking().first().getResource(); + User createdReadUser = client.createUser(createdDatabase.selfLink(), readUserDefinition, null).blockFirst().getResource(); // CREATE a read only permission for the above document Permission readOnlyPermissionDefinition = new Permission(); @@ -123,7 +123,7 @@ public void setUp() { readOnlyPermissionDefinition.setPermissionMode(PermissionMode.READ); // Assign the permission to the above user - Permission readOnlyCreatedPermission = client.createPermission(createdReadUser.selfLink(), readOnlyPermissionDefinition, null).toBlocking().first().getResource(); + Permission readOnlyCreatedPermission = client.createPermission(createdReadUser.selfLink(), readOnlyPermissionDefinition, null).blockFirst().getResource(); userToReadOnlyResourceTokenMap.put(createdReadUser.id(), readOnlyCreatedPermission.getToken()); documentToReadUserMap.put(createdDocument.selfLink(), createdReadUser.id()); @@ -131,7 +131,7 @@ public void setUp() { // CREATE a User who can both read and write this document User readWriteUserDefinition = new User(); readWriteUserDefinition.id(UUID.randomUUID().toString()); - User createdReadWriteUser = client.createUser(createdDatabase.selfLink(), readWriteUserDefinition, null).toBlocking().first().getResource(); + User createdReadWriteUser = client.createUser(createdDatabase.selfLink(), readWriteUserDefinition, null).blockFirst().getResource(); // CREATE a read/write permission for the above document Permission readWritePermissionDefinition = new Permission(); @@ -140,7 +140,7 @@ public void setUp() { readWritePermissionDefinition.setPermissionMode(PermissionMode.ALL); // Assign the permission to the above user - Permission readWriteCreatedPermission = client.createPermission(createdReadWriteUser.selfLink(), readWritePermissionDefinition, null).toBlocking().first().getResource(); + Permission readWriteCreatedPermission = client.createPermission(createdReadWriteUser.selfLink(), readWritePermissionDefinition, null).blockFirst().getResource(); userToReadWriteResourceTokenMap.put(createdReadWriteUser.id(), readWriteCreatedPermission.getToken()); documentToReadWriteUserMap.put(createdDocument.selfLink(), createdReadWriteUser.id()); @@ -174,13 +174,10 @@ public void readDocumentThroughTokenResolver() throws Exception { RequestOptions requestOptions = new RequestOptions(); requestOptions.setProperties(properties); requestOptions.setPartitionKey(PartitionKey.None); - Observable> readDocumentObservable = asyncClientWithTokenResolver + Flux> readDocumentObservable = asyncClientWithTokenResolver .readDocument(documentLink, requestOptions); - readDocumentObservable.subscribe(resourceResponse -> { - capturedResponse.add(resourceResponse); - }); + readDocumentObservable.collectList().block().forEach(capturedResponse::add); } - Thread.sleep(2000); System.out.println("capturedResponse.size() = " + capturedResponse.size()); assertThat(capturedResponse, hasSize(10)); } finally { @@ -216,13 +213,10 @@ public void deleteDocumentThroughTokenResolver() throws Exception { RequestOptions requestOptions = new RequestOptions(); requestOptions.setProperties(properties); requestOptions.setPartitionKey(PartitionKey.None); - Observable> readDocumentObservable = asyncClientWithTokenResolver + Flux> readDocumentObservable = asyncClientWithTokenResolver .deleteDocument(documentLink, requestOptions); - readDocumentObservable.subscribe(resourceResponse -> { - capturedResponse.add(resourceResponse); - }); + readDocumentObservable.collectList().block().forEach(capturedResponse::add); } - Thread.sleep(2000); assertThat(capturedResponse, hasSize(10)); } finally { Utils.safeClose(asyncClientWithTokenResolver); @@ -257,11 +251,11 @@ public void blockListUserThroughTokenResolver() throws Exception { .build(); options.setProperties(properties); - Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); + Flux> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); List capturedErrors = Collections .synchronizedList(new ArrayList<>()); readObservable.subscribe(response -> {}, throwable -> capturedErrors.add(throwable)); - Thread.sleep(2000); + Thread.sleep(4000); assertThat(capturedErrors, hasSize(1)); assertThat(capturedErrors.get(0), instanceOf(RuntimeException.class)); assertThat(capturedErrors.get(0).getMessage(), equalTo(errorMessage)); @@ -278,7 +272,7 @@ public void blockListUserThroughTokenResolver() throws Exception { List capturedResponse = Collections .synchronizedList(new ArrayList<>()); readObservable.subscribe(resourceResponse -> capturedResponse.add(resourceResponse.getResource()), error -> error.printStackTrace()); - Thread.sleep(2000); + Thread.sleep(4000); assertThat(capturedErrors, hasSize(1)); assertThat(capturedResponse.get(0).id(), equalTo(createdCollection.id())); } finally { diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java index 44c8b56193ee4..1bceda236660e 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java @@ -36,11 +36,12 @@ import com.azure.data.cosmos.UniqueKey; import com.azure.data.cosmos.UniqueKeyPolicy; import com.google.common.collect.ImmutableList; +import io.reactivex.subscribers.TestSubscriber; +import org.hamcrest.Matchers; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Observable; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.Collections; @@ -48,7 +49,6 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; public class UniqueIndexAsyncAPITest extends DocumentClientTest { @@ -72,18 +72,18 @@ public void uniqueIndex() { partitionKeyDef.paths(paths); collectionDefinition.setPartitionKey(partitionKeyDef); - DocumentCollection collection = client.createCollection(getDatabaseLink(), collectionDefinition, null).toBlocking().single().getResource(); + DocumentCollection collection = client.createCollection(getDatabaseLink(), collectionDefinition, null).single().block().getResource(); Document doc1 = new Document("{ 'name':'Alan Turning', 'field': 'Mathematics', 'other' : 'Logic' }"); Document doc2 = new Document("{ 'name':'Al-Khwarizmi', 'field': 'Mathematics' , 'other' : 'Algebra '}"); Document doc3 = new Document("{ 'name':'Alan Turning', 'field': 'Mathematics', 'other' : 'CS' }"); - client.createDocument(getCollectionLink(collection), doc1, null, false).toBlocking().single().getResource(); - client.createDocument(getCollectionLink(collection), doc2, null, false).toBlocking().single().getResource(); + client.createDocument(getCollectionLink(collection), doc1, null, false).single().block().getResource(); + client.createDocument(getCollectionLink(collection), doc2, null, false).single().block().getResource(); // doc1 got inserted with the same values for 'name' and 'field' // so inserting a new one with the same values will violate unique index constraint. - Observable> docCreation = + Flux> docCreation = client.createDocument(getCollectionLink(collection), doc3, null, false); TestSubscriber> subscriber = new TestSubscriber<>(); @@ -91,10 +91,10 @@ public void uniqueIndex() { subscriber.awaitTerminalEvent(); subscriber.assertError(CosmosClientException.class); - assertThat(subscriber.getOnErrorEvents(), hasSize(1)); + assertThat(subscriber.errorCount(), Matchers.equalTo(1)); // error code for failure is conflict - assertThat(((CosmosClientException) subscriber.getOnErrorEvents().get(0)).statusCode(), equalTo(409)); + assertThat(((CosmosClientException) subscriber.getEvents().get(1).get(0)).statusCode(), equalTo(409)); } @BeforeClass(groups = "samples", timeOut = TIMEOUT) diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java index 32d9bdd93aeb9..c5de4b904b1b5 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java @@ -35,7 +35,7 @@ import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.rx.TestConfigurations; import org.testng.annotations.AfterSuite; -import rx.Observable; +import reactor.core.publisher.Flux; public class Utils { @@ -77,7 +77,7 @@ public static void safeClean(AsyncDocumentClient client, String databaseId) { if (client != null) { if (databaseId != null) { try { - client.deleteDatabase("/dbs/" + databaseId, null).toBlocking().single(); + client.deleteDatabase("/dbs/" + databaseId, null).single().block(); } catch (Exception e) { } } @@ -106,17 +106,17 @@ private DatabaseManagerImpl(AsyncDocumentClient client) { } @Override - public Observable> queryDatabases(SqlQuerySpec query) { + public Flux> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override - public Observable> createDatabase(Database databaseDefinition) { + public Flux> createDatabase(Database databaseDefinition) { return client.createDatabase(databaseDefinition, null); } @Override - public Observable> deleteDatabase(String id) { + public Flux> deleteDatabase(String id) { return client.deleteDatabase("dbs/" + id, null); } diff --git a/gateway/pom.xml b/gateway/pom.xml index d382cfcdc2b3e..0a506a584c772 100644 --- a/gateway/pom.xml +++ b/gateway/pom.xml @@ -132,5 +132,18 @@ SOFTWARE. ${guava.version} test + + io.projectreactor.netty + reactor-netty + + + io.reactivex.rxjava2 + rxjava + ${rxjava2.version} + + + io.projectreactor.addons + reactor-adapter + diff --git a/gateway/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java b/gateway/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java index 31e7242f868ee..3606f07eff051 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java +++ b/gateway/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos; -import rx.Observable; +import reactor.core.publisher.Flux; import java.net.URI; @@ -34,7 +34,7 @@ public interface DatabaseAccountManagerInternal { * @param endpoint the endpoint from which gets the database account * @return the database account. */ - Observable getDatabaseAccountFromEndpoint(URI endpoint); + Flux getDatabaseAccountFromEndpoint(URI endpoint); /** * Gets the connection policy diff --git a/gateway/src/main/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtility.java b/gateway/src/main/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtility.java index bf3e24dadbfcf..0da7d3d68d975 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtility.java +++ b/gateway/src/main/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtility.java @@ -25,7 +25,6 @@ import com.azure.data.cosmos.internal.Utils; import io.netty.channel.ChannelException; -import io.reactivex.netty.client.PoolExhaustedException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLPeerUnverifiedException; @@ -51,9 +50,6 @@ public static boolean isWebExceptionRetriable(Exception ex) { } private static boolean isWebExceptionRetriableInternal(Exception ex) { - if (ex instanceof PoolExhaustedException) { - return true; - } IOException webEx = Utils.as(ex, IOException.class); if (webEx == null) { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java b/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java index 1d2bd67ef18de..b319ede033e03 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java @@ -22,13 +22,11 @@ */ package com.azure.data.cosmos.internal; -import rx.Observable; -import rx.Single; -import rx.functions.Action1; -import rx.functions.Func0; -import rx.functions.Func1; +import reactor.core.publisher.Mono; import java.time.Duration; +import java.util.concurrent.Callable; +import java.util.function.Function; /** * While this class is public, but it is not part of our published public APIs. @@ -41,75 +39,34 @@ public class BackoffRetryUtility { public static final Quadruple InitialArgumentValuePolicyArg = Quadruple.with(false, false, Duration.ofSeconds(60), 0); - static Func1, Observable> toRetryWhenFunc( - Func1> retryFunc, Action1 preRetryCallback) { - - return new Func1, Observable>() { - - @Override - public Observable call(Observable t) { - - return t.flatMap(f -> { - Exception e = Utils.as(f, Exception.class); - if (e instanceof Exception) { - if (preRetryCallback != null) { - - // TODO: is retry callback invoked immediately on the same thread? - // we should verify this - return retryFunc.call(e).doOnSuccess(v -> preRetryCallback.call(e)).toObservable(); - } else { - return retryFunc.call(e).toObservable(); - } - } else { - return Observable.error(f); - } - }); - } - }; - } - - @SuppressWarnings("unused") - static private Single executeRetry(Func0> callbackMethod, - Func1> callShouldRetry, Action1 preRetryCallback) { - - return Single.defer(() -> { - return callbackMethod.call(); - - }).retryWhen(toRetryWhenFunc(callShouldRetry, preRetryCallback)); - } - // a helper method for invoking callback method given the retry policy. // it also invokes the pre retry callback prior to retrying - static public Single executeRetry(Func0> callbackMethod, - IRetryPolicy retryPolicy, - Action1 preRetryCallback) { - return Single.defer(() -> { - // TODO: is defer required? - return callbackMethod.call(); - }).retryWhen(RetryUtils.toRetryWhenFunc(retryPolicy)); - } + // a helper method for invoking callback method given the retry policy // a helper method for invoking callback method given the retry policy - static public Single executeRetry(Func0> callbackMethod, - IRetryPolicy retryPolicy) { + static public Mono executeRetry(Callable> callbackMethod, + IRetryPolicy retryPolicy) { - return Single.defer(() -> { + return Mono.defer(() -> { // TODO: is defer required? - return callbackMethod.call(); + try { + return callbackMethod.call(); + } catch (Exception e) { + return Mono.error(e); + } }).retryWhen(RetryUtils.toRetryWhenFunc(retryPolicy)); } - static public Single executeAsync( - Func1, Single> callbackMethod, IRetryPolicy retryPolicy, - Func1, Single> inBackoffAlternateCallbackMethod, + static public Mono executeAsync( + Function, Mono> callbackMethod, IRetryPolicy retryPolicy, + Function, Mono> inBackoffAlternateCallbackMethod, Duration minBackoffForInBackoffCallback) { - Quadruple policyArg1 = InitialArgumentValuePolicyArg; - - return Single.defer(() -> { + + return Mono.defer(() -> { // TODO: is defer required? - return callbackMethod.call(policyArg1).onErrorResumeNext( - RetryUtils.toRetryWithAlternateFunc(callbackMethod,retryPolicy, inBackoffAlternateCallbackMethod,minBackoffForInBackoffCallback)); + return callbackMethod.apply(InitialArgumentValuePolicyArg).onErrorResume( + RetryUtils.toRetryWithAlternateFunc(callbackMethod, retryPolicy, inBackoffAlternateCallbackMethod,minBackoffForInBackoffCallback)); }); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java index 0ef14e768b1f7..75a992fe1baf6 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.ISessionContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; +import reactor.core.publisher.Mono; /** * While this class is public, but it is not part of our published public APIs. @@ -59,7 +59,7 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { } @Override - public Single shouldRetry(Exception e) { + public Mono shouldRetry(Exception e) { return this.retryPolicy.shouldRetry(e).flatMap(shouldRetryResult -> { @@ -70,7 +70,7 @@ public Single shouldRetry(Exception e) { if (this.request == null) { // someone didn't call OnBeforeSendRequest - nothing we can do logger.error("onBeforeSendRequest is not invoked, encountered failure due to request being null", e); - return Single.just(ShouldRetryResult.error(e)); + return Mono.just(ShouldRetryResult.error(e)); } if (clientException != null && this.request.getIsNameBased() && @@ -86,7 +86,7 @@ public Single shouldRetry(Exception e) { } } - return Single.just(shouldRetryResult); + return Mono.just(shouldRetryResult); }); } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java index 30a5fa0323939..cb4722343f61f 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java @@ -29,7 +29,7 @@ import org.apache.commons.collections4.list.UnmodifiableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; +import reactor.core.publisher.Mono; import java.net.URL; import java.time.Duration; @@ -48,7 +48,6 @@ public class ClientRetryPolicy implements IDocumentClientRetryPolicy { final static int MaxRetryCount = 120; private final IDocumentClientRetryPolicy throttlingRetry; - private final ConnectionPoolExhaustedRetry rxNettyConnectionPoolExhaustedRetry; private final GlobalEndpointManager globalEndpointManager; private final boolean enableEndpointDiscovery; private int failoverRetryCount; @@ -67,7 +66,6 @@ public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, this.throttlingRetry = new ResourceThrottleRetryPolicy( retryOptions.maxRetryAttemptsOnThrottledRequests(), retryOptions.maxRetryWaitTimeInSeconds()); - this.rxNettyConnectionPoolExhaustedRetry = new ConnectionPoolExhaustedRetry(); this.globalEndpointManager = globalEndpointManager; this.failoverRetryCount = 0; this.enableEndpointDiscovery = enableEndpointDiscovery; @@ -77,16 +75,12 @@ public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, } @Override - public Single shouldRetry(Exception e) { + public Mono shouldRetry(Exception e) { if (this.locationEndpoint == null) { // on before request is not invoked because Document Service Request creation failed. logger.error("locationEndpoint is null because ClientRetryPolicy::onBeforeRequest(.) is not invoked, " + "probably request creation failed due to invalid options, serialization setting, etc."); - return Single.just(ShouldRetryResult.error(e)); - } - - if (ConnectionPoolExhaustedRetry.isConnectionPoolExhaustedException(e)) { - return rxNettyConnectionPoolExhaustedRetry.shouldRetry(e); + return Mono.just(ShouldRetryResult.error(e)); } this.retryContext = null; @@ -122,7 +116,7 @@ public Single shouldRetry(Exception e) { if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.NOTFOUND) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE)) { - return Single.just(this.shouldRetryOnSessionNotAvailable()); + return Mono.just(this.shouldRetryOnSessionNotAvailable()); } return this.throttlingRetry.shouldRetry(e); @@ -159,10 +153,10 @@ private ShouldRetryResult shouldRetryOnSessionNotAvailable() { } } - private Single shouldRetryOnEndpointFailureAsync(boolean isReadRequest) { + private Mono shouldRetryOnEndpointFailureAsync(boolean isReadRequest) { if (!this.enableEndpointDiscovery || this.failoverRetryCount > MaxRetryCount) { logger.warn("ShouldRetryOnEndpointFailureAsync() Not retrying. Retry count = {}", this.failoverRetryCount); - return Single.just(ShouldRetryResult.noRetry()); + return Mono.just(ShouldRetryResult.noRetry()); } this.failoverRetryCount++; @@ -192,7 +186,7 @@ private Single shouldRetryOnEndpointFailureAsync(boolean isRe } this.retryContext = new RetryContext(this.failoverRetryCount, false); return this.globalEndpointManager.refreshLocationAsync(null) - .andThen(Single.just(ShouldRetryResult.retryAfter(retryDelay))); + .then(Mono.just(ShouldRetryResult.retryAfter(retryDelay))); } @Override diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetry.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetry.java deleted file mode 100644 index b44d37ba4e262..0000000000000 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetry.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.azure.data.cosmos.internal; - -import io.reactivex.netty.client.PoolExhaustedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import rx.Single; - -import java.time.Duration; - -// rxnetty in servicing a new request throws PoolExhaustedException -// if all connections are in used and max connection pool size is configured. -class ConnectionPoolExhaustedRetry implements IDocumentClientRetryPolicy { - private static final Logger logger = LoggerFactory.getLogger(ConnectionPoolExhaustedRetry.class); - static final Duration RETRY_WAIT_TIME = Duration.ofMillis(10); - static final int MAX_RETRY_COUNT = 10; - - private int retryCount = 0; - - @Override - public Single shouldRetry(Exception e) { - boolean isConnectionPoolExhaustedException = isConnectionPoolExhaustedException(e); - assert isConnectionPoolExhaustedException; - if (!isConnectionPoolExhaustedException) { - logger.error("Fatal error invalid retry path for {}", e.getMessage(), e); - return Single.just(ShouldRetryResult.error(e)); - } - - if (++retryCount <= MAX_RETRY_COUNT) { - logger.warn("PoolExhaustedException failure indicates" + - " the load on the SDK is higher than what current connection pool size can support" + - " either increase the connection pool size for the configured connection mode," + - " or distribute the load on more machines. retry count {}", retryCount); - return Single.just(ShouldRetryResult.retryAfter(RETRY_WAIT_TIME)); - } else { - logger.error("PoolExhaustedException failure indicates" + - " the load on the SDK is higher than what current connection pool size can support" + - " either increase the connection pool size for the configured connection mode," + - " or distribute the load on more machines. ALL retries exhausted!"); - return Single.just(ShouldRetryResult.error(e)); - } - } - - @Override - public void onBeforeSendRequest(RxDocumentServiceRequest request) { - // no op - } - - static boolean isConnectionPoolExhaustedException(Exception ex) { - while (ex != null) { - if (ex instanceof PoolExhaustedException) { - return true; - } - - Throwable t = ex.getCause(); - if (!(t instanceof Exception)) { - break; - } - - ex = (Exception) t; - } - - return false; - } -} diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java b/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java index e5f9de5aea0f2..24a56c6bd3d9f 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java @@ -32,23 +32,22 @@ import org.apache.commons.collections4.list.UnmodifiableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Completable; -import rx.Observable; -import rx.Scheduler; -import rx.Single; -import rx.functions.Func1; -import rx.schedulers.Schedulers; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Scheduler; +import reactor.core.scheduler.Schedulers; import java.net.URISyntaxException; import java.net.URL; +import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; /** * Endpoint region cache manager implementation. Supports cross region address routing based on @@ -64,7 +63,7 @@ public class GlobalEndpointManager implements AutoCloseable { private final DatabaseAccountManagerInternal owner; private final AtomicBoolean isRefreshing; private final ExecutorService executor = Executors.newSingleThreadExecutor(); - private final Scheduler scheduler = Schedulers.from(executor); + private final Scheduler scheduler = Schedulers.fromExecutor(executor); private volatile boolean isClosed; public GlobalEndpointManager(DatabaseAccountManagerInternal owner, ConnectionPolicy connectionPolicy, Configs configs) { @@ -94,7 +93,7 @@ public GlobalEndpointManager(DatabaseAccountManagerInternal owner, ConnectionPol public void init() { // TODO: add support for openAsync // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/332589 - startRefreshLocationTimerAsync(true).toCompletable().await(); + startRefreshLocationTimerAsync(true).block(); } public UnmodifiableList getReadEndpoints() { @@ -107,25 +106,23 @@ public UnmodifiableList getWriteEndpoints() { return this.locationCache.getWriteEndpoints(); } - public static Single getDatabaseAccountFromAnyLocationsAsync( - URL defaultEndpoint, List locations, Func1> getDatabaseAccountFn) { + public static Mono getDatabaseAccountFromAnyLocationsAsync( + URL defaultEndpoint, List locations, Function> getDatabaseAccountFn) { - return getDatabaseAccountFn.call(defaultEndpoint).onErrorResumeNext( + return getDatabaseAccountFn.apply(defaultEndpoint).onErrorResume( e -> { logger.error("Fail to reach global gateway [{}], [{}]", defaultEndpoint, e.getMessage()); if (locations.isEmpty()) { - return Single.error(e); + return Mono.error(e); } - Observable> obs = Observable.range(0, locations.size()) - .map(index -> getDatabaseAccountFn.call(LocationHelper.getLocationEndpoint(defaultEndpoint, locations.get(index))).toObservable()); + Flux> obs = Flux.range(0, locations.size()) + .map(index -> getDatabaseAccountFn.apply(LocationHelper.getLocationEndpoint(defaultEndpoint, locations.get(index))).flux()); // iterate and get the database account from the first non failure, otherwise get the last error. - Observable res = Observable.concatDelayError(obs).first().single(); - return res.toSingle().doOnError( - innerE -> { - logger.error("Fail to reach location any of locations", String.join(",", locations), innerE.getMessage()); - }); + Mono res = Flux.concatDelayError(obs).take(1).single(); + return res.doOnError( + innerE -> logger.error("Fail to reach location any of locations {} {}", String.join(",", locations), innerE.getMessage())); }); } @@ -153,12 +150,12 @@ public void close() { logger.debug("GlobalEndpointManager closed."); } - public Completable refreshLocationAsync(DatabaseAccount databaseAccount) { - return Completable.defer(() -> { + public Mono refreshLocationAsync(DatabaseAccount databaseAccount) { + return Mono.defer(() -> { logger.debug("refreshLocationAsync() invoked"); if (!isRefreshing.compareAndSet(false, true)) { logger.debug("in the middle of another refresh. Not invoking a new refresh."); - return Completable.complete(); + return Mono.empty(); } logger.debug("will refresh"); @@ -166,44 +163,44 @@ public Completable refreshLocationAsync(DatabaseAccount databaseAccount) { }); } - private Completable refreshLocationPrivateAsync(DatabaseAccount databaseAccount) { - return Completable.defer(() -> { + private Mono refreshLocationPrivateAsync(DatabaseAccount databaseAccount) { + return Mono.defer(() -> { logger.debug("refreshLocationPrivateAsync() refreshing locations"); if (databaseAccount != null) { this.locationCache.onDatabaseAccountRead(databaseAccount); } - Utils.ValueHolder canRefreshInBackground = new Utils.ValueHolder(); + Utils.ValueHolder canRefreshInBackground = new Utils.ValueHolder<>(); if (this.locationCache.shouldRefreshEndpoints(canRefreshInBackground)) { logger.debug("shouldRefreshEndpoints: true"); if (databaseAccount == null && !canRefreshInBackground.v) { logger.debug("shouldRefreshEndpoints: can't be done in background"); - Single databaseAccountObs = getDatabaseAccountFromAnyLocationsAsync( + Mono databaseAccountObs = getDatabaseAccountFromAnyLocationsAsync( this.defaultEndpoint, new ArrayList<>(this.connectionPolicy.preferredLocations()), - url -> this.getDatabaseAccountAsync(url)); + this::getDatabaseAccountAsync); return databaseAccountObs.map(dbAccount -> { this.locationCache.onDatabaseAccountRead(dbAccount); return dbAccount; - }).flatMapCompletable(dbAccount -> { + }).flatMap(dbAccount -> { // trigger a startRefreshLocationTimerAsync don't wait on it. this.startRefreshLocationTimerAsync(); - return Completable.complete(); + return Mono.empty(); }); } // trigger a startRefreshLocationTimerAsync don't wait on it. this.startRefreshLocationTimerAsync(); - return Completable.complete(); + return Mono.empty(); } else { logger.debug("shouldRefreshEndpoints: false, nothing to do."); this.isRefreshing.set(false); - return Completable.complete(); + return Mono.empty(); } }); } @@ -212,12 +209,12 @@ private void startRefreshLocationTimerAsync() { startRefreshLocationTimerAsync(false).subscribe(); } - private Observable startRefreshLocationTimerAsync(boolean initialization) { + private Mono startRefreshLocationTimerAsync(boolean initialization) { if (this.isClosed) { logger.debug("startRefreshLocationTimerAsync: nothing to do, it is closed"); // if client is already closed, nothing to be done, just return. - return Observable.empty(); + return Mono.empty(); } logger.debug("registering a refresh in [{}] ms", this.backgroundRefreshLocationTimeIntervalInMS); @@ -225,37 +222,37 @@ private Observable startRefreshLocationTimerAsync(boolean initialization) { int delayInMillis = initialization ? 0: this.backgroundRefreshLocationTimeIntervalInMS; - return Observable.timer(delayInMillis, TimeUnit.MILLISECONDS) - .toSingle().flatMapCompletable( + return Mono.delay(Duration.ofMillis(delayInMillis)) + .flatMap( t -> { if (this.isClosed) { logger.warn("client already closed"); // if client is already closed, nothing to be done, just return. - return Completable.complete(); + return Mono.empty(); } logger.debug("startRefreshLocationTimerAsync() - Invoking refresh, I was registered on [{}]", now); - Single databaseAccountObs = GlobalEndpointManager.getDatabaseAccountFromAnyLocationsAsync(this.defaultEndpoint, new ArrayList<>(this.connectionPolicy.preferredLocations()), - url -> this.getDatabaseAccountAsync(url)).toObservable().toSingle(); + Mono databaseAccountObs = GlobalEndpointManager.getDatabaseAccountFromAnyLocationsAsync(this.defaultEndpoint, new ArrayList<>(this.connectionPolicy.preferredLocations()), + this::getDatabaseAccountAsync); - return databaseAccountObs.flatMapCompletable(dbAccount -> { + return databaseAccountObs.flatMap(dbAccount -> { logger.debug("db account retrieved"); return this.refreshLocationPrivateAsync(dbAccount); }); - }).onErrorResumeNext(ex -> { + }).onErrorResume(ex -> { logger.error("startRefreshLocationTimerAsync() - Unable to refresh database account from any location. Exception: {}", ex.toString(), ex); this.startRefreshLocationTimerAsync(); - return Completable.complete(); - }).toObservable().subscribeOn(scheduler); + return Mono.empty(); + }).subscribeOn(scheduler); } - private Single getDatabaseAccountAsync(URL serviceEndpoint) { + private Mono getDatabaseAccountAsync(URL serviceEndpoint) { try { return this.owner.getDatabaseAccountFromEndpoint(serviceEndpoint.toURI()) - .doOnNext(i -> logger.debug("account retrieved: {}", i)).toSingle(); + .doOnNext(i -> logger.debug("account retrieved: {}", i)).single(); } catch (URISyntaxException e) { - return Single.error(e); + return Mono.error(e); } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java index c3be709965255..1ac11e218facb 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; -import rx.Single; +import reactor.core.publisher.Mono; import java.util.Map; @@ -33,14 +33,14 @@ * This is meant to be internally used only by our sdk. **/ public interface ICollectionRoutingMapCache { - default Single tryLookupAsync( + default Mono tryLookupAsync( String collectionRid, CollectionRoutingMap previousValue, Map properties) { return tryLookupAsync(collectionRid, previousValue, false, properties); } - Single tryLookupAsync( + Mono tryLookupAsync( String collectionRid, CollectionRoutingMap previousValue, boolean forceRefreshCollectionRoutingMap, diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java index efb7f03f0f246..b1ce820c586d8 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos.internal; -import rx.Single; +import reactor.core.publisher.Mono; /** * While this class is public, but it is not part of our published public APIs. @@ -63,8 +63,8 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { } @Override - public Single shouldRetry(Exception e) { - return Single.just(ShouldRetryResult.error(e)); + public Mono shouldRetry(Exception e) { + return Mono.just(ShouldRetryResult.error(e)); } } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java index f1fcab0f6f4bc..84e753bf33d03 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal; -import rx.Single; +import reactor.core.publisher.Mono; import java.time.Duration; @@ -42,7 +42,7 @@ public interface IRetryPolicy { /// Exception during the callback method invocation /// /// If the retry needs to be attempted or not - Single shouldRetry(Exception e); + Mono shouldRetry(Exception e); class ShouldRetryResult { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java index ef8f4fa74868e..1b92a019695f4 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.internal.routing.Range; -import rx.Single; +import reactor.core.publisher.Mono; import java.util.List; import java.util.Map; @@ -43,9 +43,9 @@ public interface IRoutingMapProvider { /// This method will return all ranges which overlap this range. /// Whether forcefully refreshing the routing map is necessary /// List of effective partition key ranges for a collection or null if collection doesn't exist. - Single> tryGetOverlappingRangesAsync(String collectionResourceId, Range range, - boolean forceRefresh /* = false */, Map properties); + Mono> tryGetOverlappingRangesAsync(String collectionResourceId, Range range, + boolean forceRefresh /* = false */, Map properties); - Single tryGetPartitionKeyRangeByIdAsync(String collectionResourceId, String partitionKeyRangeId, + Mono tryGetPartitionKeyRangeByIdAsync(String collectionResourceId, String partitionKeyRangeId, boolean forceRefresh /* = false */, Map properties); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java index 6a046bcf434d0..37695b2958640 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.WFConstants; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -59,7 +59,7 @@ public InvalidPartitionException(String msg, String resourceAddress) { setSubStatus(); } - public InvalidPartitionException(String message, HttpResponseHeaders headers, String requestUri) { + public InvalidPartitionException(String message, HttpHeaders headers, String requestUri) { this(message, null, headers, requestUri); } @@ -69,7 +69,7 @@ public InvalidPartitionException(Exception innerException) { public InvalidPartitionException(String message, Exception innerException, - HttpResponseHeaders headers, + HttpHeaders headers, String requestUri) { super(String.format("%s: %s", RMResources.Gone, message), innerException, diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java index 15caec2ee57c3..a76203f6e2cea 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.internal.caches.RxCollectionCache; -import rx.Single; +import reactor.core.publisher.Mono; import java.time.Duration; @@ -61,7 +61,7 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { } @Override - public Single shouldRetry(Exception e) { + public Mono shouldRetry(Exception e) { CosmosClientException clientException = Utils.as(e, CosmosClientException.class); if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.GONE) && @@ -77,9 +77,9 @@ public Single shouldRetry(Exception e) { } this.retried = true; - return Single.just(ShouldRetryResult.retryAfter(Duration.ZERO)); + return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); } else { - return Single.just(ShouldRetryResult.error(e)); + return Mono.just(ShouldRetryResult.error(e)); } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java index 67d40708440f0..3318eddc646f7 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Error; import com.azure.data.cosmos.directconnectivity.HttpUtils; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; import java.util.Map; @@ -49,18 +49,18 @@ public NotFoundException(Error error, long lsn, String partitionKeyRangeId, Map< } public NotFoundException(String message) { - this(message, (Exception) null, (HttpResponseHeaders) null, null); + this(message, null, (HttpHeaders) null, null); } public NotFoundException(String message, Map headers, String requestUri) { this(message, null, headers, requestUri); } - public NotFoundException(String message, HttpResponseHeaders headers, String requestUri) { + public NotFoundException(String message, HttpHeaders headers, String requestUri) { this(message, null, headers, requestUri); } - public NotFoundException(String message, HttpResponseHeaders headers, URI requestUri) { + public NotFoundException(String message, HttpHeaders headers, URI requestUri) { this(message, headers, requestUri != null ? requestUri.toString() : null); } @@ -70,7 +70,7 @@ public NotFoundException(Exception innerException) { public NotFoundException(String message, Exception innerException, - HttpResponseHeaders headers, + HttpHeaders headers, String requestUri) { this(message, innerException, HttpUtils.asMap(headers), requestUri); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java index c5bb14f97fa05..1a5af062b3042 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java @@ -22,9 +22,10 @@ */ package com.azure.data.cosmos.internal; -import rx.Observable; -import rx.Single; -import rx.functions.Func0; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.concurrent.Callable; /** * While this class is public, but it is not part of our published public APIs. @@ -33,26 +34,34 @@ **/ public class ObservableHelper { - static public Single inlineIfPossible(Func0> function, IRetryPolicy retryPolicy) { + static public Mono inlineIfPossible(Callable> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { // shortcut - return function.call(); + try { + return function.call(); + } catch (Exception e) { + return Mono.error(e); + } } else { return BackoffRetryUtility.executeRetry(function, retryPolicy); } } - static public Observable inlineIfPossibleAsObs(Func0> function, IRetryPolicy retryPolicy) { + static public Flux inlineIfPossibleAsObs(Callable> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { // shortcut - return Observable.defer(() -> { - return function.call(); + return Flux.defer(() -> { + try { + return function.call(); + } catch (Exception e) { + return Flux.error(e); + } }); } else { - return BackoffRetryUtility.executeRetry(() -> function.call().toSingle(), retryPolicy).toObservable(); + return BackoffRetryUtility.executeRetry(() -> function.call().single(), retryPolicy).flux(); } } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java index 8b07a5c1fea45..43ecf8b1619a6 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.WFConstants; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -59,7 +59,7 @@ public PartitionIsMigratingException(String msg, String resourceAddress) { setSubStatus(); } - public PartitionIsMigratingException(String message, HttpResponseHeaders headers, String requestUri) { + public PartitionIsMigratingException(String message, HttpHeaders headers, String requestUri) { this(message, null, headers, requestUri); } @@ -69,7 +69,7 @@ public PartitionIsMigratingException(Exception innerException) { public PartitionIsMigratingException(String message, Exception innerException, - HttpResponseHeaders headers, + HttpHeaders headers, String requestUri) { super(String.format("%s: %s", RMResources.Gone, message), innerException, diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java index 88830089cb014..c70b65d4ecf56 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; -import rx.Single; +import reactor.core.publisher.Mono; import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; @@ -72,7 +72,7 @@ public PartitionKeyMismatchRetryPolicy( /// Exception that occured when the operation was tried /// /// True indicates caller should retry, False otherwise - public Single shouldRetry(Exception exception) { + public Mono shouldRetry(Exception exception) { CosmosClientException clientException = Utils.as(exception, CosmosClientException.class) ; if (clientException != null && @@ -91,7 +91,7 @@ public Single shouldRetry(Exception exception) { this.retriesAttempted.incrementAndGet(); - return Single.just(ShouldRetryResult.retryAfter(Duration.ZERO)); + return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); } return this.nextRetryPolicy.shouldRetry(exception); @@ -99,7 +99,7 @@ public Single shouldRetry(Exception exception) { /* (non-Javadoc) - * @see com.azure.data.cosmos.internal.internal.query.IDocumentClientRetryPolicy#onBeforeSendRequest(rx.Observable) + * @see com.azure.data.cosmos.internal.internal.query.IDocumentClientRetryPolicy#onBeforeSendRequest(RxDocumentServiceRequest) */ @Override public void onBeforeSendRequest(RxDocumentServiceRequest request) { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java index 74bf67abcb011..622fbf3797d61 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java @@ -28,8 +28,7 @@ import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; -import rx.Observable; -import rx.Single; +import reactor.core.publisher.Mono; import java.time.Duration; @@ -66,14 +65,14 @@ public PartitionKeyRangeGoneRetryPolicy( /// Exception that occured when the operation was tried /// /// True indicates caller should retry, False otherwise - public Single shouldRetry(Exception exception) { + public Mono shouldRetry(Exception exception) { CosmosClientException clientException = Utils.as(exception, CosmosClientException.class); if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.GONE) && Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)) { if (this.retried){ - return Single.just(ShouldRetryResult.error(clientException)); + return Mono.just(ShouldRetryResult.error(clientException)); } RxDocumentServiceRequest request = RxDocumentServiceRequest.create( @@ -86,31 +85,30 @@ public Single shouldRetry(Exception exception) { if (this.feedOptions != null) { request.properties = this.feedOptions.properties(); } - Single collectionObs = this.collectionCache.resolveCollectionAsync(request); + Mono collectionObs = this.collectionCache.resolveCollectionAsync(request); - Single retryTimeObservable = collectionObs.flatMap(collection -> { + return collectionObs.flatMap(collection -> { - Single routingMapObs = this.partitionKeyRangeCache.tryLookupAsync(collection.resourceId(), null, request.properties); + Mono routingMapObs = this.partitionKeyRangeCache.tryLookupAsync(collection.resourceId(), null, request.properties); - Single refreshedRoutingMapObs = routingMapObs.flatMap(routingMap -> { - if (routingMap != null) { - // Force refresh. - return this.partitionKeyRangeCache.tryLookupAsync( - collection.resourceId(), - routingMap, - request.properties); - } else { - return Observable.just((CollectionRoutingMap) null).toSingle(); - } - }); + Mono refreshedRoutingMapObs = routingMapObs.flatMap(routingMap -> { + // Force refresh. + return this.partitionKeyRangeCache.tryLookupAsync( + collection.resourceId(), + routingMap, + request.properties); + }).switchIfEmpty(Mono.defer(Mono::empty)); + // TODO: Check if this behavior can be replaced by doOnSubscribe return refreshedRoutingMapObs.flatMap(rm -> { this.retried = true; - return Single.just(ShouldRetryResult.retryAfter(Duration.ZERO)); - }); + return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); + }).switchIfEmpty(Mono.defer(() -> { + this.retried = true; + return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); + })); }); - return retryTimeObservable; } else { return this.nextRetryPolicy.shouldRetry(exception); diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java index 71e29bac82961..759baddf288ab 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.Error; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.WFConstants; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -59,7 +59,7 @@ public PartitionKeyRangeIsSplittingException(String msg, String resourceAddress) setSubStatus(); } - public PartitionKeyRangeIsSplittingException(String message, HttpResponseHeaders headers, String requestUri) { + public PartitionKeyRangeIsSplittingException(String message, HttpHeaders headers, String requestUri) { this(message, null, headers, requestUri); } @@ -69,7 +69,7 @@ public PartitionKeyRangeIsSplittingException(Exception innerException) { public PartitionKeyRangeIsSplittingException(String message, Exception innerException, - HttpResponseHeaders headers, + HttpHeaders headers, String requestUri) { super(String.format("%s: %s", RMResources.Gone, message), innerException, diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java index d9a5a8de7f1e4..558a6cf332e84 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java @@ -29,7 +29,7 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; +import reactor.core.publisher.Mono; import java.time.Duration; @@ -57,7 +57,7 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { } @Override - public Single shouldRetry(Exception e) { + public Mono shouldRetry(Exception e) { return this.retryPolicy.shouldRetry(e).flatMap(shouldRetryResult -> { if (!shouldRetryResult.shouldRetry && !this.hasTriggered) { CosmosClientException clientException = Utils.as(e, CosmosClientException.class); @@ -65,7 +65,7 @@ public Single shouldRetry(Exception e) { if (this.request == null) { // someone didn't call OnBeforeSendRequest - nothing we can do logger.error("onBeforeSendRequest is not invoked, encountered failure due to request being null", e); - return Single.just(ShouldRetryResult.error(e)); + return Mono.just(ShouldRetryResult.error(e)); } if (clientException != null && this.request.getIsNameBased() && @@ -83,28 +83,29 @@ public Single shouldRetry(Exception e) { request.forceNameCacheRefresh = true; request.requestContext.resolvedCollectionRid = null; - Single collectionObs = this.collectionCache.resolveCollectionAsync(request); + Mono collectionObs = this.collectionCache.resolveCollectionAsync(request); return collectionObs.flatMap(collectionInfo -> { - if (collectionInfo == null) { - logger.warn("Can't recover from session unavailable exception because resolving collection name {} returned null", request.getResourceAddress()); - } else if (!StringUtils.isEmpty(oldCollectionRid) && !StringUtils.isEmpty(collectionInfo.resourceId())) { - return Single.just(ShouldRetryResult.retryAfter(Duration.ZERO)); + if (!StringUtils.isEmpty(oldCollectionRid) && !StringUtils.isEmpty(collectionInfo.resourceId())) { + return Mono.just(ShouldRetryResult.retryAfter(Duration.ZERO)); } - return Single.just(shouldRetryResult); - }).onErrorResumeNext(throwable -> { + return Mono.just(shouldRetryResult); + }).switchIfEmpty(Mono.defer(() -> { + logger.warn("Can't recover from session unavailable exception because resolving collection name {} returned null", request.getResourceAddress()); + return Mono.just(shouldRetryResult); + })).onErrorResume(throwable -> { // When resolveCollectionAsync throws an exception ignore it because it's an attempt to recover an existing // error. When the recovery fails we return ShouldRetryResult.noRetry and propagate the original exception to the client logger.warn("Can't recover from session unavailable exception because resolving collection name {} failed with {}", request.getResourceAddress(), throwable.getMessage()); if (throwable instanceof Exception) { - return Single.just(ShouldRetryResult.error((Exception) throwable)); + return Mono.just(ShouldRetryResult.error((Exception) throwable)); } - return Single.error(throwable); + return Mono.error(throwable); }); } } - return Single.just(shouldRetryResult); + return Mono.just(shouldRetryResult); }); } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java index 4095df95601f8..47ae481869fb2 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.CosmosClientException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; +import reactor.core.publisher.Mono; import java.time.Duration; @@ -67,7 +67,7 @@ public ResourceThrottleRetryPolicy(int maxAttemptCount, int maxWaitTimeInSeconds } @Override - public Single shouldRetry(Exception exception) { + public Mono shouldRetry(Exception exception) { Duration retryDelay = Duration.ZERO; if (this.currentAttemptCount < this.maxAttemptCount && @@ -79,13 +79,13 @@ public Single shouldRetry(Exception exception) { this.currentAttemptCount, this.cumulativeRetryDelay, exception); - return Single.just(ShouldRetryResult.retryAfter(retryDelay)); + return Mono.just(ShouldRetryResult.retryAfter(retryDelay)); } else { logger.debug( "Operation will NOT be retried. Current attempt {}", this.currentAttemptCount, exception); - return Single.just(ShouldRetryResult.noRetry()); + return Mono.just(ShouldRetryResult.noRetry()); } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java index c356d4eb645bd..4e50ed2a6f5dc 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java @@ -25,12 +25,11 @@ import org.apache.commons.lang3.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; -import rx.functions.Func1; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.time.Duration; -import java.util.concurrent.TimeUnit; +import java.util.function.Function; /** * While this class is public, but it is not part of our published public APIs. @@ -39,31 +38,25 @@ public class RetryUtils { private final static Logger logger = LoggerFactory.getLogger(BackoffRetryUtility.class); - public static Func1, Observable> toRetryWhenFunc(IRetryPolicy policy) { - return new Func1, Observable>() { - - @Override - public Observable call(Observable throwableObs) { - return throwableObs.flatMap( t -> { - Exception e = Utils.as(t, Exception.class); - if (e == null) { - return Observable.error(t); - } - - return policy.shouldRetry(e).toObservable().flatMap(s -> { - - if (s.backOffTime != null) { - return Observable.timer(s.backOffTime.toMillis(), TimeUnit.MILLISECONDS); - } else if (s.exception != null) { - return Observable.error(s.exception); - } else { - // NoRetry return original failure - return Observable.error(t); - } - }); - }); + static Function, Flux> toRetryWhenFunc(IRetryPolicy policy) { + return throwableFlux -> throwableFlux.flatMap(t -> { + Exception e = Utils.as(t, Exception.class); + if (e == null) { + return Flux.error(t); } - }; + Flux shouldRetryResultFlux = policy.shouldRetry(e).flux(); + return shouldRetryResultFlux.flatMap(s -> { + + if (s.backOffTime != null) { + return Mono.delay(Duration.ofMillis(s.backOffTime.toMillis())).flux(); + } else if (s.exception != null) { + return Flux.error(s.exception); + } else { + // NoRetry return original failure + return Flux.error(t); + } + }); + }); } /** @@ -71,87 +64,67 @@ public Observable call(Observable throwableObs) { * callbackMethod and inBackoffAlternateCallbackMethod until success or as stated in * retry policy. * @param callbackMethod The callbackMethod - * @param policy Retry policy + * @param retryPolicy Retry policy * @param inBackoffAlternateCallbackMethod The inBackoffAlternateCallbackMethod * @param minBackoffForInBackoffCallback Minimum backoff for InBackoffCallbackMethod * @return */ - static Func1> toRetryWithAlternateFunc( - Func1, Single> callbackMethod, IRetryPolicy policy, - Func1, Single> inBackoffAlternateCallbackMethod, - Duration minBackoffForInBackoffCallback) { - return new Func1>() { - - @Override - public Single call(Throwable t) { - Exception e = Utils.as(t, Exception.class); - if (e == null) { - return Single.error(t); - } - return policy.shouldRetry(e).flatMap(shouldRetryResult -> { - if (!shouldRetryResult.shouldRetry) { - if(shouldRetryResult.exception == null) { - return Single.error(e); - } else { - return Single.error(shouldRetryResult.exception); - } - } + public static Function> toRetryWithAlternateFunc(Function, Mono> callbackMethod, IRetryPolicy retryPolicy, Function, Mono> inBackoffAlternateCallbackMethod, Duration minBackoffForInBackoffCallback) { + return throwable -> { + Exception e = Utils.as(throwable, Exception.class); + if (e == null) { + return Mono.error(throwable); + } - if (inBackoffAlternateCallbackMethod != null - && shouldRetryResult.backOffTime.compareTo(minBackoffForInBackoffCallback) > 0) { - StopWatch stopwatch = new StopWatch(); - startStopWatch(stopwatch); - return inBackoffAlternateCallbackMethod.call(shouldRetryResult.policyArg) - .onErrorResumeNext(recurrsiveWithAlternateFunc(callbackMethod, policy, - inBackoffAlternateCallbackMethod, shouldRetryResult, stopwatch, - minBackoffForInBackoffCallback)); + Flux shouldRetryResultFlux = retryPolicy.shouldRetry(e).flux(); + return shouldRetryResultFlux.flatMap(shouldRetryResult -> { + if (!shouldRetryResult.shouldRetry) { + if(shouldRetryResult.exception == null) { + return Mono.error(e); } else { - return recurrsiveFunc(callbackMethod, policy, inBackoffAlternateCallbackMethod, - shouldRetryResult, minBackoffForInBackoffCallback) - .delaySubscription(Observable.timer(shouldRetryResult.backOffTime.toMillis(), - TimeUnit.MILLISECONDS)); + return Mono.error(shouldRetryResult.exception); } - }); - } - }; + } + if (inBackoffAlternateCallbackMethod != null + && shouldRetryResult.backOffTime.compareTo(minBackoffForInBackoffCallback) > 0) { + StopWatch stopwatch = new StopWatch(); + startStopWatch(stopwatch); + return inBackoffAlternateCallbackMethod.apply(shouldRetryResult.policyArg) + .onErrorResume(recurrsiveWithAlternateFunc(callbackMethod, retryPolicy, + inBackoffAlternateCallbackMethod, shouldRetryResult, stopwatch, + minBackoffForInBackoffCallback)); + } else { + return recurrsiveFunc(callbackMethod, retryPolicy, inBackoffAlternateCallbackMethod, + shouldRetryResult, minBackoffForInBackoffCallback) + .delaySubscription(Duration.ofMillis(shouldRetryResult.backOffTime.toMillis())); + } + }).single(); + }; } - private static Single recurrsiveFunc( - Func1, Single> callbackMethod, IRetryPolicy policy, - Func1, Single> inBackoffAlternateCallbackMethod, - IRetryPolicy.ShouldRetryResult shouldRetryResult, Duration minBackoffForInBackoffCallback) { - return callbackMethod.call(shouldRetryResult.policyArg).onErrorResumeNext(toRetryWithAlternateFunc( - callbackMethod, policy, inBackoffAlternateCallbackMethod, minBackoffForInBackoffCallback)); - + private static Mono recurrsiveFunc(Function, Mono> callbackMethod, IRetryPolicy retryPolicy, Function, Mono> inBackoffAlternateCallbackMethod, IRetryPolicy.ShouldRetryResult shouldRetryResult, Duration minBackoffForInBackoffCallback) { + return callbackMethod.apply(shouldRetryResult.policyArg).onErrorResume(toRetryWithAlternateFunc( + callbackMethod, retryPolicy, inBackoffAlternateCallbackMethod, minBackoffForInBackoffCallback)); } - private static Func1> recurrsiveWithAlternateFunc( - Func1, Single> callbackMethod, IRetryPolicy policy, - Func1, Single> inBackoffAlternateCallbackMethod, - IRetryPolicy.ShouldRetryResult shouldRetryResult, StopWatch stopwatch, Duration minBackoffForInBackoffCallback) { - return new Func1>() { - - @Override - public Single call(Throwable t) { - - Exception e = Utils.as(t, Exception.class); - if (e == null) { - return Single.error(t); - } - - stopStopWatch(stopwatch); - logger.info("Failed inBackoffAlternateCallback with {}, proceeding with retry. Time taken: {}ms", - e.toString(), stopwatch.getTime()); - Duration backoffTime = shouldRetryResult.backOffTime.toMillis() > stopwatch.getTime() - ? Duration.ofMillis(shouldRetryResult.backOffTime.toMillis() - stopwatch.getTime()) - : Duration.ZERO; - return recurrsiveFunc(callbackMethod, policy, inBackoffAlternateCallbackMethod, shouldRetryResult, - minBackoffForInBackoffCallback) - .delaySubscription(Observable.timer(backoffTime.toMillis(), TimeUnit.MILLISECONDS)); + private static Function> recurrsiveWithAlternateFunc(Function, Mono> callbackMethod, IRetryPolicy retryPolicy, Function, Mono> inBackoffAlternateCallbackMethod, IRetryPolicy.ShouldRetryResult shouldRetryResult, StopWatch stopwatch, Duration minBackoffForInBackoffCallback) { + return throwable -> { + Exception e = Utils.as(throwable, Exception.class); + if (e == null) { + return Mono.error(throwable); } + stopStopWatch(stopwatch); + logger.info("Failed inBackoffAlternateCallback with {}, proceeding with retry. Time taken: {}ms", + e.toString(), stopwatch.getTime()); + Duration backoffTime = shouldRetryResult.backOffTime.toMillis() > stopwatch.getTime() + ? Duration.ofMillis(shouldRetryResult.backOffTime.toMillis() - stopwatch.getTime()) + : Duration.ZERO; + return recurrsiveFunc(callbackMethod, retryPolicy, inBackoffAlternateCallbackMethod, shouldRetryResult, + minBackoffForInBackoffCallback) + .delaySubscription(Flux.just(0L).delayElements(Duration.ofMillis(backoffTime.toMillis()))); }; } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java index 2719039b3e1c6..d283b21ae8cd0 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java @@ -1,17 +1,17 @@ /* * The MIT License (MIT) * Copyright (c) 2018 Microsoft Corporation - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -30,24 +30,21 @@ import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; -import rx.functions.Func0; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -57,11 +54,12 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; +import java.util.concurrent.Callable; /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. - * + * * Used internally to provide functionality to communicate and process response from GATEWAY in the Azure Cosmos DB database service. */ class RxGatewayStoreModel implements RxStoreModel { @@ -69,7 +67,7 @@ class RxGatewayStoreModel implements RxStoreModel { private final static int INITIAL_RESPONSE_BUFFER_SIZE = 1024; private final Logger logger = LoggerFactory.getLogger(RxGatewayStoreModel.class); private final Map defaultHeaders; - private final CompositeHttpClient httpClient; + private final HttpClient httpClient; private final QueryCompatibilityMode queryCompatibilityMode; private final GlobalEndpointManager globalEndpointManager; private ConsistencyLevel defaultConsistencyLevel; @@ -81,7 +79,7 @@ public RxGatewayStoreModel( QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, - CompositeHttpClient httpClient) { + HttpClient httpClient) { this.defaultHeaders = new HashMap<>(); this.defaultHeaders.put(HttpConstants.HttpHeaders.CACHE_CONTROL, "no-cache"); @@ -96,7 +94,7 @@ public RxGatewayStoreModel( if (defaultConsistencyLevel != null) { this.defaultHeaders.put(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, - defaultConsistencyLevel.toString()); + defaultConsistencyLevel.toString()); } this.defaultConsistencyLevel = defaultConsistencyLevel; @@ -107,111 +105,112 @@ public RxGatewayStoreModel( this.sessionContainer = sessionContainer; } - private Observable doCreate(RxDocumentServiceRequest request) { + private Flux doCreate(RxDocumentServiceRequest request) { return this.performRequest(request, HttpMethod.POST); } - private Observable upsert(RxDocumentServiceRequest request) { + private Flux upsert(RxDocumentServiceRequest request) { return this.performRequest(request, HttpMethod.POST); } - private Observable read(RxDocumentServiceRequest request) { + private Flux read(RxDocumentServiceRequest request) { return this.performRequest(request, HttpMethod.GET); } - private Observable replace(RxDocumentServiceRequest request) { + private Flux replace(RxDocumentServiceRequest request) { return this.performRequest(request, HttpMethod.PUT); } - private Observable delete(RxDocumentServiceRequest request) { + private Flux delete(RxDocumentServiceRequest request) { return this.performRequest(request, HttpMethod.DELETE); } - private Observable execute(RxDocumentServiceRequest request) { + private Flux execute(RxDocumentServiceRequest request) { return this.performRequest(request, HttpMethod.POST); } - private Observable readFeed(RxDocumentServiceRequest request) { + private Flux readFeed(RxDocumentServiceRequest request) { return this.performRequest(request, HttpMethod.GET); } - private Observable query(RxDocumentServiceRequest request) { + private Flux query(RxDocumentServiceRequest request) { request.getHeaders().put(HttpConstants.HttpHeaders.IS_QUERY, "true"); switch (this.queryCompatibilityMode) { - case SqlQuery: - request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, - RuntimeConstants.MediaTypes.SQL); - break; - case Default: - case Query: - default: - request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, - RuntimeConstants.MediaTypes.QUERY_JSON); - break; - } + case SqlQuery: + request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, + RuntimeConstants.MediaTypes.SQL); + break; + case Default: + case Query: + default: + request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE, + RuntimeConstants.MediaTypes.QUERY_JSON); + break; + } return this.performRequest(request, HttpMethod.POST); } /** - * Given the request it creates an observable which upon subscription issues HTTP call and emits one RxDocumentServiceResponse. + * Given the request it creates an flux which upon subscription issues HTTP call and emits one RxDocumentServiceResponse. * * @param request * @param method - * @return Observable + * @return Flux */ - public Observable performRequest(RxDocumentServiceRequest request, HttpMethod method) { + public Flux performRequest(RxDocumentServiceRequest request, HttpMethod method) { try { URI uri = getUri(request); - HttpClientRequest httpRequest = HttpClientRequest.create(method, uri.toString()); - - this.fillHttpRequestBaseWithHeaders(request.getHeaders(), httpRequest); - if (request.getContentObservable() != null) { + HttpHeaders httpHeaders = this.getHttpRequestHeaders(request.getHeaders()); - // TODO validate this - // convert byte[] to ByteBuf - // why not use Observable directly? - Observable byteBufObservable = request.getContentObservable() - .map(bytes -> Unpooled.wrappedBuffer(bytes)); + Flux byteBufObservable = Flux.empty(); - httpRequest.withContentSource(byteBufObservable); + if (request.getContentObservable() != null) { + byteBufObservable = request.getContentObservable().map(Unpooled::wrappedBuffer); } else if (request.getContent() != null){ - httpRequest.withContent(request.getContent()); + byteBufObservable = Flux.just(Unpooled.wrappedBuffer(request.getContent())); } - RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(uri.getHost(), uri.getPort()); - Observable> clientResponseObservable = this.httpClient.submit(serverInfo, httpRequest); + HttpRequest httpRequest = new HttpRequest(method, + uri, + uri.getPort(), + httpHeaders, + byteBufObservable); - return toDocumentServiceResponse(clientResponseObservable, request); + Mono httpResponseMono = this.httpClient.send(httpRequest); + + return toDocumentServiceResponse(httpResponseMono, request); } catch (Exception e) { - return Observable.error(e); + return Flux.error(e); } } - private void fillHttpRequestBaseWithHeaders(Map headers, HttpClientRequest req) { + private HttpHeaders getHttpRequestHeaders(Map headers) { + HttpHeaders httpHeaders = new HttpHeaders(this.defaultHeaders.size()); // Add default headers. for (Entry entry : this.defaultHeaders.entrySet()) { if (!headers.containsKey(entry.getKey())) { // populate default header only if there is no overwrite by the request header - req.withHeader(entry.getKey(), entry.getValue()); + httpHeaders.set(entry.getKey(), entry.getValue()); } } - + // Add override headers. if (headers != null) { for (Entry entry : headers.entrySet()) { if (entry.getValue() == null) { // netty doesn't allow setting null value in header - req.withHeader(entry.getKey(), ""); + httpHeaders.set(entry.getKey(), ""); } else { - req.withHeader(entry.getKey(), entry.getValue()); + httpHeaders.set(entry.getKey(), entry.getValue()); } } } + return httpHeaders; } private URI getUri(RxDocumentServiceRequest request) throws URISyntaxException { @@ -230,163 +229,139 @@ private URI getUri(RxDocumentServiceRequest request) throws URISyntaxException { path = StringUtils.EMPTY; } - URI uri = new URI("https", + return new URI("https", null, rootUri.getHost(), rootUri.getPort(), ensureSlashPrefixed(path), null, // Query string not used. null); - - return uri; } private String ensureSlashPrefixed(String path) { if (path == null) { return path; } - + if (path.startsWith("/")) { return path; } - - return "/" + path; - } - private Observable toInputStream(Observable contentObservable) { - // TODO: this is a naive approach for converting to InputStream - // this first reads and buffers everything in memory and then translate that to an input stream - // this means - // 1) there is some performance implication - // 2) this may result in OutOfMemoryException if used for reading huge content, e.g., a media - // - // see this: https://github.com/ReactiveX/RxNetty/issues/391 for some similar discussion on how to - // convert to an input stream - return contentObservable - .reduce( - new ByteArrayOutputStream(), - (out, bb) -> { - try { - bb.readBytes(out, bb.readableBytes()); - return out; - } - catch (IOException e) { - throw new RuntimeException(e); - } - }) - .map(out -> { - return new ByteArrayInputStream(out.toByteArray()); - }); + return "/" + path; } - private Observable toString(Observable contentObservable) { + private Mono toString(Flux contentObservable) { return contentObservable - .reduce( - new ByteArrayOutputStream(INITIAL_RESPONSE_BUFFER_SIZE), - (out, bb) -> { - try { - bb.readBytes(out, bb.readableBytes()); - return out; - } - catch (IOException e) { - throw new RuntimeException(e); - } - }) - .map(out -> { - return new String(out.toByteArray(), StandardCharsets.UTF_8); - }); + .reduce( + new ByteArrayOutputStream(INITIAL_RESPONSE_BUFFER_SIZE), + (out, bb) -> { + try { + bb.readBytes(out, bb.readableBytes()); + return out; + } + catch (IOException e) { + throw new RuntimeException(e); + } + }) + .map(out -> new String(out.toByteArray(), StandardCharsets.UTF_8)); } /** - * Transforms the rxNetty's client response Observable to RxDocumentServiceResponse Observable. - * - * + * Transforms the reactor netty's client response Observable to RxDocumentServiceResponse Observable. + * + * * Once the customer code subscribes to the observable returned by the CRUD APIs, - * the subscription goes up till it reaches the source rxNetty's observable, and at that point the HTTP invocation will be made. - * - * @param clientResponseObservable + * the subscription goes up till it reaches the source reactor netty's observable, and at that point the HTTP invocation will be made. + * + * @param httpResponseMono * @param request - * @return {@link Observable} + * @return {@link Flux} */ - private Observable toDocumentServiceResponse(Observable> clientResponseObservable, - RxDocumentServiceRequest request) { + private Flux toDocumentServiceResponse(Mono httpResponseMono, + RxDocumentServiceRequest request) { if (request.getIsMedia()) { - return clientResponseObservable.flatMap(clientResponse -> { + return httpResponseMono.flatMap(httpResponse -> { // header key/value pairs - HttpResponseHeaders httpResponseHeaders = clientResponse.getHeaders(); - HttpResponseStatus httpResponseStatus = clientResponse.getStatus(); + HttpHeaders httpResponseHeaders = httpResponse.headers(); + int httpResponseStatus = httpResponse.statusCode(); - Observable inputStreamObservable; + Flux inputStreamObservable; if (request.getOperationType() == OperationType.Delete) { // for delete we don't expect any body - inputStreamObservable = Observable.just(null); + inputStreamObservable = Flux.just(IOUtils.toInputStream("", StandardCharsets.UTF_8)); } else { - // transforms the observable to Observable - inputStreamObservable = toInputStream(clientResponse.getContent()); + // transforms the ByteBufFlux to Flux + inputStreamObservable = httpResponse + .body() + .flatMap(byteBuf -> + Flux.just(IOUtils.toInputStream(byteBuf.toString(StandardCharsets.UTF_8), StandardCharsets.UTF_8))); } - Observable storeResponseObservable = inputStreamObservable + return inputStreamObservable .flatMap(contentInputStream -> { try { // If there is any error in the header response this throws exception // TODO: potential performance improvement: return Observable.error(exception) on failure instead of throwing Exception - validateOrThrow(request, httpResponseStatus, httpResponseHeaders, null, contentInputStream); + validateOrThrow(request, + HttpResponseStatus.valueOf(httpResponseStatus), + httpResponseHeaders, + null, + contentInputStream); // transforms to Observable - StoreResponse rsp = new StoreResponse(httpResponseStatus.code(), HttpUtils.unescape(httpResponseHeaders.entries()), contentInputStream); - return Observable.just(rsp); + StoreResponse rsp = new StoreResponse(httpResponseStatus, HttpUtils + .unescape(httpResponseHeaders.toMap().entrySet()), contentInputStream); + return Flux.just(rsp); } catch (Exception e) { - return Observable.error(e); + return Flux.error(e); } - }); - - return storeResponseObservable; + }).single(); - }).map(storeResponse -> new RxDocumentServiceResponse(storeResponse)); + }).map(RxDocumentServiceResponse::new).flux(); } else { - return clientResponseObservable.flatMap(clientResponse -> { + return httpResponseMono.flatMap(httpResponse -> { // header key/value pairs - HttpResponseHeaders httpResponseHeaders = clientResponse.getHeaders(); - HttpResponseStatus httpResponseStatus = clientResponse.getStatus(); + HttpHeaders httpResponseHeaders = httpResponse.headers(); + int httpResponseStatus = httpResponse.statusCode(); - Observable contentObservable; + Flux contentObservable; if (request.getOperationType() == OperationType.Delete) { // for delete we don't expect any body - contentObservable = Observable.just(null); + contentObservable = Flux.just(StringUtils.EMPTY); } else { - // transforms the observable to Observable - contentObservable = toString(clientResponse.getContent()); + // transforms the ByteBufFlux to Flux + contentObservable = toString(httpResponse.body()).flux(); } - Observable storeResponseObservable = contentObservable + return contentObservable .flatMap(content -> { try { // If there is any error in the header response this throws exception // TODO: potential performance improvement: return Observable.error(exception) on failure instead of throwing Exception - validateOrThrow(request, httpResponseStatus, httpResponseHeaders, content, null); + validateOrThrow(request, HttpResponseStatus.valueOf(httpResponseStatus), httpResponseHeaders, content, null); // transforms to Observable - StoreResponse rsp = new StoreResponse(httpResponseStatus.code(), HttpUtils.unescape(httpResponseHeaders.entries()), content); - return Observable.just(rsp); + StoreResponse rsp = new StoreResponse(httpResponseStatus, + HttpUtils.unescape(httpResponseHeaders.toMap().entrySet()), + content); + return Flux.just(rsp); } catch (Exception e) { - return Observable.error(e); + return Flux.error(e); } - }); + }).single(); - return storeResponseObservable; - - }).map(storeResponse -> new RxDocumentServiceResponse(storeResponse)) - .onErrorResumeNext(throwable -> { + }).map(RxDocumentServiceResponse::new) + .onErrorResume(throwable -> { if (!(throwable instanceof Exception)) { // fatal error logger.error("Unexpected failure {}", throwable.getMessage(), throwable); - return Observable.error(throwable); + return Mono.error(throwable); } Exception exception = (Exception) throwable; @@ -395,16 +370,16 @@ private Observable toDocumentServiceResponse(Observab logger.error("Network failure", exception); CosmosClientException dce = new CosmosClientException(0, exception); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); - return Observable.error(dce); + return Mono.error(dce); } - return Observable.error(exception); - }); + return Mono.error(exception); + }).flux(); } } - private void validateOrThrow(RxDocumentServiceRequest request, HttpResponseStatus status, HttpResponseHeaders headers, String body, - InputStream inputStream) throws CosmosClientException { + private void validateOrThrow(RxDocumentServiceRequest request, HttpResponseStatus status, HttpHeaders headers, String body, + InputStream inputStream) throws CosmosClientException { int statusCode = status.code(); @@ -425,60 +400,60 @@ private void validateOrThrow(RxDocumentServiceRequest request, HttpResponseStatu String statusCodeString = status.reasonPhrase() != null ? status.reasonPhrase().replace(" ", "") : ""; - Error error = null; - error = (body != null) ? new Error(body) : new Error(); + Error error; + error = (StringUtils.isNotEmpty(body)) ? new Error(body) : new Error(); error = new Error(statusCodeString, - String.format("%s, StatusCode: %s", error.getMessage(), statusCodeString), - error.getPartitionedQueryExecutionInfo()); + String.format("%s, StatusCode: %s", error.getMessage(), statusCodeString), + error.getPartitionedQueryExecutionInfo()); - CosmosClientException dce = new CosmosClientException(statusCode, error, HttpUtils.asMap(headers)); + CosmosClientException dce = new CosmosClientException(statusCode, error, headers.toMap()); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); throw dce; } } - private Observable invokeAsyncInternal(RxDocumentServiceRequest request) { + private Flux invokeAsyncInternal(RxDocumentServiceRequest request) { switch (request.getOperationType()) { - case Create: - return this.doCreate(request); - case Upsert: - return this.upsert(request); - case Delete: - return this.delete(request); - case ExecuteJavaScript: - return this.execute(request); - case Read: - return this.read(request); - case ReadFeed: - return this.readFeed(request); - case Replace: - return this.replace(request); - case SqlQuery: - case Query: - return this.query(request); - default: - throw new IllegalStateException("Unknown operation type " + request.getOperationType()); + case Create: + return this.doCreate(request); + case Upsert: + return this.upsert(request); + case Delete: + return this.delete(request); + case ExecuteJavaScript: + return this.execute(request); + case Read: + return this.read(request); + case ReadFeed: + return this.readFeed(request); + case Replace: + return this.replace(request); + case SqlQuery: + case Query: + return this.query(request); + default: + throw new IllegalStateException("Unknown operation type " + request.getOperationType()); } } - private Observable invokeAsync(RxDocumentServiceRequest request) { - Func0> funcDelegate = () -> invokeAsyncInternal(request).toSingle(); - return BackoffRetryUtility.executeRetry(funcDelegate, new WebExceptionRetryPolicy()).toObservable(); + private Flux invokeAsync(RxDocumentServiceRequest request) { + Callable> funcDelegate = () -> invokeAsyncInternal(request).single(); + return BackoffRetryUtility.executeRetry(funcDelegate, new WebExceptionRetryPolicy()).flux(); } @Override - public Observable processMessage(RxDocumentServiceRequest request) { + public Flux processMessage(RxDocumentServiceRequest request) { this.applySessionToken(request); - Observable responseObs = invokeAsync(request); + Flux responseObs = invokeAsync(request); - return responseObs.onErrorResumeNext( + return responseObs.onErrorResume( e -> { CosmosClientException dce = Utils.as(e, CosmosClientException.class); if (dce == null) { logger.error("unexpected failure {}", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } if ((!ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) && @@ -491,13 +466,13 @@ public Observable processMessage(RxDocumentServiceReq this.captureSessionToken(request, dce.responseHeaders()); } - return Observable.error(dce); + return Flux.error(dce); } ).map(response -> - { - this.captureSessionToken(request, response.getResponseHeaders()); - return response; - } + { + this.captureSessionToken(request, response.getResponseHeaders()); + return response; + } ); } @@ -543,5 +518,5 @@ private void applySessionToken(RxDocumentServiceRequest request) { if (!Strings.isNullOrEmpty(sessionToken)) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionToken); } - } -} + } +} \ No newline at end of file diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java index 9cacda843d096..38fae2f6c0ea7 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos.internal; -import rx.Observable; +import reactor.core.publisher.Flux; /** * While this class is public, but it is not part of our published public APIs. @@ -39,5 +39,5 @@ public interface RxStoreModel { * @param request * @return */ - Observable processMessage(RxDocumentServiceRequest request); + Flux processMessage(RxDocumentServiceRequest request); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java index b9dd3e52cd1b9..8b145e42d50d7 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java @@ -27,7 +27,7 @@ import org.apache.commons.lang3.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; +import reactor.core.publisher.Mono; import java.time.Duration; import java.util.concurrent.TimeUnit; @@ -51,13 +51,13 @@ public WebExceptionRetryPolicy() { @Override - public Single shouldRetry(Exception exception) { + public Mono shouldRetry(Exception exception) { Duration backoffTime = Duration.ofSeconds(0); if (!WebExceptionUtility.isWebExceptionRetriable(exception)) { // Have caller propagate original exception. this.durationTimer.stop(); - return Single.just(ShouldRetryResult.noRetry()); + return Mono.just(ShouldRetryResult.noRetry()); } // Don't penalise first retry with delay. @@ -65,7 +65,7 @@ public Single shouldRetry(Exception exception) { int remainingSeconds = WebExceptionRetryPolicy.waitTimeInSeconds - Math.toIntExact(this.durationTimer.getTime(TimeUnit.SECONDS)); if (remainingSeconds <= 0) { this.durationTimer.stop(); - return Single.just(ShouldRetryResult.noRetry()); + return Mono.just(ShouldRetryResult.noRetry()); } backoffTime = Duration.ofSeconds(Math.min(this.currentBackoffSeconds, remainingSeconds)); @@ -74,6 +74,6 @@ public Single shouldRetry(Exception exception) { logger.warn("Received retriable web exception, will retry", exception); - return Single.just(ShouldRetryResult.retryAfter(backoffTime)); + return Mono.just(ShouldRetryResult.retryAfter(backoffTime)); } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java index 32a5f75ffe47d..668ae4428b981 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java @@ -24,10 +24,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; -import rx.functions.Func0; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; public class AsyncCache { @@ -42,15 +42,12 @@ public AsyncCache(IEqualityComparer equalityComparer) { } public AsyncCache() { - this(new IEqualityComparer() { - @Override - public boolean areEqual(TValue value1, TValue value2) { - if (value1 == value2) - return true; - if (value1 == null || value2 == null) - return false; - return value1.equals(value2); - } + this((value1, value2) -> { + if (value1 == value2) + return true; + if (value1 == null || value2 == null) + return false; + return value1.equals(value2); }); } @@ -80,27 +77,27 @@ public void set(TKey key, TValue value) { * @param singleValueInitFunc Initialization function. * @return Cached value or value returned by initialization function. */ - public Single getAsync( + public Mono getAsync( TKey key, TValue obsoleteValue, - Func0> singleValueInitFunc) { + Callable> singleValueInitFunc) { AsyncLazy initialLazyValue = values.get(key); if (initialLazyValue != null) { logger.debug("cache[{}] exists", key); - return initialLazyValue.single().toObservable().flatMap(vaule -> { + return initialLazyValue.single().flux().flatMap(value -> { - if (!equalityComparer.areEqual(vaule, obsoleteValue)) { + if (!equalityComparer.areEqual(value, obsoleteValue)) { logger.debug("Returning cache[{}] as it is different from obsoleteValue", key); - return Observable.just(vaule); + return Flux.just(value); } logger.debug("cache[{}] result value is obsolete ({}), computing new value", key, obsoleteValue); AsyncLazy asyncLazy = new AsyncLazy<>(singleValueInitFunc); AsyncLazy actualValue = values.merge(key, asyncLazy, - (lazyValue1, lazyValu2) -> lazyValue1 == initialLazyValue ? lazyValu2 : lazyValue1); - return actualValue.single().toObservable(); + (lazyValue1, lazyValue2) -> lazyValue1 == initialLazyValue ? lazyValue2 : lazyValue1); + return actualValue.single().flux(); }, err -> { @@ -108,9 +105,9 @@ public Single getAsync( AsyncLazy asyncLazy = new AsyncLazy<>(singleValueInitFunc); AsyncLazy resultAsyncLazy = values.merge(key, asyncLazy, (lazyValue1, lazyValu2) -> lazyValue1 == initialLazyValue ? lazyValu2 : lazyValue1); - return resultAsyncLazy.single().toObservable(); + return resultAsyncLazy.single().flux(); - }, () -> Observable.empty()).toSingle(); + }, Flux::empty).single(); } logger.debug("cache[{}] doesn't exist, computing new value", key); @@ -129,7 +126,7 @@ public void remove(TKey key) { * @param key * @return Value if present, default value if not present */ - public Single removeAsync(TKey key) { + public Mono removeAsync(TKey key) { AsyncLazy lazy = values.remove(key); return lazy.single(); // TODO: .Net returns default value on failure of single why? @@ -146,7 +143,7 @@ public void clear() { */ public void refresh( TKey key, - Func0> singleValueInitFunc) { + Callable> singleValueInitFunc) { logger.debug("refreshing cache[{}]", key); AsyncLazy initialLazyValue = values.get(key); if (initialLazyValue != null && (initialLazyValue.isSucceeded() || initialLazyValue.isFaulted())) { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java index cc7053a2735a0..d42e157e8f7b7 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java @@ -24,32 +24,38 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Single; -import rx.functions.Func0; + +import reactor.core.publisher.Mono; + +import java.util.concurrent.Callable; class AsyncLazy { private final static Logger logger = LoggerFactory.getLogger(AsyncLazy.class); - private final Single single; + private final Mono single; private volatile boolean succeeded; private volatile boolean failed; - public AsyncLazy(Func0> func) { - this(Single.defer(() -> { - logger.debug("using Func0> {}", func); - return func.call(); + public AsyncLazy(Callable> func) { + this(Mono.defer(() -> { + logger.debug("using Function> {}", func); + try { + return func.call(); + } catch (Exception e) { + return Mono.error(e); + } })); } public AsyncLazy(TValue value) { - this.single = Single.just(value); + this.single = Mono.just(value); this.succeeded = true; this.failed = false; } - private AsyncLazy(Single single) { + private AsyncLazy(Mono single) { logger.debug("constructor"); this.single = single .doOnSuccess(v -> this.succeeded = true) @@ -57,7 +63,7 @@ private AsyncLazy(Single single) { .cache(); } - public Single single() { + public Mono single() { return single; } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java index 43f5c8ec066ea..f30e7a9fcdec3 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.internal.IRoutingMapProvider; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import com.azure.data.cosmos.internal.routing.Range; -import rx.Single; +import reactor.core.publisher.Mono; import java.util.List; import java.util.Map; @@ -37,14 +37,14 @@ */ public interface IPartitionKeyRangeCache extends IRoutingMapProvider, ICollectionRoutingMapCache { - Single tryLookupAsync(String collectionRid, CollectionRoutingMap previousValue, Map properties); + Mono tryLookupAsync(String collectionRid, CollectionRoutingMap previousValue, Map properties); - Single> tryGetOverlappingRangesAsync(String collectionRid, Range range, boolean forceRefresh, + Mono> tryGetOverlappingRangesAsync(String collectionRid, Range range, boolean forceRefresh, Map properties); - Single tryGetPartitionKeyRangeByIdAsync(String collectionResourceId, String partitionKeyRangeId, boolean forceRefresh, + Mono tryGetPartitionKeyRangeByIdAsync(String collectionResourceId, String partitionKeyRangeId, boolean forceRefresh, Map properties); - Single tryGetRangeByPartitionKeyRangeId(String collectionRid, String partitionKeyRangeId, Map properties); + Mono tryGetRangeByPartitionKeyRangeId(String collectionRid, String partitionKeyRangeId, Map properties); } \ No newline at end of file diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java index 08a1346bbbd36..84116a4a01a29 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java @@ -39,8 +39,8 @@ import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import com.azure.data.cosmos.internal.RxStoreModel; import com.azure.data.cosmos.internal.Utils; -import rx.Observable; -import rx.Single; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @@ -69,28 +69,28 @@ public RxClientCollectionCache(ISessionContainer sessionContainer, this.sessionContainer = sessionContainer; } - protected Single getByRidAsync(String collectionRid, Map properties) { + protected Mono getByRidAsync(String collectionRid, Map properties) { IDocumentClientRetryPolicy retryPolicyInstance = new ClearingSessionContainerClientRetryPolicy(this.sessionContainer, this.retryPolicy.getRequestPolicy()); return ObservableHelper.inlineIfPossible( () -> this.readCollectionAsync(PathsHelper.generatePath(ResourceType.DocumentCollection, collectionRid, false), retryPolicyInstance, properties) , retryPolicyInstance); } - protected Single getByNameAsync(String resourceAddress, Map properties) { + protected Mono getByNameAsync(String resourceAddress, Map properties) { IDocumentClientRetryPolicy retryPolicyInstance = new ClearingSessionContainerClientRetryPolicy(this.sessionContainer, this.retryPolicy.getRequestPolicy()); return ObservableHelper.inlineIfPossible( () -> this.readCollectionAsync(resourceAddress, retryPolicyInstance, properties), retryPolicyInstance); } - private Single readCollectionAsync(String collectionLink, IDocumentClientRetryPolicy retryPolicyInstance, Map properties) { + private Mono readCollectionAsync(String collectionLink, IDocumentClientRetryPolicy retryPolicyInstance, Map properties) { String path = Utils.joinPath(collectionLink, null); RxDocumentServiceRequest request = RxDocumentServiceRequest.create( OperationType.Read, ResourceType.DocumentCollection, path, - new HashMap()); + new HashMap<>()); request.getHeaders().put(HttpConstants.HttpHeaders.X_DATE, Utils.nowAsRFC1123()); @@ -106,7 +106,7 @@ private Single readCollectionAsync(String collectionLink, ID try { authorizationToken = URLEncoder.encode(authorizationToken, "UTF-8"); } catch (UnsupportedEncodingException e) { - return Single.error(new IllegalStateException("Failed to encode authtoken.", e)); + return Mono.error(new IllegalStateException("Failed to encode authtoken.", e)); } request.getHeaders().put(HttpConstants.HttpHeaders.AUTHORIZATION, authorizationToken); @@ -114,8 +114,8 @@ private Single readCollectionAsync(String collectionLink, ID retryPolicyInstance.onBeforeSendRequest(request); } - Observable responseObs = this.storeModel.processMessage(request); + Flux responseObs = this.storeModel.processMessage(request); return responseObs.map(response -> BridgeInternal.toResourceResponse(response, DocumentCollection.class) - .getResource()).toSingle(); + .getResource()).single(); } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java index adfcc0689804a..e7e3e2cf8e01b 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java @@ -31,8 +31,7 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import org.apache.commons.lang3.StringUtils; -import rx.Completable; -import rx.Single; +import reactor.core.publisher.Mono; import java.util.Map; @@ -46,8 +45,8 @@ public abstract class RxCollectionCache { private final AsyncCache collectionInfoByIdCache; protected RxCollectionCache() { - this.collectionInfoByNameCache = new AsyncCache(new CollectionRidComparer()); - this.collectionInfoByIdCache = new AsyncCache(new CollectionRidComparer()); + this.collectionInfoByNameCache = new AsyncCache<>(new CollectionRidComparer()); + this.collectionInfoByIdCache = new AsyncCache<>(new CollectionRidComparer()); } /** @@ -56,30 +55,27 @@ protected RxCollectionCache() { * @param request Request to resolve. * @return an instance of Single<DocumentCollection> */ - public Single resolveCollectionAsync( + public Mono resolveCollectionAsync( RxDocumentServiceRequest request) { - Completable init = null; + // Mono Void to represent only terminal events specifically complete and error + Mono init = null; if (request.getIsNameBased()) { if (request.isForceNameCacheRefresh()) { - Completable completable = this.refreshAsync(request); - init = completable.andThen(Completable.fromAction(() -> request.setForceNameCacheRefresh(false))); + Mono mono = this.refreshAsync(request); + init = mono.then(Mono.fromRunnable(() -> request.setForceNameCacheRefresh(false))); } - Single collectionInfoObs = this.resolveByPartitionKeyRangeIdentityAsync( + Mono collectionInfoObs = this.resolveByPartitionKeyRangeIdentityAsync( request.getPartitionKeyRangeIdentity(), request.properties); if (init != null) { - collectionInfoObs = init.andThen(collectionInfoObs); + collectionInfoObs = init.then(collectionInfoObs); } - return collectionInfoObs.flatMap(collectionInfo -> { - if (collectionInfo != null) { - return Single.just(collectionInfo); - } - + return collectionInfoObs.flatMap(Mono::just).switchIfEmpty(Mono.defer(() -> { if (request.requestContext.resolvedCollectionRid == null) { - Single collectionInfoRes = this.resolveByNameAsync(request.getResourceAddress(), request.properties); + Mono collectionInfoRes = this.resolveByNameAsync(request.getResourceAddress(), request.properties); return collectionInfoRes.flatMap(collection -> { // TODO: how to async log this? @@ -90,23 +86,16 @@ public Single resolveCollectionAsync( request.setResourceId(collection.resourceId()); request.requestContext.resolvedCollectionRid = collection.resourceId(); - return Single.just(collection); + return Mono.just(collection); }); } else { return this.resolveByRidAsync(request.requestContext.resolvedCollectionRid, request.properties); - } - }); + } + })); } else { return resolveByPartitionKeyRangeIdentityAsync(request.getPartitionKeyRangeIdentity(),request.properties) - .flatMap(collection -> { - - if (collection != null) { - return Single.just(collection); - } - - return this.resolveByRidAsync(request.getResourceAddress(), request.properties); - }); + .flatMap(Mono::just).switchIfEmpty(this.resolveByRidAsync(request.getResourceAddress(), request.properties)); } } @@ -121,37 +110,35 @@ public void refresh(String resourceAddress, Map properties) { this.collectionInfoByNameCache.refresh( resourceFullName, () -> { - Single collectionObs = this.getByNameAsync(resourceFullName, properties); - return collectionObs.doOnSuccess(collection -> { - this.collectionInfoByIdCache.set(collection.resourceId(), collection); - }); + Mono collectionObs = this.getByNameAsync(resourceFullName, properties); + return collectionObs.doOnSuccess(collection -> this.collectionInfoByIdCache.set(collection.resourceId(), collection)); }); } } - protected abstract Single getByRidAsync(String collectionRid, Map properties); + protected abstract Mono getByRidAsync(String collectionRid, Map properties); - protected abstract Single getByNameAsync(String resourceAddress, Map properties); + protected abstract Mono getByNameAsync(String resourceAddress, Map properties); - private Single resolveByPartitionKeyRangeIdentityAsync(PartitionKeyRangeIdentity partitionKeyRangeIdentity, Map properties) { + private Mono resolveByPartitionKeyRangeIdentityAsync(PartitionKeyRangeIdentity partitionKeyRangeIdentity, Map properties) { // if request is targeted at specific partition using x-ms-documentd-partitionkeyrangeid header, // which contains value ",", then resolve to collection rid in this header. if (partitionKeyRangeIdentity != null && partitionKeyRangeIdentity.getCollectionRid() != null) { return this.resolveByRidAsync(partitionKeyRangeIdentity.getCollectionRid(), properties) - .onErrorResumeNext(e -> { + .onErrorResume(e -> { if (e instanceof NotFoundException) { // This is signal to the upper logic either to refresh // collection cache and retry. - return Single.error(new InvalidPartitionException(RMResources.InvalidDocumentCollection)); + return Mono.error(new InvalidPartitionException(RMResources.InvalidDocumentCollection)); } - return Single.error(e); + return Mono.error(e); }); } - return Single.just(null); + return Mono.empty(); } - private Single resolveByRidAsync( + private Mono resolveByRidAsync( String resourceId, Map properties) { ResourceId resourceIdParsed = ResourceId.parse(resourceId); @@ -163,7 +150,7 @@ private Single resolveByRidAsync( () -> this.getByRidAsync(collectionResourceId, properties)); } - private Single resolveByNameAsync( + private Mono resolveByNameAsync( String resourceAddress, Map properties) { String resourceFullName = PathsHelper.getCollectionPath(resourceAddress); @@ -172,40 +159,38 @@ private Single resolveByNameAsync( resourceFullName, null, () -> { - Single collectionObs = this.getByNameAsync(resourceFullName, properties); - return collectionObs.doOnSuccess(collection -> { - this.collectionInfoByIdCache.set(collection.resourceId(), collection); - }); + Mono collectionObs = this.getByNameAsync(resourceFullName, properties); + return collectionObs.doOnSuccess(collection -> this.collectionInfoByIdCache.set(collection.resourceId(), collection)); }); } - private Completable refreshAsync(RxDocumentServiceRequest request) { + private Mono refreshAsync(RxDocumentServiceRequest request) { // TODO System.Diagnostics.Debug.Assert(request.IsNameBased); String resourceFullName = PathsHelper.getCollectionPath(request.getResourceAddress()); - Completable completable = null; + Mono mono; if (request.requestContext.resolvedCollectionRid != null) { // Here we will issue backend call only if cache wasn't already refreshed (if whatever is there corresponds to previously resolved collection rid). DocumentCollection obsoleteValue = new DocumentCollection(); obsoleteValue.resourceId(request.requestContext.resolvedCollectionRid); - completable = this.collectionInfoByNameCache.getAsync( + mono = this.collectionInfoByNameCache.getAsync( resourceFullName, obsoleteValue, () -> { - Single collectionObs = this.getByNameAsync(resourceFullName, request.properties); + Mono collectionObs = this.getByNameAsync(resourceFullName, request.properties); return collectionObs.doOnSuccess(collection -> { this.collectionInfoByIdCache.set(collection.resourceId(), collection); }); - }).toCompletable(); + }).then(); } else { // In case of ForceRefresh directive coming from client, there will be no ResolvedCollectionRid, so we // need to refresh unconditionally. - completable = Completable.fromAction(() -> this.refresh(request.getResourceAddress(), request.properties)); + mono = Mono.fromRunnable(() -> this.refresh(request.getResourceAddress(), request.properties)); } - return completable.doOnCompleted(() -> request.requestContext.resolvedCollectionRid = null); + return mono.doOnSuccess(aVoid -> request.requestContext.resolvedCollectionRid = null); } private class CollectionRidComparer implements IEqualityComparer { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java index 4abc554dda8f2..af0c75f888cc5 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java @@ -38,7 +38,7 @@ import com.azure.data.cosmos.internal.query.aggregation.MaxAggregator; import com.azure.data.cosmos.internal.query.aggregation.MinAggregator; import com.azure.data.cosmos.internal.query.aggregation.SumAggregator; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.Collection; @@ -84,10 +84,10 @@ public AggregateDocumentQueryExecutionContext (IDocumentQueryExecutionComponent< @SuppressWarnings("unchecked") @Override - public Observable> drainAsync(int maxPageSize) { + public Flux> drainAsync(int maxPageSize) { return this.component.drainAsync(maxPageSize) - .toList() + .collectList() .map( superList -> { double requestCharge = 0; @@ -130,11 +130,11 @@ public Observable> drainAsync(int maxPageSize) { } } return (FeedResponse) frp; - }); + }).flux(); } - public static Observable> createAsync( - Function>> createSourceComponentFunction, + public static Flux> createAsync( + Function>> createSourceComponentFunction, Collection aggregates, String continuationToken) { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java index bd24a186bf5c4..2afca90e9ff3e 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java @@ -51,15 +51,15 @@ import com.azure.data.cosmos.internal.routing.Range; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import rx.Observable; -import rx.Single; -import rx.functions.Func1; -import rx.functions.Func2; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Function; /** * While this class is public, but it is not part of our published public APIs. @@ -98,7 +98,7 @@ protected PartitionKeyInternal getPartitionKeyInternal() { } @Override - public Observable> executeAsync() { + public Flux> executeAsync() { if (feedOptions == null) { feedOptions = new FeedOptions(); @@ -121,23 +121,23 @@ public Observable> executeAsync() { int maxPageSize = newFeedOptions.maxItemCount() != null ? newFeedOptions.maxItemCount() : Constants.Properties.DEFAULT_MAX_PAGE_SIZE; - Func2 createRequestFunc = (continuationToken, pageSize) -> this.createRequestAsync(continuationToken, pageSize); + BiFunction createRequestFunc = (continuationToken, pageSize) -> this.createRequestAsync(continuationToken, pageSize); // TODO: clean up if we want to use single vs observable. - Func1>> executeFunc = executeInternalAsyncFunc(); + Function>> executeFunc = executeInternalAsyncFunc(); return Paginator .getPaginatedQueryResultAsObservable(newFeedOptions, createRequestFunc, executeFunc, resourceType, maxPageSize); } - public Single> getTargetPartitionKeyRanges(String resourceId, List> queryRanges) { + public Mono> getTargetPartitionKeyRanges(String resourceId, List> queryRanges) { // TODO: FIXME this needs to be revisited Range r = new Range<>("", "FF", true, false); return client.getPartitionKeyRangeCache().tryGetOverlappingRangesAsync(resourceId, r, false, null); } - protected Func1>> executeInternalAsyncFunc() { + protected Function>> executeInternalAsyncFunc() { RxCollectionCache collectionCache = this.client.getCollectionCache(); IPartitionKeyRangeCache partitionKeyRangeCache = this.client.getPartitionKeyRangeCache(); IDocumentClientRetryPolicy retryPolicyInstance = this.client.getResetSessionTokenRetryPolicy().getRequestPolicy(); @@ -154,14 +154,14 @@ protected Func1>> executeIn final IDocumentClientRetryPolicy finalRetryPolicyInstance = retryPolicyInstance; - Func1>> executeFunc = req -> { + return req -> { finalRetryPolicyInstance.onBeforeSendRequest(req); this.fetchExecutionRangeAccumulator.beginFetchRange(); this.fetchSchedulingMetrics.start(); return BackoffRetryUtility.executeRetry(() -> { ++this.retries; return executeRequestAsync(req); - }, finalRetryPolicyInstance).toObservable() + }, finalRetryPolicyInstance).flux() .map(tFeedResponse -> { this.fetchSchedulingMetrics.stop(); this.fetchExecutionRangeAccumulator.endFetchRange(tFeedResponse.activityId(), @@ -183,11 +183,9 @@ protected Func1>> executeIn return tFeedResponse; }); }; - - return executeFunc; } - private Single> executeOnceAsync(IDocumentClientRetryPolicy retryPolicyInstance, String continuationToken) { + private Mono> executeOnceAsync(IDocumentClientRetryPolicy retryPolicyInstance, String continuationToken) { // Don't reuse request, as the rest of client SDK doesn't reuse requests between retries. // The code leaves some temporary garbage in request (in RequestContext etc.), // which shold be erased during retries. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java index 9181fbeef53f8..cf420023fd6e9 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java @@ -26,6 +26,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.QueryMetrics; import com.azure.data.cosmos.QueryMetricsConstants; @@ -45,17 +46,16 @@ import org.apache.commons.lang3.tuple.ImmutablePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; -import rx.functions.Func0; -import rx.functions.Func1; -import rx.functions.Func2; -import rx.functions.Func3; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.function.BiFunction; +import java.util.function.Function; import java.util.stream.Collectors; /** @@ -106,9 +106,9 @@ void populatePartitionedQueryMetrics() { protected final Class resourceType; protected final PartitionKeyRange targetRange; protected final String collectionLink; - protected final Func3 createRequestFunc; - protected final Func1>> executeRequestFuncWithRetries; - protected final Func0 createRetryPolicyFunc; + protected final TriFunction createRequestFunc; + protected final Function>> executeRequestFuncWithRetries; + protected final Callable createRetryPolicyFunc; protected final int pageSize; protected final UUID correlatedActivityId; public int top; @@ -121,11 +121,11 @@ public DocumentProducer( IDocumentQueryClient client, String collectionResourceId, FeedOptions feedOptions, - Func3 createRequestFunc, - Func1>> executeRequestFunc, + TriFunction createRequestFunc, + Function>> executeRequestFunc, PartitionKeyRange targetRange, String collectionLink, - Func0 createRetryPolicyFunc, + Callable createRetryPolicyFunc, Class resourceType , UUID correlatedActivityId, int initialPageSize, // = -1, @@ -147,13 +147,17 @@ public DocumentProducer( this.fetchExecutionRangeAccumulator.beginFetchRange(); IDocumentClientRetryPolicy retryPolicy = null; if (createRetryPolicyFunc != null) { - retryPolicy = createRetryPolicyFunc.call(); + try { + retryPolicy = createRetryPolicyFunc.call(); + } catch (Exception e) { + return Flux.error(e); + } retryPolicy.onBeforeSendRequest(request); } return ObservableHelper.inlineIfPossibleAsObs( () -> { ++retries; - return executeRequestFunc.call(request); + return executeRequestFunc.apply(request); }, retryPolicy); }; @@ -170,10 +174,10 @@ public DocumentProducer( this.top = top; } - public Observable produceAsync() { - Func2 sourcePartitionCreateRequestFunc = - (token, maxItemCount) -> createRequestFunc.call(targetRange, token, maxItemCount); - Observable> obs = Paginator + public Flux produceAsync() { + BiFunction sourcePartitionCreateRequestFunc = + (token, maxItemCount) -> createRequestFunc.apply(targetRange, token, maxItemCount); + Flux> obs = Paginator .getPaginatedQueryResultAsObservable( feedOptions, sourcePartitionCreateRequestFunc, @@ -188,44 +192,44 @@ public Observable produceAsync() { this.retries); this.fetchSchedulingMetrics.stop(); return rsp;}); - - return splitProof(obs.map(page -> new DocumentProducerFeedResponse(page))); + + return splitProof(obs.map(DocumentProducerFeedResponse::new)); } - private Observable splitProof(Observable sourceFeedResponseObservable) { - return sourceFeedResponseObservable.onErrorResumeNext( t -> { + private Flux splitProof(Flux sourceFeedResponseObservable) { + return sourceFeedResponseObservable.onErrorResume( t -> { CosmosClientException dce = Utils.as(t, CosmosClientException.class); if (dce == null || !isSplit(dce)) { logger.error("Unexpected failure", t); - return Observable.error(t); + return Flux.error(t); } // we are dealing with Split logger.info("DocumentProducer handling a partition split in [{}], detail:[{}]", targetRange, dce); - Single> replacementRangesObs = getReplacementRanges(targetRange.toRange()); + Mono> replacementRangesObs = getReplacementRanges(targetRange.toRange()); // Since new DocumentProducers are instantiated for the new replacement ranges, if for the new // replacement partitions split happens the corresponding DocumentProducer can recursively handle splits. // so this is resilient to split on splits. - Observable> replacementProducers = replacementRangesObs.toObservable().flatMap( + Flux> replacementProducers = replacementRangesObs.flux().flatMap( partitionKeyRanges -> { if (logger.isDebugEnabled()) { logger.info("Cross Partition Query Execution detected partition [{}] split into [{}] partitions," + " last continuation token is [{}].", targetRange.toJson(), - String.join(", ", partitionKeyRanges.stream() - .map(pkr -> pkr.toJson()).collect(Collectors.toList())), + partitionKeyRanges.stream() + .map(JsonSerializable::toJson).collect(Collectors.joining(", ")), lastResponseContinuationToken); } - return Observable.from(createReplacingDocumentProducersOnSplit(partitionKeyRanges)); + return Flux.fromIterable(createReplacingDocumentProducersOnSplit(partitionKeyRanges)); }); return produceOnSplit(replacementProducers); }); } - protected Observable produceOnSplit(Observable> replacingDocumentProducers) { - return replacingDocumentProducers.flatMap(dp -> dp.produceAsync(), 1); + protected Flux produceOnSplit(Flux> replacingDocumentProducers) { + return replacingDocumentProducers.flatMap(DocumentProducer::produceAsync, 1); } private List> createReplacingDocumentProducersOnSplit(List partitionKeyRanges) { @@ -257,7 +261,7 @@ protected DocumentProducer createChildDocumentProducerOnSplit( top); } - private Single> getReplacementRanges(Range range) { + private Mono> getReplacementRanges(Range range) { return client.getPartitionKeyRangeCache().tryGetOverlappingRangesAsync(collectionRid, range, true, feedOptions.properties()); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java index e317c133dec78..46f6d269d93bb 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java @@ -41,8 +41,8 @@ import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import rx.Observable; -import rx.Single; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.io.UnsupportedEncodingException; import java.util.HashMap; @@ -82,7 +82,7 @@ protected DocumentQueryExecutionContextBase(IDocumentQueryClient client, Resourc } @Override - abstract public Observable> executeAsync(); + abstract public Flux> executeAsync(); public String getPartitionKeyId() { // TODO Auto-generated method stub @@ -115,20 +115,20 @@ protected RxDocumentServiceRequest createDocumentServiceRequest(Map> executeRequestAsync(RxDocumentServiceRequest request) { + public Mono> executeRequestAsync(RxDocumentServiceRequest request) { return (this.shouldExecuteQueryRequest ? this.executeQueryRequestAsync(request) : this.executeReadFeedRequestAsync(request)); } - public Single> executeQueryRequestAsync(RxDocumentServiceRequest request) { + public Mono> executeQueryRequestAsync(RxDocumentServiceRequest request) { return this.getFeedResponse(this.executeQueryRequestInternalAsync(request)); } - public Single> executeReadFeedRequestAsync(RxDocumentServiceRequest request) { + public Mono> executeReadFeedRequestAsync(RxDocumentServiceRequest request) { return this.getFeedResponse(this.client.readFeedAsync(request)); } - protected Single> getFeedResponse(Single response) { + protected Mono> getFeedResponse(Mono response) { return response.map(resp -> BridgeInternal.toFeedResponsePage(resp, resourceType)); } @@ -139,7 +139,7 @@ public FeedOptions getFeedOptions(String continuationToken, Integer maxPageSize) return options; } - private Single executeQueryRequestInternalAsync(RxDocumentServiceRequest request) { + private Mono executeQueryRequestInternalAsync(RxDocumentServiceRequest request) { return this.client.executeQueryAsync(request); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java index 8b1118dd45e74..3cb8f4136437a 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java @@ -35,8 +35,8 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.caches.RxCollectionCache; -import rx.Observable; -import rx.Single; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.util.List; import java.util.UUID; @@ -49,7 +49,7 @@ public class DocumentQueryExecutionContextFactory { private final static int PageSizeFactorForTop = 5; - private static Single resolveCollection(IDocumentQueryClient client, SqlQuerySpec query, + private static Mono resolveCollection(IDocumentQueryClient client, SqlQuerySpec query, ResourceType resourceTypeEnum, String resourceLink) { RxCollectionCache collectionCache = client.getCollectionCache(); @@ -63,7 +63,7 @@ private static Single resolveCollection(IDocumentQueryClient return collectionCache.resolveCollectionAsync(request); } - public static Observable> createDocumentQueryExecutionContextAsync( + public static Flux> createDocumentQueryExecutionContextAsync( IDocumentQueryClient client, ResourceType resourceTypeEnum, Class resourceType, @@ -74,17 +74,17 @@ public static Observable collectionObs = Observable.just(null); + Flux collectionObs = Flux.empty(); if (resourceTypeEnum.isCollectionChild()) { - collectionObs = resolveCollection(client, query, resourceTypeEnum, resourceLink).toObservable(); + collectionObs = resolveCollection(client, query, resourceTypeEnum, resourceLink).flux(); } // We create a ProxyDocumentQueryExecutionContext that will be initialized with DefaultDocumentQueryExecutionContext // which will be used to send the query to GATEWAY and on getting 400(bad request) with 1004(cross parition query not servable), we initialize it with // PipelinedDocumentQueryExecutionContext by providing the partition query execution info that's needed(which we get from the exception returned from GATEWAY). - Observable> proxyQueryExecutionContext = + Flux> proxyQueryExecutionContext = collectionObs.flatMap(collection -> { if (feedOptions != null && feedOptions.partitionKey() != null && feedOptions.partitionKey().equals(PartitionKey.None)) { feedOptions.partitionKey(BridgeInternal.getPartitionKey(BridgeInternal.getNonePartitionKey(collection.getPartitionKey()))); @@ -99,12 +99,21 @@ public static Observable Observable> createSpecializedDocumentQueryExecutionContextAsync( + public static Flux> createSpecializedDocumentQueryExecutionContextAsync( IDocumentQueryClient client, ResourceType resourceTypeEnum, Class resourceType, @@ -122,7 +131,7 @@ public static Observable 0, "MaxItemCount", "INVALID MaxItemCount %s", initialPageSize); if (validationError != null) { - return Observable.error(validationError); + return Flux.error(validationError); } QueryInfo queryInfo = partitionedQueryExecutionInfo.getQueryInfo(); diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java index d5f1834c53897..c71717b72c308 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java @@ -31,15 +31,16 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.functions.Func1; -import rx.functions.Func2; +import reactor.core.publisher.Flux; + +import java.util.function.BiFunction; +import java.util.function.Function; class Fetcher { private final static Logger logger = LoggerFactory.getLogger(Fetcher.class); - private final Func2 createRequestFunc; - private final Func1>> executeFunc; + private final BiFunction createRequestFunc; + private final Function>> executeFunc; private final boolean isChangeFeed; private volatile boolean shouldFetchMore; @@ -47,8 +48,8 @@ class Fetcher { private volatile int top; private volatile String continuationToken; - public Fetcher(Func2 createRequestFunc, - Func1>> executeFunc, + public Fetcher(BiFunction createRequestFunc, + Function>> executeFunc, FeedOptionsBase options, boolean isChangeFeed, int top, @@ -73,7 +74,7 @@ public boolean shouldFetchMore() { return shouldFetchMore; } - public Observable> nextPage() { + public Flux> nextPage() { RxDocumentServiceRequest request = createRequest(); return nextPage(request); } @@ -109,11 +110,11 @@ private RxDocumentServiceRequest createRequest() { throw new IllegalStateException("INVALID state, trying to fetch more after completion"); } - return createRequestFunc.call(continuationToken, maxItemCount); + return createRequestFunc.apply(continuationToken, maxItemCount); } - private Observable> nextPage(RxDocumentServiceRequest request) { - return executeFunc.call(request).map(rsp -> { + private Flux> nextPage(RxDocumentServiceRequest request) { + return executeFunc.apply(request).map(rsp -> { updateState(rsp); return rsp; }); diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java index 6a9016170dcb1..6bd7f74abcece 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; import com.azure.data.cosmos.internal.caches.RxCollectionCache; -import rx.Single; +import reactor.core.publisher.Mono; /** * While this class is public, but it is not part of our published public APIs. @@ -65,7 +65,7 @@ public interface IDocumentQueryClient { */ ConsistencyLevel getDesiredConsistencyLevelAsync(); - Single executeQueryAsync(RxDocumentServiceRequest request); + Mono executeQueryAsync(RxDocumentServiceRequest request); QueryCompatibilityMode getQueryCompatibilityMode(); @@ -91,5 +91,5 @@ enum QueryCompatibilityMode { SqlQuery } - Single readFeedAsync(RxDocumentServiceRequest request); + Mono readFeedAsync(RxDocumentServiceRequest request); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java index a0f223edf6e7e..4825b6931de0b 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; -import rx.Observable; +import reactor.core.publisher.Flux; /** * While this class is public, but it is not part of our published public APIs. @@ -32,5 +32,5 @@ */ public interface IDocumentQueryExecutionComponent { - Observable> drainAsync(int maxPageSize); + Flux> drainAsync(int maxPageSize); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java index abac466aa9595..9134daf10b657 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; -import rx.Observable; +import reactor.core.publisher.Flux; /** * While this class is public, but it is not part of our published public APIs. @@ -32,5 +32,5 @@ */ public interface IDocumentQueryExecutionContext { - Observable> executeAsync(); + Flux> executeAsync(); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java index beca1b5f00d90..4632d7c7b43dd 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java @@ -35,15 +35,14 @@ import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; -import rx.Observable; -import rx.functions.Func0; -import rx.functions.Func1; -import rx.functions.Func3; +import reactor.core.publisher.Flux; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.function.Function; class OrderByDocumentProducer extends DocumentProducer { private final OrderbyRowComparer consumeComparer; @@ -54,11 +53,11 @@ class OrderByDocumentProducer extends DocumentProducer { IDocumentQueryClient client, String collectionResourceId, FeedOptions feedOptions, - Func3 createRequestFunc, - Func1>> executeRequestFunc, + TriFunction createRequestFunc, + Function>> executeRequestFunc, PartitionKeyRange targetRange, String collectionLink, - Func0 createRetryPolicyFunc, + Callable createRetryPolicyFunc, Class resourceType, UUID correlatedActivityId, int initialPageSize, @@ -71,16 +70,14 @@ class OrderByDocumentProducer extends DocumentProducer { this.targetRangeToOrderByContinuationTokenMap = targetRangeToOrderByContinuationTokenMap; } - protected Observable produceOnSplit(Observable> replacementProducers) { - Observable res = replacementProducers.toList().single().flatMap(documentProducers -> { + protected Flux produceOnSplit(Flux> replacementProducers) { + return replacementProducers.collectList().flux().flatMap(documentProducers -> { RequestChargeTracker tracker = new RequestChargeTracker(); Map queryMetricsMap = new HashMap<>(); return OrderByUtils.orderedMerge(resourceType, consumeComparer, tracker, documentProducers, queryMetricsMap, targetRangeToOrderByContinuationTokenMap) .map(orderByQueryResult -> resultPageFrom(tracker, orderByQueryResult)); }); - - return res; } @SuppressWarnings("unchecked") diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java index 927f456fa646e..c120402c15f8a 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java @@ -42,11 +42,8 @@ import com.azure.data.cosmos.internal.routing.Range; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.tuple.ImmutablePair; -import rx.Observable; -import rx.Observable.Transformer; -import rx.functions.Func0; -import rx.functions.Func1; -import rx.functions.Func3; +import reactor.core.Exceptions; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.Collection; @@ -54,6 +51,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; @@ -70,7 +68,7 @@ public class OrderByDocumentQueryExecutionContext private final OrderbyRowComparer consumeComparer; private final RequestChargeTracker tracker; private final ConcurrentMap queryMetricMap; - private Observable> orderByObservable; + private Flux> orderByObservable; private final Map targetRangeToOrderByContinuationTokenMap; private OrderByDocumentQueryExecutionContext( @@ -96,7 +94,7 @@ private OrderByDocumentQueryExecutionContext( targetRangeToOrderByContinuationTokenMap = new HashMap<>(); } - public static Observable> createAsync( + public static Flux> createAsync( IDocumentQueryClient client, ResourceType resourceTypeEnum, Class resourceType, @@ -132,9 +130,9 @@ public static Observable createDocumentProducer( FeedOptions feedOptions, SqlQuerySpec querySpecForInit, Map commonRequestHeaders, - Func3 createRequestFunc, - Func1>> executeFunc, - Func0 createRetryPolicyFunc) { + TriFunction createRequestFunc, + Function>> executeFunc, + Callable createRetryPolicyFunc) { return new OrderByDocumentProducer(consumeComparer, client, collectionRid, @@ -406,7 +404,7 @@ protected OrderByDocumentProducer createDocumentProducer( } private static class ItemToPageTransformer - implements Transformer, FeedResponse> { + implements Function>, Flux>> { private final static int DEFAULT_PAGE_SIZE = 100; private final RequestChargeTracker tracker; private final int maxPageSize; @@ -444,12 +442,11 @@ private FeedResponse> addOrderByContinuationToken( } @Override - public Observable> call( - Observable> source) { + public Flux> apply(Flux> source) { return source // .windows: creates an observable of observable where inner observable // emits max maxPageSize elements - .window(maxPageSize).map(o -> o.toList()) + .window(maxPageSize).map(Flux::collectList) // flattens the observable>>> to // Observable>> .flatMap(resultListObs -> resultListObs, @@ -472,8 +469,8 @@ public Observable> call( }) // Emit an empty page so the downstream observables know when there are no more // results. - .concatWith(Observable.defer(() -> { - return Observable.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(), + .concatWith(Flux.defer(() -> { + return Flux.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(), null)); })) // CREATE pairs from the stream to allow the observables downstream to "peek" @@ -521,16 +518,16 @@ public Observable> call( return BridgeInternal.createFeedResponseWithQueryMetrics(unwrappedResults, feedOfOrderByRowResults.responseHeaders(), feedOfOrderByRowResults.queryMetrics()); - }).switchIfEmpty(Observable.defer(() -> { + }).switchIfEmpty(Flux.defer(() -> { // create an empty page if there is no result - return Observable.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(), + return Flux.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(), headerResponse(tracker.getAndResetCharge()))); })); } } @Override - public Observable> drainAsync( + public Flux> drainAsync( int maxPageSize) { //// In order to maintain the continuation token for the user we must drain with //// a few constraints @@ -565,14 +562,11 @@ public Observable> drainAsync( return this.orderByObservable.compose(new ItemToPageTransformer(tracker, maxPageSize, this.queryMetricMap, - ( - orderByRowResult) -> { - return this.getContinuationToken(orderByRowResult); - })); + this::getContinuationToken)); } @Override - public Observable> executeAsync() { + public Flux> executeAsync() { return drainAsync(feedOptions.maxItemCount()); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java index 05730e8398d95..7f7d2cb7a6753 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java @@ -31,45 +31,44 @@ import com.azure.data.cosmos.internal.query.orderbyquery.OrderbyRowComparer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; -import com.github.davidmoten.rx.Transformers; import org.apache.commons.lang3.tuple.Pair; -import rx.Observable; -import rx.Observable.Transformer; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.function.Function; import java.util.stream.Collectors; class OrderByUtils { - public static Observable> orderedMerge(Class klass, - OrderbyRowComparer consumeComparer, - RequestChargeTracker tracker, - List> documentProducers, - Map queryMetricsMap, - Map targetRangeToOrderByContinuationTokenMap) { - return toOrderByQueryResultObservable(klass, documentProducers.get(0), tracker, queryMetricsMap, targetRangeToOrderByContinuationTokenMap, consumeComparer.getSortOrders()) - .compose( - Transformers.orderedMergeWith( - documentProducers.subList(1, documentProducers.size()) - .stream() - .map(producer -> toOrderByQueryResultObservable(klass, producer, tracker, queryMetricsMap, targetRangeToOrderByContinuationTokenMap, consumeComparer.getSortOrders())) - .collect(Collectors.toList()), consumeComparer, false, 1)); + public static Flux> orderedMerge(Class klass, + OrderbyRowComparer consumeComparer, + RequestChargeTracker tracker, + List> documentProducers, + Map queryMetricsMap, + Map targetRangeToOrderByContinuationTokenMap) { + Flux>[] fluxes = documentProducers + .subList(0, documentProducers.size()) + .stream() + .map(producer -> + toOrderByQueryResultObservable(klass, producer, tracker, queryMetricsMap, targetRangeToOrderByContinuationTokenMap, consumeComparer.getSortOrders())) + .toArray(Flux[]::new); + return Flux.mergeOrdered(consumeComparer, fluxes); } - private static Observable> toOrderByQueryResultObservable(Class klass, - DocumentProducer producer, - RequestChargeTracker tracker, - Map queryMetricsMap, - Map targetRangeToOrderByContinuationTokenMap, - List sortOrders) { + private static Flux> toOrderByQueryResultObservable(Class klass, + DocumentProducer producer, + RequestChargeTracker tracker, + Map queryMetricsMap, + Map targetRangeToOrderByContinuationTokenMap, + List sortOrders) { return producer .produceAsync() .compose(new OrderByUtils.PageToItemTransformer(klass, tracker, queryMetricsMap, targetRangeToOrderByContinuationTokenMap, sortOrders)); } - private static class PageToItemTransformer implements Transformer.DocumentProducerFeedResponse, OrderByRowResult> { + private static class PageToItemTransformer implements Function.DocumentProducerFeedResponse>, Flux>> { private final RequestChargeTracker tracker; private final Class klass; private final Map queryMetricsMap; @@ -86,7 +85,7 @@ public PageToItemTransformer(Class klass, RequestChargeTracker tracker, Map> call(Observable.DocumentProducerFeedResponse> source) { + public Flux> apply(Flux.DocumentProducerFeedResponse> source) { return source.flatMap(documentProducerFeedResponse -> { for (String key : documentProducerFeedResponse.pageResult.queryMetrics().keySet()) { if (queryMetricsMap.containsKey(key)) { @@ -101,7 +100,7 @@ public Observable> call(Observable.Docum if (orderByContinuationToken != null) { Pair booleanResourceIdPair = ResourceId.tryParse(orderByContinuationToken.getRid()); if (!booleanResourceIdPair.getLeft()) { - return Observable.error(new BadRequestException(String.format("INVALID Rid in the continuation token %s for OrderBy~Context.", + return Flux.error(new BadRequestException(String.format("INVALID Rid in the continuation token %s for OrderBy~Context.", orderByContinuationToken.getCompositeContinuationToken().getToken()))); } ResourceId continuationTokenRid = booleanResourceIdPair.getRight(); @@ -130,7 +129,7 @@ public Observable> call(Observable.Docum break; } } - + if (cmp == 0) { // Once the item matches the order by items from the continuation tokens // We still need to remove all the documents that have a lower rid in the rid sort order. @@ -152,7 +151,7 @@ public Observable> call(Observable.Docum } tracker.addCharge(documentProducerFeedResponse.pageResult.requestCharge()); - Observable x = Observable.from(results); + Flux x = Flux.fromIterable(results); return x.map(r -> new OrderByRowResult( klass, diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java index 62fc3f463b1bd..f55fe964f4b34 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java @@ -30,11 +30,10 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Observer; -import rx.functions.Func1; -import rx.functions.Func2; -import rx.observables.AsyncOnSubscribe; +import reactor.core.publisher.Flux; + +import java.util.function.BiFunction; +import java.util.function.Function; /** * While this class is public, but it is not part of our published public APIs. @@ -44,62 +43,53 @@ public class Paginator { private final static Logger logger = LoggerFactory.getLogger(Paginator.class); - public static Observable> getPaginatedChangeFeedQueryResultAsObservable( - ChangeFeedOptions feedOptions, Func2 createRequestFunc, - Func1>> executeFunc, Class resourceType, + public static Flux> getPaginatedChangeFeedQueryResultAsObservable( + ChangeFeedOptions feedOptions, BiFunction createRequestFunc, + Function>> executeFunc, Class resourceType, int maxPageSize) { return getPaginatedQueryResultAsObservable(feedOptions, createRequestFunc, executeFunc, resourceType, -1, maxPageSize, true); } - public static Observable> getPaginatedQueryResultAsObservable( + public static Flux> getPaginatedQueryResultAsObservable( FeedOptions feedOptions, - Func2 createRequestFunc, - Func1>> executeFunc, Class resourceType, + BiFunction createRequestFunc, + Function>> executeFunc, Class resourceType, int maxPageSize) { return getPaginatedQueryResultAsObservable(feedOptions, createRequestFunc, executeFunc, resourceType, -1, maxPageSize); } - public static Observable> getPaginatedQueryResultAsObservable( + public static Flux> getPaginatedQueryResultAsObservable( FeedOptions options, - Func2 createRequestFunc, - Func1>> executeFunc, Class resourceType, + BiFunction createRequestFunc, + Function>> executeFunc, Class resourceType, int top, int maxPageSize) { return getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, resourceType, top, maxPageSize, false); } - private static Observable> getPaginatedQueryResultAsObservable( + private static Flux> getPaginatedQueryResultAsObservable( FeedOptionsBase options, - Func2 createRequestFunc, - Func1>> executeFunc, Class resourceType, + BiFunction createRequestFunc, + Function>> executeFunc, Class resourceType, int top, int maxPageSize, boolean isChangeFeed) { - Observable> obs = Observable.defer(() -> { - return Observable.create(new AsyncOnSubscribe>() { - @Override - protected Fetcher generateState() { - return new Fetcher(createRequestFunc, executeFunc, options, isChangeFeed, top, maxPageSize); - } - - @Override - protected Fetcher next(Fetcher fetcher, long requested, Observer>> observer) { - assert requested == 1 : "requested amount expected to be 1"; // as there is a rebatchRequests(1) + return Flux.defer(() -> { + Flux>> generate = Flux.generate(() -> + new Fetcher<>(createRequestFunc, executeFunc, options, isChangeFeed, top, maxPageSize), + (tFetcher, sink) -> { + if (tFetcher.shouldFetchMore()) { + Flux> nextPage = tFetcher.nextPage(); + sink.next(nextPage); + } else { + logger.debug("No more results"); + sink.complete(); + } + return tFetcher; + }); - if (fetcher.shouldFetchMore()) { - Observable> respObs = fetcher.nextPage(); - observer.onNext(respObs); - } else { - logger.debug("No more results"); - observer.onCompleted(); - } - - return fetcher; - } - }).rebatchRequests(1); + return generate.flatMapSequential(feedResponseFlux -> feedResponseFlux, 1); }); - - return obs; } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java index faf83eac6c9bd..4fb2d50ad2591 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java @@ -37,19 +37,17 @@ import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.Utils.ValueHolder; import org.apache.commons.lang3.tuple.ImmutablePair; -import rx.Observable; -import rx.Observable.Transformer; -import rx.functions.Func0; -import rx.functions.Func1; -import rx.functions.Func3; +import reactor.core.publisher.Flux; import java.util.ArrayList; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.function.Function; import java.util.stream.Collectors; - /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. @@ -74,7 +72,7 @@ private ParallelDocumentQueryExecutionContext( rewrittenQuery, isContinuationExpected, getLazyFeedResponse, correlatedActivityId); } - public static Observable> createAsync( + public static Flux> createAsync( IDocumentQueryClient client, ResourceType resourceTypeEnum, Class resourceType, @@ -107,9 +105,9 @@ public static Observable getPartitionKeyRangesForContinuation( } private static class EmptyPagesFilterTransformer - implements Transformer.DocumentProducerFeedResponse, FeedResponse> { + implements Function.DocumentProducerFeedResponse>, Flux>> { private final RequestChargeTracker tracker; private DocumentProducer.DocumentProducerFeedResponse previousPage; @@ -240,8 +238,9 @@ private static Map headerResponse( } @Override - public Observable> call( - Observable.DocumentProducerFeedResponse> source) { + public Flux> apply(Flux.DocumentProducerFeedResponse> source) { + // Emit an empty page so the downstream observables know when there are no more + // results. return source.filter(documentProducerFeedResponse -> { if (documentProducerFeedResponse.pageResult.results().isEmpty()) { // filter empty pages and accumulate charge @@ -253,23 +252,20 @@ public Observable> call( // Add the request charge double charge = tracker.getAndResetCharge(); if (charge > 0) { - return plusCharge(documentProducerFeedResponse, - charge); + return new ValueHolder<>(plusCharge(documentProducerFeedResponse, + charge)); } else { - return documentProducerFeedResponse; + return new ValueHolder<>(documentProducerFeedResponse); } - }).concatWith(Observable.defer(() -> { - // Emit an empty page so the downstream observables know when there are no more - // results. - return Observable.just(null); - })).map(documentProducerFeedResponse -> { + }).concatWith(Flux.just(new ValueHolder<>(null))).map(heldValue -> { + DocumentProducer.DocumentProducerFeedResponse documentProducerFeedResponse = heldValue.v; // CREATE pairs from the stream to allow the observables downstream to "peek" // 1, 2, 3, null -> (null, 1), (1, 2), (2, 3), (3, null) - ImmutablePair.DocumentProducerFeedResponse, DocumentProducer.DocumentProducerFeedResponse> previousCurrent = new ImmutablePair.DocumentProducerFeedResponse, DocumentProducer.DocumentProducerFeedResponse>( + ImmutablePair.DocumentProducerFeedResponse, DocumentProducer.DocumentProducerFeedResponse> previousCurrent = new ImmutablePair<>( this.previousPage, documentProducerFeedResponse); - this.previousPage = documentProducerFeedResponse; - return previousCurrent; + this.previousPage = documentProducerFeedResponse; + return previousCurrent; }).skip(1).map(currentNext -> { // remove the (null, 1) // Add the continuation token based on the current and next page. @@ -308,33 +304,31 @@ public Observable> call( }).map(documentProducerFeedResponse -> { // Unwrap the documentProducerFeedResponse and get back the feedResponse return documentProducerFeedResponse.pageResult; - }).switchIfEmpty(Observable.defer(() -> { + }).switchIfEmpty(Flux.defer(() -> { // create an empty page if there is no result - return Observable.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(), + return Flux.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(), headerResponse(tracker.getAndResetCharge()))); })); } } @Override - public Observable> drainAsync( + public Flux> drainAsync( int maxPageSize) { - List.DocumentProducerFeedResponse>> obs = this.documentProducers + List.DocumentProducerFeedResponse>> obs = this.documentProducers // Get the stream. .stream() // Start from the left most partition first. - .sorted(( - dp1, - dp2) -> dp1.targetRange.getMinInclusive().compareTo(dp2.targetRange.getMinInclusive())) + .sorted(Comparator.comparing(dp -> dp.targetRange.getMinInclusive())) // For each partition get it's stream of results. - .map(dp -> dp.produceAsync()) + .map(DocumentProducer::produceAsync) // Merge results from all partitions. .collect(Collectors.toList()); - return Observable.concat(obs).compose(new EmptyPagesFilterTransformer<>(new RequestChargeTracker())); + return Flux.concat(obs).compose(new EmptyPagesFilterTransformer<>(new RequestChargeTracker())); } @Override - public Observable> executeAsync() { + public Flux> executeAsync() { return this.drainAsync(feedOptions.maxItemCount()); } @@ -346,9 +340,9 @@ protected DocumentProducer createDocumentProducer( FeedOptions feedOptions, SqlQuerySpec querySpecForInit, Map commonRequestHeaders, - Func3 createRequestFunc, - Func1>> executeFunc, - Func0 createRetryPolicyFunc) { + TriFunction createRequestFunc, + Function>> executeFunc, + Callable createRetryPolicyFunc) { return new DocumentProducer(client, collectionRid, feedOptions, diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java index be0fdd8a3971b..53b78d6f0ec00 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java @@ -34,16 +34,15 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.internal.routing.Range; -import rx.Observable; -import rx.functions.Func0; -import rx.functions.Func1; -import rx.functions.Func3; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.function.Function; /** * While this class is public, but it is not part of our published public APIs. @@ -83,7 +82,7 @@ protected void initialize(String collectionRid, Map commonRequestHeaders = createCommonHeadersAsync(this.getFeedOptions(null, null)); for (PartitionKeyRange targetRange : partitionKeyRangeToContinuationTokenMap.keySet()) { - Func3 createRequestFunc = (partitionKeyRange, + TriFunction createRequestFunc = (partitionKeyRange, continuationToken, pageSize) -> { Map headers = new HashMap<>(commonRequestHeaders); headers.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); @@ -91,8 +90,8 @@ protected void initialize(String collectionRid, return this.createDocumentServiceRequest(headers, querySpecForInit, partitionKeyRange, collectionRid); }; - Func1>> executeFunc = (request) -> { - return this.executeRequestAsync(request).toObservable(); + Function>> executeFunc = (request) -> { + return this.executeRequestAsync(request).flux(); }; DocumentProducer dp = createDocumentProducer(collectionRid, targetRange, @@ -140,12 +139,12 @@ protected int FindTargetRangeAndExtractContinuationTokens( abstract protected DocumentProducer createDocumentProducer(String collectionRid, PartitionKeyRange targetRange, String initialContinuationToken, int initialPageSize, FeedOptions feedOptions, SqlQuerySpec querySpecForInit, Map commonRequestHeaders, - Func3 createRequestFunc, - Func1>> executeFunc, - Func0 createRetryPolicyFunc); + TriFunction createRequestFunc, + Function>> executeFunc, + Callable createRetryPolicyFunc); @Override - abstract public Observable> drainAsync(int maxPageSize); + abstract public Flux> drainAsync(int maxPageSize); public void setTop(int newTop) { this.top = newTop; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java index 61d0fd68cc4c8..903423d06dfa6 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.Utils; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.List; import java.util.UUID; @@ -61,14 +61,14 @@ private PipelinedDocumentQueryExecutionContext(IDocumentQueryExecutionComponent< // this.actualPageSize)); } - public static Observable> createAsync( + public static Flux> createAsync( IDocumentQueryClient client, ResourceType resourceTypeEnum, Class resourceType, SqlQuerySpec expression, FeedOptions feedOptions, String resourceLink, String collectionRid, PartitionedQueryExecutionInfo partitionedQueryExecutionInfo, List targetRanges, int initialPageSize, boolean isContinuationExpected, boolean getLazyFeedResponse, UUID correlatedActivityId) { // Use nested callback pattern to unwrap the continuation token at each level. - Function>> createBaseComponentFunction; + Function>> createBaseComponentFunction; QueryInfo queryInfo = partitionedQueryExecutionInfo.getQueryInfo(); @@ -92,7 +92,7 @@ public static Observable>> createAggregateComponentFunction; + Function>> createAggregateComponentFunction; if (queryInfo.hasAggregates()) { createAggregateComponentFunction = (continuationToken) -> { return AggregateDocumentQueryExecutionContext.createAsync(createBaseComponentFunction, @@ -102,7 +102,7 @@ public static Observable>> createTopComponentFunction; + Function>> createTopComponentFunction; if (queryInfo.hasTop()) { createTopComponentFunction = (continuationToken) -> { return TopDocumentQueryExecutionContext.createAsync(createAggregateComponentFunction, @@ -125,7 +125,7 @@ public static Observable> executeAsync() { + public Flux> executeAsync() { // TODO Auto-generated method stub // TODO add more code here diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java index dc8879b669cfc..b93e83a8bfea8 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java @@ -35,13 +35,13 @@ import com.azure.data.cosmos.internal.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; -import rx.functions.Func1; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.lang.invoke.MethodHandles; import java.util.List; import java.util.UUID; +import java.util.function.Function; /** * While this class is public, but it is not part of our published public APIs. @@ -92,20 +92,20 @@ public ProxyDocumentQueryExecutionContext( } @Override - public Observable> executeAsync() { + public Flux> executeAsync() { - Func1>> func = t -> { + Function>> func = t -> { logger.debug("Received non result message from gateway", t); if (!(t instanceof Exception)) { logger.error("Unexpected failure", t); - return Observable.error(t); + return Flux.error(t); } if (!isCrossPartitionQuery((Exception) t)) { // If this is not a cross partition query then propagate error logger.debug("Failure from gateway", t); - return Observable.error(t); + return Flux.error(t); } logger.debug("Setting up query pipeline using the query plan received form gateway"); @@ -122,29 +122,27 @@ public Observable> executeAsync() { DefaultDocumentQueryExecutionContext queryExecutionContext = (DefaultDocumentQueryExecutionContext) this.innerExecutionContext; - Single> partitionKeyRanges = queryExecutionContext.getTargetPartitionKeyRanges(collection.resourceId(), + Mono> partitionKeyRanges = queryExecutionContext.getTargetPartitionKeyRanges(collection.resourceId(), partitionedQueryExecutionInfo.getQueryRanges()); - Observable> exContext = partitionKeyRanges.toObservable() - .flatMap(pkranges -> { - return DocumentQueryExecutionContextFactory.createSpecializedDocumentQueryExecutionContextAsync( - this.client, - this.resourceTypeEnum, - this.resourceType, - this.query, - this.feedOptions, - this.resourceLink, - isContinuationExpected, - partitionedQueryExecutionInfo, - pkranges, - this.collection.resourceId(), - this.correlatedActivityId); - }); - - return exContext.flatMap(context -> context.executeAsync()); + Flux> exContext = partitionKeyRanges.flux() + .flatMap(pkranges -> DocumentQueryExecutionContextFactory.createSpecializedDocumentQueryExecutionContextAsync( + this.client, + this.resourceTypeEnum, + this.resourceType, + this.query, + this.feedOptions, + this.resourceLink, + isContinuationExpected, + partitionedQueryExecutionInfo, + pkranges, + this.collection.resourceId(), + this.correlatedActivityId)); + + return exContext.flatMap(IDocumentQueryExecutionContext::executeAsync); }; - return this.innerExecutionContext.executeAsync().onErrorResumeNext(func); + return this.innerExecutionContext.executeAsync().onErrorResume(func); } private boolean isCrossPartitionQuery(Exception exception) { @@ -159,10 +157,10 @@ private boolean isCrossPartitionQuery(Exception exception) { Exceptions.isSubStatusCode(clientException, HttpConstants.SubStatusCodes.CROSS_PARTITION_QUERY_NOT_SERVABLE)); } - public static Observable> createAsync(IDocumentQueryClient client, - ResourceType resourceTypeEnum, Class resourceType, SqlQuerySpec query, FeedOptions feedOptions, - String resourceLink, DocumentCollection collection, boolean isContinuationExpected, - UUID correlatedActivityId) { + public static Flux> createAsync(IDocumentQueryClient client, + ResourceType resourceTypeEnum, Class resourceType, SqlQuerySpec query, FeedOptions feedOptions, + String resourceLink, DocumentCollection collection, boolean isContinuationExpected, + UUID correlatedActivityId) { IDocumentQueryExecutionContext innerExecutionContext = new DefaultDocumentQueryExecutionContext( @@ -175,7 +173,7 @@ public static Observable(innerExecutionContext, client, + return Flux.just(new ProxyDocumentQueryExecutionContext(innerExecutionContext, client, resourceTypeEnum, resourceType, query, diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java index e04b0e052b7df..8ec81cbf7063b 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java @@ -29,12 +29,12 @@ import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Utils.ValueHolder; -import rx.Observable; -import rx.functions.Func1; +import reactor.core.publisher.Flux; import java.util.HashMap; import java.util.Map; import java.util.function.Function; +import java.util.function.Predicate; public class TopDocumentQueryExecutionContext implements IDocumentQueryExecutionComponent { @@ -46,8 +46,8 @@ public TopDocumentQueryExecutionContext(IDocumentQueryExecutionComponent comp this.top = top; } - public static Observable> createAsync( - Function>> createSourceComponentFunction, + public static Flux> createAsync( + Function>> createSourceComponentFunction, int topCount, String topContinuationToken) { TakeContinuationToken takeContinuationToken; @@ -60,7 +60,7 @@ public static Observable Observable { - return new TopDocumentQueryExecutionContext(component, takeContinuationToken.getTakeCount()); - }); + return createSourceComponentFunction + .apply(takeContinuationToken.getSourceToken()) + .map(component -> new TopDocumentQueryExecutionContext<>(component, takeContinuationToken.getTakeCount())); } @Override - public Observable> drainAsync(int maxPageSize) { + public Flux> drainAsync(int maxPageSize) { ParallelDocumentQueryExecutionContextBase context; if (this.component instanceof AggregateDocumentQueryExecutionContext) { @@ -92,25 +92,25 @@ public Observable> drainAsync(int maxPageSize) { context.setTop(this.top); - return this.component.drainAsync(maxPageSize).takeUntil(new Func1, Boolean>() { + return this.component.drainAsync(maxPageSize).takeUntil(new Predicate>() { private volatile int fetchedItems = 0; @Override - public Boolean call(FeedResponse frp) { + public boolean test(FeedResponse frp) { fetchedItems += frp.results().size(); // take until we have at least top many elements fetched return fetchedItems >= top; } - }).map(new Func1, FeedResponse>() { + }).map(new Function, FeedResponse>() { private volatile int collectedItems = 0; private volatile boolean lastPage = false; @Override - public FeedResponse call(FeedResponse t) { + public FeedResponse apply(FeedResponse t) { if (collectedItems + t.results().size() <= top) { collectedItems += t.results().size(); diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java new file mode 100644 index 0000000000000..fc4772ad8e940 --- /dev/null +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java @@ -0,0 +1,23 @@ +package com.azure.data.cosmos.internal.query; + +/** + * A functional interface (callback) that computes a value based on multiple input values. + * @param the first value type + * @param the second value type + * @param the third value type + * @param the result type + */ + +@FunctionalInterface +public interface TriFunction { + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @param v the third function argument + * @return the function result + */ + R apply(T t, U u, V v); +} \ No newline at end of file diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java index a61aee098509c..c205d04529834 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java @@ -58,8 +58,7 @@ public int compare(OrderByRowResult r1, OrderByRowResult r2) { } if (result1.size() != this.sortOrders.size()) { - throw new IllegalStateException( - String.format("OrderByItems cannot have a different size than sort orders.")); + throw new IllegalStateException("OrderByItems cannot have a different size than sort orders."); } if (this.itemTypes == null) { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java index b5ad73c4a1453..aaa00bd9d3ddb 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java @@ -39,9 +39,9 @@ public interface CollectionRoutingMap { PartitionKeyRange getRangeByPartitionKeyRangeId(String partitionKeyRangeId); - Collection getOverlappingRanges(Range range); + List getOverlappingRanges(Range range); - Collection getOverlappingRanges(Collection> providedPartitionKeyRanges); + List getOverlappingRanges(Collection> providedPartitionKeyRanges); PartitionKeyRange tryGetRangeByPartitionKeyRangeId(String partitionKeyRangeId); diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java index b15f5fd96c1e2..e04dae05d6e3f 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java @@ -156,12 +156,12 @@ public PartitionKeyRange getRangeByPartitionKeyRangeId(String partitionKeyRangeI @Override - public Collection getOverlappingRanges(Range range) { + public List getOverlappingRanges(Range range) { return this.getOverlappingRanges(Collections.singletonList(range)); } @Override - public Collection getOverlappingRanges(Collection> providedPartitionKeyRanges) { + public List getOverlappingRanges(Collection> providedPartitionKeyRanges) { if (providedPartitionKeyRanges == null) { throw new IllegalArgumentException("providedPartitionKeyRanges"); } @@ -187,7 +187,7 @@ public Collection getOverlappingRanges(Collection(partitionRanges.values()); } diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java index e5e91d9611539..fbbf29a9389e8 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java @@ -25,11 +25,10 @@ import com.azure.data.cosmos.RetryOptions; import io.netty.handler.timeout.ReadTimeoutException; +import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; import org.testng.annotations.Test; -import rx.Completable; -import rx.Single; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Mono; import java.net.URL; import java.time.Duration; @@ -43,7 +42,7 @@ public void networkFailureOnRead() throws Exception { RetryOptions retryOptions = new RetryOptions(); GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URL("http://localhost")).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); - Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); + Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(endpointManager, true, retryOptions); Exception exception = ReadTimeoutException.INSTANCE; @@ -55,7 +54,7 @@ public void networkFailureOnRead() throws Exception { clientRetryPolicy.onBeforeSendRequest(dsr); for (int i = 0; i < 10; i++) { - Single shouldRetry = clientRetryPolicy.shouldRetry(exception); + Mono shouldRetry = clientRetryPolicy.shouldRetry(exception); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() @@ -73,7 +72,7 @@ public void networkFailureOnWrite() throws Exception { RetryOptions retryOptions = new RetryOptions(); GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URL("http://localhost")).when(endpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); - Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); + Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(endpointManager, true, retryOptions); Exception exception = ReadTimeoutException.INSTANCE; @@ -84,7 +83,7 @@ public void networkFailureOnWrite() throws Exception { clientRetryPolicy.onBeforeSendRequest(dsr); for (int i = 0; i < 10; i++) { - Single shouldRetry = clientRetryPolicy.shouldRetry(exception); + Mono shouldRetry = clientRetryPolicy.shouldRetry(exception); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .nullException() .shouldRetry(true) @@ -101,7 +100,7 @@ public void onBeforeSendRequestNotInvoked() { RetryOptions retryOptions = new RetryOptions(); GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); + Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(endpointManager, true, retryOptions); Exception exception = ReadTimeoutException.INSTANCE; @@ -110,7 +109,7 @@ public void onBeforeSendRequestNotInvoked() { OperationType.Create, "/dbs/db/colls/col/docs/docId", ResourceType.Document); dsr.requestContext = Mockito.mock(DocumentServiceRequestContext.class); - Single shouldRetry = clientRetryPolicy.shouldRetry(exception); + Mono shouldRetry = clientRetryPolicy.shouldRetry(exception); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .withException(exception) .shouldRetry(false) @@ -119,22 +118,22 @@ public void onBeforeSendRequestNotInvoked() { Mockito.verifyZeroInteractions(endpointManager); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, ShouldRetryValidator validator) { validateSuccess(single, validator, TIMEOUT); } - public static void validateSuccess(Single single, + public static void validateSuccess(Mono single, ShouldRetryValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - single.toObservable().subscribe(testSubscriber); + single.flux().subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertNoErrors(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } } diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java index d12ad50fc6257..8f6199c7db4de 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java @@ -30,8 +30,7 @@ import io.netty.handler.timeout.ReadTimeoutException; import org.mockito.Mockito; import org.testng.annotations.Test; -import rx.Completable; -import rx.Single; +import reactor.core.publisher.Mono; import static com.azure.data.cosmos.internal.ClientRetryPolicyTest.validateSuccess; import static org.assertj.core.api.Assertions.assertThat; @@ -43,7 +42,7 @@ public class RenameCollectionAwareClientRetryPolicyTest { @Test(groups = "unit", timeOut = TIMEOUT) public void onBeforeSendRequestNotInvoked() { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); + Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.defaultPolicy()); RxClientCollectionCache rxClientCollectionCache = Mockito.mock(RxClientCollectionCache.class); @@ -59,7 +58,8 @@ public void onBeforeSendRequestNotInvoked() { OperationType.Create, "/dbs/db/colls/col/docs/docId", ResourceType.Document); dsr.requestContext = Mockito.mock(DocumentServiceRequestContext.class); - Single shouldRetry = renameCollectionAwareClientRetryPolicy.shouldRetry(exception); + Mono shouldRetry = + renameCollectionAwareClientRetryPolicy.shouldRetry(exception); validateSuccess(shouldRetry, ShouldRetryValidator.builder() .withException(exception) .shouldRetry(false) @@ -71,7 +71,7 @@ public void onBeforeSendRequestNotInvoked() { @Test(groups = "unit", timeOut = TIMEOUT) public void shouldRetryWithNotFoundStatusCode() { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); + Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.defaultPolicy()); RxClientCollectionCache rxClientCollectionCache = Mockito.mock(RxClientCollectionCache.class); @@ -86,7 +86,7 @@ public void shouldRetryWithNotFoundStatusCode() { NotFoundException notFoundException = new NotFoundException(); - Single singleShouldRetry = renameCollectionAwareClientRetryPolicy + Mono singleShouldRetry = renameCollectionAwareClientRetryPolicy .shouldRetry(notFoundException); validateSuccess(singleShouldRetry, ShouldRetryValidator.builder() .withException(notFoundException) @@ -97,7 +97,7 @@ public void shouldRetryWithNotFoundStatusCode() { @Test(groups = "unit", timeOut = TIMEOUT) public void shouldRetryWithNotFoundStatusCodeAndReadSessionNotAvailableSubStatusCode() { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); + Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.defaultPolicy()); RxClientCollectionCache rxClientCollectionCache = Mockito.mock(RxClientCollectionCache.class); @@ -118,9 +118,9 @@ public void shouldRetryWithNotFoundStatusCodeAndReadSessionNotAvailableSubStatus DocumentCollection documentCollection = new DocumentCollection(); documentCollection.resourceId("rid_1"); - Mockito.when(rxClientCollectionCache.resolveCollectionAsync(request)).thenReturn(Single.just(documentCollection)); + Mockito.when(rxClientCollectionCache.resolveCollectionAsync(request)).thenReturn(Mono.just(documentCollection)); - Single singleShouldRetry = renameCollectionAwareClientRetryPolicy + Mono singleShouldRetry = renameCollectionAwareClientRetryPolicy .shouldRetry(notFoundException); validateSuccess(singleShouldRetry, ShouldRetryValidator.builder() .nullException() @@ -134,7 +134,7 @@ public void shouldRetryWithNotFoundStatusCodeAndReadSessionNotAvailableSubStatus @Test(groups = "unit", timeOut = TIMEOUT) public void shouldRetryWithGenericException() { GlobalEndpointManager endpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(Completable.complete()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); + Mockito.doReturn(Mono.empty()).when(endpointManager).refreshLocationAsync(Mockito.eq(null)); IRetryPolicyFactory retryPolicyFactory = new RetryPolicy(endpointManager, ConnectionPolicy.defaultPolicy()); RxClientCollectionCache rxClientCollectionCache = Mockito.mock(RxClientCollectionCache.class); @@ -147,9 +147,9 @@ public void shouldRetryWithGenericException() { request.requestContext = Mockito.mock(DocumentServiceRequestContext.class); renameCollectionAwareClientRetryPolicy.onBeforeSendRequest(request); - Single singleShouldRetry = renameCollectionAwareClientRetryPolicy + Mono singleShouldRetry = renameCollectionAwareClientRetryPolicy .shouldRetry(new BadRequestException()); - IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.toBlocking().value(); + IRetryPolicy.ShouldRetryResult shouldRetryResult = singleShouldRetry.block(); assertThat(shouldRetryResult.shouldRetry).isFalse(); } } diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java index 72fd41fe534da..1d09d160ad126 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java @@ -26,22 +26,23 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpRequest; import com.azure.data.cosmos.rx.FailureValidator; -import io.netty.buffer.ByteBuf; import io.netty.handler.timeout.ReadTimeoutException; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; +import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; import org.testng.annotations.Test; -import rx.Observable; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.net.URL; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; +; + public class RxGatewayStoreModelTest { private final static int TIMEOUT = 10000; @@ -53,9 +54,9 @@ public void readTimeout() throws Exception { GlobalEndpointManager globalEndpointManager = Mockito.mock(GlobalEndpointManager.class); Mockito.doReturn(new URL("https://localhost")) .when(globalEndpointManager).resolveServiceEndpoint(Mockito.any()); - CompositeHttpClient httpClient = Mockito.mock(CompositeHttpClient.class); - Mockito.doReturn(Observable.error(ReadTimeoutException.INSTANCE)) - .when(httpClient).submit(Mockito.any(RxClient.ServerInfo.class), Mockito.any(HttpClientRequest.class)); + HttpClient httpClient = Mockito.mock(HttpClient.class); + Mockito.doReturn(Mono.error(ReadTimeoutException.INSTANCE)) + .when(httpClient).send(Mockito.any(HttpRequest.class)); RxGatewayStoreModel storeModel = new RxGatewayStoreModel( sessionContainer, @@ -70,7 +71,7 @@ public void readTimeout() throws Exception { dsr.getHeaders().put("key", "value"); dsr.requestContext = Mockito.mock(DocumentServiceRequestContext.class); - Observable resp = storeModel.processMessage(dsr); + Flux resp = storeModel.processMessage(dsr); validateFailure(resp, FailureValidator.builder() .instanceOf(CosmosClientException.class) .causeInstanceOf(ReadTimeoutException.class) @@ -78,21 +79,20 @@ public void readTimeout() throws Exception { .statusCode(0).build()); } - public void validateFailure(Observable observable, + public void validateFailure(Flux observable, FailureValidator validator) { validateFailure(observable, validator, TIMEOUT); } - public static void validateFailure(Observable observable, + public static void validateFailure(Flux observable, FailureValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); - observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + assertThat(testSubscriber.errorCount()).isEqualTo(1); + validator.validate(testSubscriber.errors().get(0)); } } diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java index 86795d1ca6f34..1df2b6547073c 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java @@ -23,13 +23,13 @@ package com.azure.data.cosmos.internal.caches; import org.testng.annotations.Test; -import rx.Observable; -import rx.Single; -import rx.functions.Func1; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; @@ -41,49 +41,49 @@ public class AsyncCacheTest { @Test(groups = { "unit" }, timeOut = TIMEOUT) public void getAsync() { AtomicInteger numberOfCacheRefreshes = new AtomicInteger(0); - final Func1> refreshFunc = key -> { + final Function> refreshFunc = key -> { numberOfCacheRefreshes.incrementAndGet(); - return Single.just(key*2); + return Mono.just(key*2); }; AsyncCache cache = new AsyncCache<>(); - List> tasks = new ArrayList<>(); + List> tasks = new ArrayList<>(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { int key = j; - tasks.add(cache.getAsync(key, -1, () -> refreshFunc.call(key))); + tasks.add(cache.getAsync(key, -1, () -> refreshFunc.apply(key))); } } - Observable o = Observable.merge(tasks.stream().map(s -> s.toObservable()).collect(Collectors.toList())); - o.toList().toSingle().toBlocking().value(); + Flux o = Flux.merge(tasks.stream().map(Mono::flux).collect(Collectors.toList())); + o.collectList().single().block(); assertThat(numberOfCacheRefreshes.get()).isEqualTo(10); - assertThat(cache.getAsync(2, -1, () -> refreshFunc.call(2)).toBlocking().value()).isEqualTo(4); + assertThat(cache.getAsync(2, -1, () -> refreshFunc.apply(2)).block()).isEqualTo(4); - Func1> refreshFunc1 = key -> { + Function> refreshFunc1 = key -> { numberOfCacheRefreshes.incrementAndGet(); - return Single.just(key * 2 + 1); + return Mono.just(key * 2 + 1); }; - List> tasks1 = new ArrayList<>(); + List> tasks1 = new ArrayList<>(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { int key = j; - tasks1.add(cache.getAsync(key, key * 2, () -> refreshFunc1.call(key))); + tasks1.add(cache.getAsync(key, key * 2, () -> refreshFunc1.apply(key))); } for (int j = 0; j < 10; j++) { int key = j; - tasks1.add(cache.getAsync(key, key * 2 , () -> refreshFunc1.call(key))); + tasks1.add(cache.getAsync(key, key * 2 , () -> refreshFunc1.apply(key))); } } - Observable o1 = Observable.merge(tasks1.stream().map(s -> s.toObservable()).collect(Collectors.toList())); - o1.toList().toSingle().toBlocking().value(); + Flux o1 = Flux.merge(tasks1.stream().map(Mono::flux).collect(Collectors.toList())); + o1.collectList().single().block(); assertThat(numberOfCacheRefreshes.get()).isEqualTo(20); - assertThat(cache.getAsync(2, -1, () -> refreshFunc.call(2)).toBlocking().value()).isEqualTo(5); + assertThat(cache.getAsync(2, -1, () -> refreshFunc.apply(2)).block()).isEqualTo(5); } } diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java index 62cc7ce65bfbf..2d952d8f41adc 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java @@ -40,8 +40,8 @@ import org.apache.commons.collections4.list.UnmodifiableList; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Completable; -import rx.Observable; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.net.MalformedURLException; import java.net.URI; @@ -186,8 +186,8 @@ private int getInvocationCounter() { } @Override - public Observable getDatabaseAccountFromEndpoint(URI endpoint) { - return Observable.just(LocationCacheTest.this.databaseAccount); + public Flux getDatabaseAccountFromEndpoint(URI endpoint) { + return Flux.just(LocationCacheTest.this.databaseAccount); } @Override @@ -329,11 +329,11 @@ private boolean areEqual(URL url1, URL url2) { private void validateGlobalEndpointLocationCacheRefreshAsync() throws Exception { mockedClient.reset(); - List list = IntStream.range(0, 10) + List> list = IntStream.range(0, 10) .mapToObj(index -> this.endpointManager.refreshLocationAsync(null)) .collect(Collectors.toList()); - Completable.merge(list).await(); + Flux.merge(list).then().block(); assertThat(mockedClient.getInvocationCounter()).isLessThanOrEqualTo(1); mockedClient.reset(); @@ -341,8 +341,8 @@ private void validateGlobalEndpointLocationCacheRefreshAsync() throws Exception IntStream.range(0, 10) .mapToObj(index -> this.endpointManager.refreshLocationAsync(null)) .collect(Collectors.toList()); - for (Completable completable : list) { - completable.await(); + for (Mono completable : list) { + completable.block(); } assertThat(mockedClient.getInvocationCounter()).isLessThanOrEqualTo(1); diff --git a/pom.xml b/pom.xml index 24fbe695a5028..e40ab2618c189 100644 --- a/pom.xml +++ b/pom.xml @@ -57,19 +57,13 @@ 3.1.4 1.58 1.2.17 - 3.2.6 + 4.0.5 1.10.19 4.1.36.Final 2.0.25.Final 3.2.2.RELEASE - Bismuth-RELEASE - 0.8.0.17 - 1.0.3 - 1.1.1 - 1.3.8 + Californium-SR7 2.2.4 - 0.13.3 - 0.4.20 3.0.0-a1-SNAPSHOT 1.7.6 unit diff --git a/sdk/CosmosConflict b/sdk/CosmosConflict new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/sdk/pom.xml b/sdk/pom.xml index 47f5d22f5863e..015c95248568c 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -191,36 +191,10 @@ SOFTWARE. commons-io ${commons-io.version} - - com.github.davidmoten - rxjava-extras - ${rxjava-extras.version} - - - io.reactivex - rxjava - ${rxjava.version} - - - io.reactivex - rxjava-string - ${rxjava-string.version} - io.projectreactor reactor-core - - io.reactivex - rxnetty - ${rxnetty.version} - - - io.netty - netty-transport-native-epoll - - - io.netty netty-codec-http @@ -276,22 +250,11 @@ SOFTWARE. ${guava.version} test - - io.projectreactor.addons - reactor-adapter - ${reactor-addons.version} - test - io.projectreactor reactor-test test - - com.github.akarnokd - rxjava2-interop - ${rxjava2interop.verison} - io.reactivex.rxjava2 rxjava diff --git a/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java b/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java index d0190ad050548..85e32e16ef669 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java @@ -24,21 +24,20 @@ import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.RxDocumentClientImpl; -import rx.Observable; +import reactor.core.publisher.Flux; import java.net.URI; import java.net.URISyntaxException; import java.util.List; - /** * Provides a client-side logical representation of the Azure Cosmos DB * database service. This async client is used to configure and execute requests * against the service. * *

- * {@link AsyncDocumentClient} async APIs return rxJava's {@code - * Observable}, and so you can use rxJava {@link Observable} functionality. - * The async {@link Observable} based APIs perform the requested operation only after + * {@link AsyncDocumentClient} async APIs return project reactor's {@link + * Flux}, and so you can use project reactor {@link Flux} functionality. + * The async {@link Flux} based APIs perform the requested operation only after * subscription. * *

@@ -292,1040 +291,1040 @@ public void setTokenResolver(TokenResolver tokenResolver) { * Creates a database. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the created database. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the created database. + * In case of failure the {@link Flux} will error. * * @param database the database. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the created database or an error. + * @return an {@link Flux} containing the single resource response with the created database or an error. */ - Observable> createDatabase(Database database, RequestOptions options); + Flux> createDatabase(Database database, RequestOptions options); /** * Deletes a database. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the deleted database. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the deleted database. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the deleted database or an error. + * @return an {@link Flux} containing the single resource response with the deleted database or an error. */ - Observable> deleteDatabase(String databaseLink, RequestOptions options); + Flux> deleteDatabase(String databaseLink, RequestOptions options); /** * Reads a database. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the read database. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the read database. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the read database or an error. + * @return an {@link Flux} containing the single resource response with the read database or an error. */ - Observable> readDatabase(String databaseLink, RequestOptions options); + Flux> readDatabase(String databaseLink, RequestOptions options); /** * Reads all databases. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response of the read databases. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response of the read databases. + * In case of failure the {@link Flux} will error. * * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of read databases or an error. + * @return an {@link Flux} containing one or several feed response pages of read databases or an error. */ - Observable> readDatabases(FeedOptions options); + Flux> readDatabases(FeedOptions options); /** * Query for databases. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response of the read databases. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response of the read databases. + * In case of failure the {@link Flux} will error. * * @param query the query. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of read databases or an error. + * @return an {@link Flux} containing one or several feed response pages of read databases or an error. */ - Observable> queryDatabases(String query, FeedOptions options); + Flux> queryDatabases(String query, FeedOptions options); /** * Query for databases. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response of the obtained databases. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response of the obtained databases. + * In case of failure the {@link Flux} will error. * * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained databases or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained databases or an error. */ - Observable> queryDatabases(SqlQuerySpec querySpec, FeedOptions options); + Flux> queryDatabases(SqlQuerySpec querySpec, FeedOptions options); /** * Creates a document collection. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the created collection. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the created collection. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param collection the collection. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the created collection or an error. + * @return an {@link Flux} containing the single resource response with the created collection or an error. */ - Observable> createCollection(String databaseLink, DocumentCollection collection, + Flux> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options); /** * Replaces a document collection. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the replaced document collection. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the replaced document collection. + * In case of failure the {@link Flux} will error. * * @param collection the document collection to use. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the replaced document collection or an error. + * @return an {@link Flux} containing the single resource response with the replaced document collection or an error. */ - Observable> replaceCollection(DocumentCollection collection, RequestOptions options); + Flux> replaceCollection(DocumentCollection collection, RequestOptions options); /** * Deletes a document collection by the collection link. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the deleted database. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response for the deleted database. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param options the request options. - * @return an {@link Observable} containing the single resource response for the deleted database or an error. + * @return an {@link Flux} containing the single resource response for the deleted database or an error. */ - Observable> deleteCollection(String collectionLink, RequestOptions options); + Flux> deleteCollection(String collectionLink, RequestOptions options); /** * Reads a document collection by the collection link. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the read collection. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the read collection. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the read collection or an error. + * @return an {@link Flux} containing the single resource response with the read collection or an error. */ - Observable> readCollection(String collectionLink, RequestOptions options); + Flux> readCollection(String collectionLink, RequestOptions options); /** * Reads all document collections in a database. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response of the read collections. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response of the read collections. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param options the fee options. - * @return an {@link Observable} containing one or several feed response pages of the read collections or an error. + * @return an {@link Flux} containing one or several feed response pages of the read collections or an error. */ - Observable> readCollections(String databaseLink, FeedOptions options); + Flux> readCollections(String databaseLink, FeedOptions options); /** * Query for document collections in a database. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response of the obtained collections. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response of the obtained collections. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param query the query. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained collections or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained collections or an error. */ - Observable> queryCollections(String databaseLink, String query, FeedOptions options); + Flux> queryCollections(String databaseLink, String query, FeedOptions options); /** * Query for document collections in a database. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response of the obtained collections. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response of the obtained collections. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained collections or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained collections or an error. */ - Observable> queryCollections(String databaseLink, SqlQuerySpec querySpec, FeedOptions options); + Flux> queryCollections(String databaseLink, SqlQuerySpec querySpec, FeedOptions options); /** * Creates a document. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the created document. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the created document. + * In case of failure the {@link Flux} will error. * * @param collectionLink the link to the parent document collection. * @param document the document represented as a POJO or Document object. * @param options the request options. * @param disableAutomaticIdGeneration the flag for disabling automatic id generation. - * @return an {@link Observable} containing the single resource response with the created document or an error. + * @return an {@link Flux} containing the single resource response with the created document or an error. */ - Observable> createDocument(String collectionLink, Object document, RequestOptions options, + Flux> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration); /** * Upserts a document. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the upserted document. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the upserted document. + * In case of failure the {@link Flux} will error. * * @param collectionLink the link to the parent document collection. * @param document the document represented as a POJO or Document object to upsert. * @param options the request options. * @param disableAutomaticIdGeneration the flag for disabling automatic id generation. - * @return an {@link Observable} containing the single resource response with the upserted document or an error. + * @return an {@link Flux} containing the single resource response with the upserted document or an error. */ - Observable> upsertDocument(String collectionLink, Object document, RequestOptions options, + Flux> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration); /** * Replaces a document using a POJO object. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the replaced document. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the replaced document. + * In case of failure the {@link Flux} will error. * * @param documentLink the document link. * @param document the document represented as a POJO or Document object. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the replaced document or an error. + * @return an {@link Flux} containing the single resource response with the replaced document or an error. */ - Observable> replaceDocument(String documentLink, Object document, RequestOptions options); + Flux> replaceDocument(String documentLink, Object document, RequestOptions options); /** * Replaces a document with the passed in document. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the replaced document. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the replaced document. + * In case of failure the {@link Flux} will error. * * @param document the document to replace (containing the document id). * @param options the request options. - * @return an {@link Observable} containing the single resource response with the replaced document or an error. + * @return an {@link Flux} containing the single resource response with the replaced document or an error. */ - Observable> replaceDocument(Document document, RequestOptions options); + Flux> replaceDocument(Document document, RequestOptions options); /** * Deletes a document by the document link. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the deleted document. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response for the deleted document. + * In case of failure the {@link Flux} will error. * * @param documentLink the document link. * @param options the request options. - * @return an {@link Observable} containing the single resource response for the deleted document or an error. + * @return an {@link Flux} containing the single resource response for the deleted document or an error. */ - Observable> deleteDocument(String documentLink, RequestOptions options); + Flux> deleteDocument(String documentLink, RequestOptions options); /** * Reads a document by the document link. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the read document. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the read document. + * In case of failure the {@link Flux} will error. * * @param documentLink the document link. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the read document or an error. + * @return an {@link Flux} containing the single resource response with the read document or an error. */ - Observable> readDocument(String documentLink, RequestOptions options); + Flux> readDocument(String documentLink, RequestOptions options); /** * Reads all documents in a document collection. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response of the read documents. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response of the read documents. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the read documents or an error. + * @return an {@link Flux} containing one or several feed response pages of the read documents or an error. */ - Observable> readDocuments(String collectionLink, FeedOptions options); + Flux> readDocuments(String collectionLink, FeedOptions options); /** * Query for documents in a document collection. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response of the obtained documents. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response of the obtained documents. + * In case of failure the {@link Flux} will error. * * @param collectionLink the link to the parent document collection. * @param query the query. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained document or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained document or an error. */ - Observable> queryDocuments(String collectionLink, String query, FeedOptions options); + Flux> queryDocuments(String collectionLink, String query, FeedOptions options); /** * Query for documents in a document collection. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response of the obtained documents. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response of the obtained documents. + * In case of failure the {@link Flux} will error. * * @param collectionLink the link to the parent document collection. * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained documents or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained documents or an error. */ - Observable> queryDocuments(String collectionLink, SqlQuerySpec querySpec, FeedOptions options); + Flux> queryDocuments(String collectionLink, SqlQuerySpec querySpec, FeedOptions options); /** * Query for documents change feed in a document collection. * After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained documents. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained documents. + * In case of failure the {@link Flux} will error. * * @param collectionLink the link to the parent document collection. * @param changeFeedOptions the change feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained documents or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained documents or an error. */ - Observable> queryDocumentChangeFeed(String collectionLink, + Flux> queryDocumentChangeFeed(String collectionLink, ChangeFeedOptions changeFeedOptions); /** * Reads all partition key ranges in a document collection. * After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained partition key ranges. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained partition key ranges. + * In case of failure the {@link Flux} will error. * * @param collectionLink the link to the parent document collection. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained partition key ranges or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained partition key ranges or an error. */ - Observable> readPartitionKeyRanges(String collectionLink, FeedOptions options); + Flux> readPartitionKeyRanges(String collectionLink, FeedOptions options); /** * Creates a stored procedure. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the created stored procedure. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the created stored procedure. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param storedProcedure the stored procedure to create. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the created stored procedure or an error. + * @return an {@link Flux} containing the single resource response with the created stored procedure or an error. */ - Observable> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, + Flux> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options); /** * Upserts a stored procedure. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the upserted stored procedure. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the upserted stored procedure. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param storedProcedure the stored procedure to upsert. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the upserted stored procedure or an error. + * @return an {@link Flux} containing the single resource response with the upserted stored procedure or an error. */ - Observable> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, + Flux> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options); /** * Replaces a stored procedure. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the replaced stored procedure. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the replaced stored procedure. + * In case of failure the {@link Flux} will error. * * @param storedProcedure the stored procedure to use. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the replaced stored procedure or an error. + * @return an {@link Flux} containing the single resource response with the replaced stored procedure or an error. */ - Observable> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options); + Flux> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options); /** * Deletes a stored procedure by the stored procedure link. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the deleted stored procedure. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response for the deleted stored procedure. + * In case of failure the {@link Flux} will error. * * @param storedProcedureLink the stored procedure link. * @param options the request options. - * @return an {@link Observable} containing the single resource response for the deleted stored procedure or an error. + * @return an {@link Flux} containing the single resource response for the deleted stored procedure or an error. */ - Observable> deleteStoredProcedure(String storedProcedureLink, RequestOptions options); + Flux> deleteStoredProcedure(String storedProcedureLink, RequestOptions options); /** * READ a stored procedure by the stored procedure link. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the read stored procedure. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the read stored procedure. + * In case of failure the {@link Flux} will error. * * @param storedProcedureLink the stored procedure link. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the read stored procedure or an error. + * @return an {@link Flux} containing the single resource response with the read stored procedure or an error. */ - Observable> readStoredProcedure(String storedProcedureLink, RequestOptions options); + Flux> readStoredProcedure(String storedProcedureLink, RequestOptions options); /** * Reads all stored procedures in a document collection link. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the read stored procedures. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the read stored procedures. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the read stored procedures or an error. + * @return an {@link Flux} containing one or several feed response pages of the read stored procedures or an error. */ - Observable> readStoredProcedures(String collectionLink, FeedOptions options); + Flux> readStoredProcedures(String collectionLink, FeedOptions options); /** * Query for stored procedures in a document collection. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained stored procedures. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained stored procedures. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param query the query. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained stored procedures or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained stored procedures or an error. */ - Observable> queryStoredProcedures(String collectionLink, String query, FeedOptions options); + Flux> queryStoredProcedures(String collectionLink, String query, FeedOptions options); /** * Query for stored procedures in a document collection. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained stored procedures. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained stored procedures. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained stored procedures or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained stored procedures or an error. */ - Observable> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, + Flux> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, FeedOptions options); /** * Executes a stored procedure by the stored procedure link. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the stored procedure response. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the stored procedure response. + * In case of failure the {@link Flux} will error. * * @param storedProcedureLink the stored procedure link. * @param procedureParams the array of procedure parameter values. - * @return an {@link Observable} containing the single resource response with the stored procedure response or an error. + * @return an {@link Flux} containing the single resource response with the stored procedure response or an error. */ - Observable executeStoredProcedure(String storedProcedureLink, Object[] procedureParams); + Flux executeStoredProcedure(String storedProcedureLink, Object[] procedureParams); /** * Executes a stored procedure by the stored procedure link. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the stored procedure response. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the stored procedure response. + * In case of failure the {@link Flux} will error. * * @param storedProcedureLink the stored procedure link. * @param options the request options. * @param procedureParams the array of procedure parameter values. - * @return an {@link Observable} containing the single resource response with the stored procedure response or an error. + * @return an {@link Flux} containing the single resource response with the stored procedure response or an error. */ - Observable executeStoredProcedure(String storedProcedureLink, RequestOptions options, + Flux executeStoredProcedure(String storedProcedureLink, RequestOptions options, Object[] procedureParams); /** * Creates a trigger. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the created trigger. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the created trigger. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param trigger the trigger. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the created trigger or an error. + * @return an {@link Flux} containing the single resource response with the created trigger or an error. */ - Observable> createTrigger(String collectionLink, Trigger trigger, RequestOptions options); + Flux> createTrigger(String collectionLink, Trigger trigger, RequestOptions options); /** * Upserts a trigger. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the upserted trigger. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the upserted trigger. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param trigger the trigger to upsert. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the upserted trigger or an error. + * @return an {@link Flux} containing the single resource response with the upserted trigger or an error. */ - Observable> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options); + Flux> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options); /** * Replaces a trigger. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the replaced trigger. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the replaced trigger. + * In case of failure the {@link Flux} will error. * * @param trigger the trigger to use. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the replaced trigger or an error. + * @return an {@link Flux} containing the single resource response with the replaced trigger or an error. */ - Observable> replaceTrigger(Trigger trigger, RequestOptions options); + Flux> replaceTrigger(Trigger trigger, RequestOptions options); /** * Deletes a trigger. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the deleted trigger. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response for the deleted trigger. + * In case of failure the {@link Flux} will error. * * @param triggerLink the trigger link. * @param options the request options. - * @return an {@link Observable} containing the single resource response for the deleted trigger or an error. + * @return an {@link Flux} containing the single resource response for the deleted trigger or an error. */ - Observable> deleteTrigger(String triggerLink, RequestOptions options); + Flux> deleteTrigger(String triggerLink, RequestOptions options); /** * Reads a trigger by the trigger link. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the read trigger. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response for the read trigger. + * In case of failure the {@link Flux} will error. * * @param triggerLink the trigger link. * @param options the request options. - * @return an {@link Observable} containing the single resource response for the read trigger or an error. + * @return an {@link Flux} containing the single resource response for the read trigger or an error. */ - Observable> readTrigger(String triggerLink, RequestOptions options); + Flux> readTrigger(String triggerLink, RequestOptions options); /** * Reads all triggers in a document collection. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the read triggers. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the read triggers. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the read triggers or an error. + * @return an {@link Flux} containing one or several feed response pages of the read triggers or an error. */ - Observable> readTriggers(String collectionLink, FeedOptions options); + Flux> readTriggers(String collectionLink, FeedOptions options); /** * Query for triggers. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained triggers. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained triggers. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param query the query. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained triggers or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained triggers or an error. */ - Observable> queryTriggers(String collectionLink, String query, FeedOptions options); + Flux> queryTriggers(String collectionLink, String query, FeedOptions options); /** * Query for triggers. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained triggers. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained triggers. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained triggers or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained triggers or an error. */ - Observable> queryTriggers(String collectionLink, SqlQuerySpec querySpec, FeedOptions options); + Flux> queryTriggers(String collectionLink, SqlQuerySpec querySpec, FeedOptions options); /** * Creates a user defined function. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the created user defined function. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the created user defined function. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param udf the user defined function. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the created user defined function or an error. + * @return an {@link Flux} containing the single resource response with the created user defined function or an error. */ - Observable> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, + Flux> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options); /** * Upserts a user defined function. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the upserted user defined function. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the upserted user defined function. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param udf the user defined function to upsert. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the upserted user defined function or an error. + * @return an {@link Flux} containing the single resource response with the upserted user defined function or an error. */ - Observable> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, + Flux> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options); /** * Replaces a user defined function. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the replaced user defined function. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the replaced user defined function. + * In case of failure the {@link Flux} will error. * * @param udf the user defined function. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the replaced user defined function or an error. + * @return an {@link Flux} containing the single resource response with the replaced user defined function or an error. */ - Observable> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options); + Flux> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options); /** * Deletes a user defined function. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the deleted user defined function. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response for the deleted user defined function. + * In case of failure the {@link Flux} will error. * * @param udfLink the user defined function link. * @param options the request options. - * @return an {@link Observable} containing the single resource response for the deleted user defined function or an error. + * @return an {@link Flux} containing the single resource response for the deleted user defined function or an error. */ - Observable> deleteUserDefinedFunction(String udfLink, RequestOptions options); + Flux> deleteUserDefinedFunction(String udfLink, RequestOptions options); /** * READ a user defined function. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the read user defined function. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response for the read user defined function. + * In case of failure the {@link Flux} will error. * * @param udfLink the user defined function link. * @param options the request options. - * @return an {@link Observable} containing the single resource response for the read user defined function or an error. + * @return an {@link Flux} containing the single resource response for the read user defined function or an error. */ - Observable> readUserDefinedFunction(String udfLink, RequestOptions options); + Flux> readUserDefinedFunction(String udfLink, RequestOptions options); /** * Reads all user defined functions in a document collection. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the read user defined functions. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the read user defined functions. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the read user defined functions or an error. + * @return an {@link Flux} containing one or several feed response pages of the read user defined functions or an error. */ - Observable> readUserDefinedFunctions(String collectionLink, FeedOptions options); + Flux> readUserDefinedFunctions(String collectionLink, FeedOptions options); /** * Query for user defined functions. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained user defined functions. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained user defined functions. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param query the query. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained user defined functions or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained user defined functions or an error. */ - Observable> queryUserDefinedFunctions(String collectionLink, String query, + Flux> queryUserDefinedFunctions(String collectionLink, String query, FeedOptions options); /** * Query for user defined functions. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained user defined functions. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained user defined functions. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained user defined functions or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained user defined functions or an error. */ - Observable> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, + Flux> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, FeedOptions options); /** * Reads a conflict. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the read conflict. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the read conflict. + * In case of failure the {@link Flux} will error. * * @param conflictLink the conflict link. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the read conflict or an error. + * @return an {@link Flux} containing the single resource response with the read conflict or an error. */ - Observable> readConflict(String conflictLink, RequestOptions options); + Flux> readConflict(String conflictLink, RequestOptions options); /** * Reads all conflicts in a document collection. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the read conflicts. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the read conflicts. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the read conflicts or an error. + * @return an {@link Flux} containing one or several feed response pages of the read conflicts or an error. */ - Observable> readConflicts(String collectionLink, FeedOptions options); + Flux> readConflicts(String collectionLink, FeedOptions options); /** * Query for conflicts. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained conflicts. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained conflicts. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param query the query. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained conflicts or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained conflicts or an error. */ - Observable> queryConflicts(String collectionLink, String query, FeedOptions options); + Flux> queryConflicts(String collectionLink, String query, FeedOptions options); /** * Query for conflicts. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained conflicts. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained conflicts. + * In case of failure the {@link Flux} will error. * * @param collectionLink the collection link. * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained conflicts or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained conflicts or an error. */ - Observable> queryConflicts(String collectionLink, SqlQuerySpec querySpec, FeedOptions options); + Flux> queryConflicts(String collectionLink, SqlQuerySpec querySpec, FeedOptions options); /** * Deletes a conflict. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the deleted conflict. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response for the deleted conflict. + * In case of failure the {@link Flux} will error. * * @param conflictLink the conflict link. * @param options the request options. - * @return an {@link Observable} containing the single resource response for the deleted conflict or an error. + * @return an {@link Flux} containing the single resource response for the deleted conflict or an error. */ - Observable> deleteConflict(String conflictLink, RequestOptions options); + Flux> deleteConflict(String conflictLink, RequestOptions options); /** * Creates a user. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the created user. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the created user. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param user the user to create. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the created user or an error. + * @return an {@link Flux} containing the single resource response with the created user or an error. */ - Observable> createUser(String databaseLink, User user, RequestOptions options); + Flux> createUser(String databaseLink, User user, RequestOptions options); /** * Upserts a user. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the upserted user. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the upserted user. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param user the user to upsert. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the upserted user or an error. + * @return an {@link Flux} containing the single resource response with the upserted user or an error. */ - Observable> upsertUser(String databaseLink, User user, RequestOptions options); + Flux> upsertUser(String databaseLink, User user, RequestOptions options); /** * Replaces a user. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the replaced user. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the replaced user. + * In case of failure the {@link Flux} will error. * * @param user the user to use. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the replaced user or an error. + * @return an {@link Flux} containing the single resource response with the replaced user or an error. */ - Observable> replaceUser(User user, RequestOptions options); + Flux> replaceUser(User user, RequestOptions options); /** * Deletes a user. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the deleted user. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response for the deleted user. + * In case of failure the {@link Flux} will error. * * @param userLink the user link. * @param options the request options. - * @return an {@link Observable} containing the single resource response for the deleted user or an error. + * @return an {@link Flux} containing the single resource response for the deleted user or an error. */ - Observable> deleteUser(String userLink, RequestOptions options); + Flux> deleteUser(String userLink, RequestOptions options); /** * Reads a user. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the read user. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the read user. + * In case of failure the {@link Flux} will error. * * @param userLink the user link. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the read user or an error. + * @return an {@link Flux} containing the single resource response with the read user or an error. */ - Observable> readUser(String userLink, RequestOptions options); + Flux> readUser(String userLink, RequestOptions options); /** * Reads all users in a database. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the read users. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the read users. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the read users or an error. + * @return an {@link Flux} containing one or several feed response pages of the read users or an error. */ - Observable> readUsers(String databaseLink, FeedOptions options); + Flux> readUsers(String databaseLink, FeedOptions options); /** * Query for users. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained users. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained users. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param query the query. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained users or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained users or an error. */ - Observable> queryUsers(String databaseLink, String query, FeedOptions options); + Flux> queryUsers(String databaseLink, String query, FeedOptions options); /** * Query for users. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained users. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained users. + * In case of failure the {@link Flux} will error. * * @param databaseLink the database link. * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained users or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained users or an error. */ - Observable> queryUsers(String databaseLink, SqlQuerySpec querySpec, FeedOptions options); + Flux> queryUsers(String databaseLink, SqlQuerySpec querySpec, FeedOptions options); /** * Creates a permission. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the created permission. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the created permission. + * In case of failure the {@link Flux} will error. * * @param userLink the user link. * @param permission the permission to create. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the created permission or an error. + * @return an {@link Flux} containing the single resource response with the created permission or an error. */ - Observable> createPermission(String userLink, Permission permission, RequestOptions options); + Flux> createPermission(String userLink, Permission permission, RequestOptions options); /** * Upserts a permission. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the upserted permission. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the upserted permission. + * In case of failure the {@link Flux} will error. * * @param userLink the user link. * @param permission the permission to upsert. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the upserted permission or an error. + * @return an {@link Flux} containing the single resource response with the upserted permission or an error. */ - Observable> upsertPermission(String userLink, Permission permission, RequestOptions options); + Flux> upsertPermission(String userLink, Permission permission, RequestOptions options); /** * Replaces a permission. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the replaced permission. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the replaced permission. + * In case of failure the {@link Flux} will error. * * @param permission the permission to use. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the replaced permission or an error. + * @return an {@link Flux} containing the single resource response with the replaced permission or an error. */ - Observable> replacePermission(Permission permission, RequestOptions options); + Flux> replacePermission(Permission permission, RequestOptions options); /** * Deletes a permission. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response for the deleted permission. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response for the deleted permission. + * In case of failure the {@link Flux} will error. * * @param permissionLink the permission link. * @param options the request options. - * @return an {@link Observable} containing the single resource response for the deleted permission or an error. + * @return an {@link Flux} containing the single resource response for the deleted permission or an error. */ - Observable> deletePermission(String permissionLink, RequestOptions options); + Flux> deletePermission(String permissionLink, RequestOptions options); /** * Reads a permission. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the read permission. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the read permission. + * In case of failure the {@link Flux} will error. * * @param permissionLink the permission link. * @param options the request options. - * @return an {@link Observable} containing the single resource response with the read permission or an error. + * @return an {@link Flux} containing the single resource response with the read permission or an error. */ - Observable> readPermission(String permissionLink, RequestOptions options); + Flux> readPermission(String permissionLink, RequestOptions options); /** * Reads all permissions. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the read permissions. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the read permissions. + * In case of failure the {@link Flux} will error. * * @param permissionLink the permission link. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the read permissions or an error. + * @return an {@link Flux} containing one or several feed response pages of the read permissions or an error. */ - Observable> readPermissions(String permissionLink, FeedOptions options); + Flux> readPermissions(String permissionLink, FeedOptions options); /** * Query for permissions. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained permissions. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained permissions. + * In case of failure the {@link Flux} will error. * * @param permissionLink the permission link. * @param query the query. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained permissions or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained permissions or an error. */ - Observable> queryPermissions(String permissionLink, String query, FeedOptions options); + Flux> queryPermissions(String permissionLink, String query, FeedOptions options); /** * Query for permissions. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the obtained permissions. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the obtained permissions. + * In case of failure the {@link Flux} will error. * * @param permissionLink the permission link. * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained permissions or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained permissions or an error. */ - Observable> queryPermissions(String permissionLink, SqlQuerySpec querySpec, FeedOptions options); + Flux> queryPermissions(String permissionLink, SqlQuerySpec querySpec, FeedOptions options); /** * Replaces an offer. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the replaced offer. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the replaced offer. + * In case of failure the {@link Flux} will error. * * @param offer the offer to use. - * @return an {@link Observable} containing the single resource response with the replaced offer or an error. + * @return an {@link Flux} containing the single resource response with the replaced offer or an error. */ - Observable> replaceOffer(Offer offer); + Flux> replaceOffer(Offer offer); /** * Reads an offer. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the read offer. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the read offer. + * In case of failure the {@link Flux} will error. * * @param offerLink the offer link. - * @return an {@link Observable} containing the single resource response with the read offer or an error. + * @return an {@link Flux} containing the single resource response with the read offer or an error. */ - Observable> readOffer(String offerLink); + Flux> readOffer(String offerLink); /** * Reads offers. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of the read offers. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of the read offers. + * In case of failure the {@link Flux} will error. * * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the read offers or an error. + * @return an {@link Flux} containing one or several feed response pages of the read offers or an error. */ - Observable> readOffers(FeedOptions options); + Flux> readOffers(FeedOptions options); /** * Query for offers in a database. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of obtained obtained offers. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of obtained obtained offers. + * In case of failure the {@link Flux} will error. * * @param query the query. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained offers or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained offers or an error. */ - Observable> queryOffers(String query, FeedOptions options); + Flux> queryOffers(String query, FeedOptions options); /** * Query for offers in a database. *

* After subscription the operation will be performed. - * The {@link Observable} will contain one or several feed response pages of obtained obtained offers. - * In case of failure the {@link Observable} will error. + * The {@link Flux} will contain one or several feed response pages of obtained obtained offers. + * In case of failure the {@link Flux} will error. * * @param querySpec the query specification. * @param options the feed options. - * @return an {@link Observable} containing one or several feed response pages of the obtained offers or an error. + * @return an {@link Flux} containing one or several feed response pages of the obtained offers or an error. */ - Observable> queryOffers(SqlQuerySpec querySpec, FeedOptions options); + Flux> queryOffers(SqlQuerySpec querySpec, FeedOptions options); /** * Gets database account information. *

* After subscription the operation will be performed. - * The {@link Observable} upon successful completion will contain a single resource response with the database account. - * In case of failure the {@link Observable} will error. + * The {@link Flux} upon successful completion will contain a single resource response with the database account. + * In case of failure the {@link Flux} will error. * - * @return an {@link Observable} containing the single resource response with the database account or an error. + * @return an {@link Flux} containing the single resource response with the database account or an error. */ - Observable getDatabaseAccount(); + Flux getDatabaseAccount(); /** * Close this {@link AsyncDocumentClient} instance and cleans up the resources. diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java index 46f7585d61d52..56882323ad7a1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java @@ -24,8 +24,6 @@ import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -36,7 +34,7 @@ * This asynchronous client is used to configure and execute requests * against the service. */ -public class CosmosClient { +public class CosmosClient implements AutoCloseable { //Document client wrapper private final Configs configs; @@ -199,8 +197,8 @@ public Mono createDatabase(CosmosDatabaseSettings databa } Database wrappedDatabase = new Database(); wrappedDatabase.id(databaseSettings.id()); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(asyncDocumentClient.createDatabase(wrappedDatabase, options.toRequestOptions()).map(databaseResourceResponse -> - new CosmosDatabaseResponse(databaseResourceResponse, this)).toSingle())); + return asyncDocumentClient.createDatabase(wrappedDatabase, options.toRequestOptions()).map(databaseResourceResponse -> + new CosmosDatabaseResponse(databaseResourceResponse, this)).single(); } /** @@ -244,9 +242,9 @@ public Mono createDatabase(String id) { * @return a {@link Flux} containing one or several feed response pages of read databases or an error. */ public Flux> listDatabases(FeedOptions options) { - return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().readDatabases(options) + return getDocClientWrapper().readDatabases(options) .map(response-> BridgeInternal.createFeedResponse(CosmosDatabaseSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -290,14 +288,14 @@ public Flux> queryDatabases(String query, F * @return an {@link Flux} containing one or several feed response pages of read databases or an error. */ public Flux> queryDatabases(SqlQuerySpec querySpec, FeedOptions options){ - return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().queryDatabases(querySpec, options) + return getDocClientWrapper().queryDatabases(querySpec, options) .map(response-> BridgeInternal.createFeedResponse( CosmosDatabaseSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } Mono getDatabaseAccount() { - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(asyncDocumentClient.getDatabaseAccount().toSingle())); + return asyncDocumentClient.getDatabaseAccount().single(); } /** @@ -313,6 +311,7 @@ public CosmosDatabase getDatabase(String id) { /** * Close this {@link CosmosClient} instance and cleans up the resources. */ + @Override public void close() { asyncDocumentClient.close(); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java index 9665be3ece196..0a7fcc8b3a16a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java @@ -23,8 +23,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Mono; public class CosmosConflict extends CosmosResource { @@ -56,12 +54,12 @@ public Mono read(CosmosConflictRequestOptions options){ options = new CosmosConflictRequestOptions(); } RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.container.getDatabase() + return this.container.getDatabase() .getDocClientWrapper() .readConflict(getLink(), requestOptions) .map(response -> new CosmosConflictResponse(response, container)) - .toSingle())); - + .single(); + } /** @@ -79,11 +77,11 @@ public Mono delete(CosmosConflictRequestOptions options) options = new CosmosConflictRequestOptions(); } RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.container.getDatabase() + return this.container.getDatabase() .getDocClientWrapper() .deleteConflict(getLink(), requestOptions) .map(response -> new CosmosConflictResponse(response, container)) - .toSingle())); + .single(); } @Override @@ -95,4 +93,4 @@ protected String URIPathSegment() { protected String parentLink() { return this.container.getLink(); } -} +} \ No newline at end of file diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java index fc12eaf29d9cf..c5c6c82d4f4d0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java @@ -52,7 +52,7 @@ public class CosmosConflictProperties extends Resource { * * @return the operation kind. */ - public String getOperationKind() { + public String operationKind() { return super.getString(Constants.Properties.OPERATION_TYPE); } @@ -61,7 +61,7 @@ public String getOperationKind() { * * @return the resource type. */ - public String getResouceType() { + public String resouceType() { return super.getString(Constants.Properties.RESOURCE_TYPE); } @@ -69,7 +69,7 @@ public String getResouceType() { * Gets the resource ID for the conflict in the Azure Cosmos DB service. * @return resource Id for the conflict. */ - public String getSourceResourceId() { + public String sourceResourceId() { return super.getString(Constants.Properties.SOURCE_RESOURCE_ID); } @@ -93,9 +93,9 @@ public T getResource(Class klass) { return null; } } - + static List getFromV2Results(List results) { return results.stream().map(conflict -> new CosmosConflictProperties(conflict.toJson())) .collect(Collectors.toList()); } -} +} \ No newline at end of file diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java index cf969dac2ea2d..ec121491b824f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java @@ -28,4 +28,4 @@ public class CosmosConflictRequestOptions extends CosmosRequestOptions{ protected RequestOptions toRequestOptions() { return super.toRequestOptions(); } -} +} \ No newline at end of file diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java index daa2d69278fbd..e3bccae42d564 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java @@ -25,8 +25,8 @@ public class CosmosConflictResponse extends CosmosResponse { private CosmosContainer container; private CosmosConflict conflictClient; - - public CosmosConflictResponse(ResourceResponse response, CosmosContainer container) { + + CosmosConflictResponse(ResourceResponse response, CosmosContainer container) { super(response); if(response.getResource() == null){ super.resourceSettings(null); @@ -55,4 +55,4 @@ public CosmosConflict getConflict() { public CosmosConflictProperties getConflictProperties() { return resourceSettings(); } -} +} \ No newline at end of file diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index 39dbad4052aae..7d00a870f7028 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -24,8 +24,6 @@ import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Paths; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -102,9 +100,8 @@ public Mono read(CosmosContainerRequestOptions options) if (options == null) { options = new CosmosContainerRequestOptions(); } - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(database.getDocClientWrapper().readCollection(getLink(), - options.toRequestOptions()) - .map(response -> new CosmosContainerResponse(response, database)).toSingle())); + return database.getDocClientWrapper().readCollection(getLink(), options.toRequestOptions()) + .map(response -> new CosmosContainerResponse(response, database)).single(); } /** @@ -121,11 +118,10 @@ public Mono delete(CosmosContainerRequestOptions option if (options == null) { options = new CosmosContainerRequestOptions(); } - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(database.getDocClientWrapper() + return database.getDocClientWrapper() .deleteCollection(getLink(), options.toRequestOptions()) .map(response -> new CosmosContainerResponse(response, database)) - .toSingle())); + .single(); } /** @@ -158,11 +154,10 @@ public Mono replace(CosmosContainerSettings containerSe if(options == null){ options = new CosmosContainerRequestOptions(); } - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(database.getDocClientWrapper() + return database.getDocClientWrapper() .replaceCollection(containerSettings.getV2Collection(),options.toRequestOptions()) .map(response -> new CosmosContainerResponse(response, database)) - .toSingle())); + .single(); } /* CosmosItem operations */ @@ -212,8 +207,7 @@ public Mono createItem(Object item, CosmosItemRequestOptions options = new CosmosItemRequestOptions(); } RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(database.getDocClientWrapper() + return database.getDocClientWrapper() .createDocument(getLink(), CosmosItemProperties.fromObject(item), requestOptions, @@ -221,7 +215,7 @@ public Mono createItem(Object item, CosmosItemRequestOptions .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), this)) - .toSingle())); + .single(); } /** @@ -270,7 +264,7 @@ public Mono upsertItem(Object item, CosmosItemRequestOptions } RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.getDatabase() + return this.getDatabase() .getDocClientWrapper() .upsertDocument(this.getLink(), CosmosItemProperties.fromObject(item), @@ -279,7 +273,7 @@ public Mono upsertItem(Object item, CosmosItemRequestOptions .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), this)) - .toSingle())); + .single(); } /** @@ -306,11 +300,10 @@ public Flux> listItems() { * @return an {@link Flux} containing one or several feed response pages of the read cosmos items or an error. */ public Flux> listItems(FeedOptions options) { - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(getDatabase().getDocClientWrapper() + return getDatabase().getDocClientWrapper() .readDocuments(getLink(), options) .map(response-> BridgeInternal.createFeedResponse(CosmosItemProperties.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -340,14 +333,13 @@ public Flux> queryItems(String query, FeedOpt * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. */ public Flux> queryItems(SqlQuerySpec querySpec, FeedOptions options){ - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(getDatabase() + return getDatabase() .getDocClientWrapper() .queryDocuments(getLink(), querySpec, options) .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( CosmosItemProperties.getFromV2Results(response.results()), response.responseHeaders(), - response.queryMetrics())))); + response.queryMetrics())); } /** @@ -361,13 +353,12 @@ public Flux> queryItems(SqlQuerySpec querySpe * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. */ public Flux> queryChangeFeedItems(ChangeFeedOptions changeFeedOptions){ - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(getDatabase() + return getDatabase() .getDocClientWrapper() .queryDocumentChangeFeed(getLink(), changeFeedOptions) .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( CosmosItemProperties.getFromV2Results(response.results()), - response.responseHeaders(), response.queryMetrics())))); + response.responseHeaders(), response.queryMetrics())); } /** @@ -418,11 +409,10 @@ public Mono createStoredProcedure(CosmosStoredPro StoredProcedure sProc = new StoredProcedure(); sProc.id(settings.id()); sProc.setBody(settings.body()); - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(database.getDocClientWrapper() + return database.getDocClientWrapper() .createStoredProcedure(getLink(), sProc, options.toRequestOptions()) .map(response -> new CosmosStoredProcedureResponse(response, this)) - .toSingle())); + .single(); } /** @@ -437,11 +427,10 @@ public Mono createStoredProcedure(CosmosStoredPro * settings or an error. */ public Flux> listStoredProcedures(FeedOptions options){ - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + return database.getDocClientWrapper() .readStoredProcedures(getLink(), options) .map(response -> BridgeInternal.createFeedResponse(CosmosStoredProcedureSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -475,11 +464,10 @@ public Flux> queryStoredProcedures(S */ public Flux> queryStoredProcedures(SqlQuerySpec querySpec, FeedOptions options){ - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + return database.getDocClientWrapper() .queryStoredProcedures(getLink(), querySpec,options) .map(response -> BridgeInternal.createFeedResponse( CosmosStoredProcedureSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -513,10 +501,9 @@ public Mono createUserDefinedFunction(CosmosU if(options == null){ options = new CosmosRequestOptions(); } - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(database.getDocClientWrapper() + return database.getDocClientWrapper() .createUserDefinedFunction(getLink(), udf, options.toRequestOptions()) - .map(response -> new CosmosUserDefinedFunctionResponse(response, this)).toSingle())); + .map(response -> new CosmosUserDefinedFunctionResponse(response, this)).single(); } /** @@ -530,11 +517,10 @@ public Mono createUserDefinedFunction(CosmosU * @return an {@link Flux} containing one or several feed response pages of the read user defined functions or an error. */ public Flux> listUserDefinedFunctions(FeedOptions options){ - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + return database.getDocClientWrapper() .readUserDefinedFunctions(getLink(), options) .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -566,11 +552,10 @@ public Flux> queryUserDefinedFun */ public Flux> queryUserDefinedFunctions(SqlQuerySpec querySpec, FeedOptions options){ - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + return database.getDocClientWrapper() .queryUserDefinedFunctions(getLink(),querySpec, options) .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -600,11 +585,10 @@ public Mono createTrigger(CosmosTriggerSettings settings, if(options == null){ options = new CosmosRequestOptions(); } - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(database.getDocClientWrapper() + return database.getDocClientWrapper() .createTrigger(getLink(), trigger,options.toRequestOptions()) .map(response -> new CosmosTriggerResponse(response, this)) - .toSingle())); + .single(); } /** @@ -618,11 +602,10 @@ public Mono createTrigger(CosmosTriggerSettings settings, * @return an {@link Flux} containing one or several feed response pages of the read cosmos rigger settings or an error. */ public Flux> listTriggers(FeedOptions options){ - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + return database.getDocClientWrapper() .readTriggers(getLink(), options) .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -653,11 +636,10 @@ public Flux> queryTriggers(String query, Fee */ public Flux> queryTriggers(SqlQuerySpec querySpec, FeedOptions options){ - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + return database.getDocClientWrapper() .queryTriggers(getLink(), querySpec, options) .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -676,11 +658,10 @@ public CosmosTrigger getTrigger(String id){ * @return a {@link Flux} containing one or several feed response pages of the obtained conflicts or an error. */ public Flux> listConflicts(FeedOptions options) { - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + return database.getDocClientWrapper() .readConflicts(getLink(), options) .map(response -> BridgeInternal.createFeedResponse(CosmosConflictProperties.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -691,11 +672,10 @@ public Flux> listConflicts(FeedOptions op * @return a {@link Flux} containing one or several feed response pages of the obtained conflicts or an error. */ public Flux> queryConflicts(String query, FeedOptions options) { - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(database.getDocClientWrapper() + return database.getDocClientWrapper() .queryConflicts(getLink(), query, options) .map(response -> BridgeInternal.createFeedResponse(CosmosConflictProperties.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -715,25 +695,23 @@ public CosmosTrigger getConflict(String id){ public Mono readProvisionedThroughput(){ return this.read() .flatMap(cosmosContainerResponse -> - RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(database.getDocClientWrapper() + database.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosContainerResponse.resourceSettings().resourceId() - + "'", new FeedOptions()).toSingle())) + + "'", new FeedOptions()).single()) .flatMap(offerFeedResponse -> { if(offerFeedResponse.results().isEmpty()){ return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(database.getDocClientWrapper() + return database.getDocClientWrapper() .readOffer(offerFeedResponse.results() .get(0) - .selfLink()).toSingle())); + .selfLink()).single(); }) .map(cosmosOfferResponse -> cosmosOfferResponse .getResource() - .getThroughput())); + .getThroughput()); } /** @@ -745,11 +723,10 @@ public Mono readProvisionedThroughput(){ public Mono replaceProvisionedThroughputAsync(int requestUnitsPerSecond){ return this.read() .flatMap(cosmosContainerResponse -> - RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(database.getDocClientWrapper() + database.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosContainerResponse.resourceSettings().resourceId() - + "'", new FeedOptions()).toSingle())) + + "'", new FeedOptions()).single()) .flatMap(offerFeedResponse -> { if(offerFeedResponse.results().isEmpty()){ return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, @@ -757,10 +734,9 @@ public Mono replaceProvisionedThroughputAsync(int requestUnitsPerSecond } Offer offer = offerFeedResponse.results().get(0); offer.setThroughput(requestUnitsPerSecond); - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(database.getDocClientWrapper() - .replaceOffer(offer).toSingle())); - }).map(offerResourceResponse -> offerResourceResponse.getResource().getThroughput())); + return database.getDocClientWrapper() + .replaceOffer(offer).single(); + }).map(offerResourceResponse -> offerResourceResponse.getResource().getThroughput()); } /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java index b80f8ffd889b2..5214184ae20e1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java @@ -24,9 +24,7 @@ import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Paths; -import hu.akarnokd.rxjava.interop.RxJavaInterop; import org.apache.commons.lang3.StringUtils; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -65,9 +63,10 @@ public Mono read(){ * @return an {@link Mono} containing the single cosmos database response with the read database or an error. */ public Mono read(CosmosDatabaseRequestOptions options) { - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(getDocClientWrapper().readDatabase(getLink(), + return getDocClientWrapper().readDatabase(getLink(), options.toRequestOptions()) - .map(response -> new CosmosDatabaseResponse(response, getClient())).toSingle())); + .map(response -> new CosmosDatabaseResponse(response, getClient())) + .single(); } /** @@ -94,11 +93,10 @@ public Mono delete() { * @return an {@link Mono} containing the single cosmos database response */ public Mono delete(CosmosRequestOptions options) { - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(getDocClientWrapper() + return getDocClientWrapper() .deleteDatabase(getLink(), options.toRequestOptions()) .map(response -> new CosmosDatabaseResponse(response, getClient())) - .toSingle())); + .single(); } /* CosmosContainer operations */ @@ -133,9 +131,10 @@ public Mono createContainer(CosmosContainerSettings con */ public Mono createContainer(CosmosContainerSettings containerSettings, CosmosContainerRequestOptions options) { - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(getDocClientWrapper().createCollection(this.getLink(), + return getDocClientWrapper().createCollection(this.getLink(), containerSettings.getV2Collection(), options.toRequestOptions()).map(response -> - new CosmosContainerResponse(response, this)).toSingle())); + new CosmosContainerResponse(response, this)) + .single(); } /** @@ -213,10 +212,9 @@ private Mono createContainerIfNotExistsInternal(CosmosC * @return a {@link Flux} containing one or several feed response pages of read containers or an error. */ public Flux> listContainers(FeedOptions options) { - //TODO: - return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().readCollections(getLink(), options) + return getDocClientWrapper().readCollections(getLink(), options) .map(response-> BridgeInternal.createFeedResponse(CosmosContainerSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -259,11 +257,11 @@ public Flux> queryContainers(String query, * @return an {@link Flux} containing one or several feed response pages of the obtained containers or an error. */ public Flux> queryContainers(SqlQuerySpec querySpec, FeedOptions options){ - return RxJava2Adapter.flowableToFlux(RxJavaInterop.toV2Flowable(getDocClientWrapper().queryCollections(getLink(), querySpec, + return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response-> BridgeInternal.createFeedResponse( CosmosContainerSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -292,9 +290,9 @@ public Mono createUser(CosmosUserSettings settings) { * @return an {@link Mono} containing the single resource response with the created cosmos user or an error. */ public Mono createUser(CosmosUserSettings settings, RequestOptions options){ - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(getDocClientWrapper().createUser(this.getLink(), + return getDocClientWrapper().createUser(this.getLink(), settings.getV2User(), options).map(response -> - new CosmosUserResponse(response, this)).toSingle())); + new CosmosUserResponse(response, this)).single(); } public Mono upsertUser(CosmosUserSettings settings) { @@ -312,9 +310,9 @@ public Mono upsertUser(CosmosUserSettings settings) { * @return an {@link Mono} containing the single resource response with the upserted user or an error. */ public Mono upsertUser(CosmosUserSettings settings, RequestOptions options){ - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(getDocClientWrapper().upsertUser(this.getLink(), + return getDocClientWrapper().upsertUser(this.getLink(), settings.getV2User(), options).map(response -> - new CosmosUserResponse(response, this)).toSingle())); + new CosmosUserResponse(response, this)).single(); } public Flux> listUsers() { @@ -332,11 +330,10 @@ public Flux> listUsers() { * @return an {@link Flux} containing one or several feed response pages of the read cosmos users or an error. */ public Flux> listUsers(FeedOptions options){ - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(getDocClientWrapper() + return getDocClientWrapper() .readUsers(getLink(), options) .map(response-> BridgeInternal.createFeedResponse(CosmosUserSettings.getFromV2Results(response.results(),this), - response.responseHeaders())))); + response.responseHeaders())); } public Flux> queryUsers(String query, FeedOptions options){ @@ -355,12 +352,11 @@ public Flux> queryUsers(String query, FeedOptio * @return an {@link Flux} containing one or several feed response pages of the obtained users or an error. */ public Flux> queryUsers(SqlQuerySpec querySpec, FeedOptions options){ - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(getDocClientWrapper() + return getDocClientWrapper() .queryUsers(getLink(), querySpec, options) .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( CosmosUserSettings.getFromV2Results(response.results(), this), - response.responseHeaders(), response.queryMetrics())))); + response.responseHeaders(), response.queryMetrics())); } public CosmosUser getUser(String id) { @@ -375,20 +371,18 @@ public CosmosUser getUser(String id) { public Mono readProvisionedThroughput(){ return this.read() .flatMap(cosmosDatabaseResponse -> - RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(getDocClientWrapper().queryOffers("select * from c where c.offerResourceId = '" + + getDocClientWrapper().queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.resourceSettings().resourceId() - + "'", new FeedOptions()).toSingle())) + + "'", new FeedOptions()).single() .flatMap(offerFeedResponse -> { if(offerFeedResponse.results().isEmpty()){ return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(getDocClientWrapper() + return getDocClientWrapper() .readOffer(offerFeedResponse.results() .get(0) - .selfLink()).toSingle())); + .selfLink()).single(); }) .map(cosmosContainerResponse1 -> cosmosContainerResponse1 .getResource() @@ -404,11 +398,10 @@ public Mono readProvisionedThroughput(){ public Mono replaceProvisionedThroughputAsync(int requestUnitsPerSecond){ return this.read() .flatMap(cosmosDatabaseResponse -> - RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(this.getDocClientWrapper() + this.getDocClientWrapper() .queryOffers("select * from c where c.offerResourceId = '" + cosmosDatabaseResponse.resourceSettings().resourceId() - + "'", new FeedOptions()).toSingle())) + + "'", new FeedOptions()).single() .flatMap(offerFeedResponse -> { if(offerFeedResponse.results().isEmpty()){ return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, @@ -416,9 +409,8 @@ public Mono replaceProvisionedThroughputAsync(int requestUnitsPerSecond } Offer offer = offerFeedResponse.results().get(0); offer.setThroughput(requestUnitsPerSecond); - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(this.getDocClientWrapper() - .replaceOffer(offer).toSingle())); + return this.getDocClientWrapper() + .replaceOffer(offer).single(); }).map(offerResourceResponse -> offerResourceResponse.getResource().getThroughput())); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java index c52aa5a22fe35..38877be0371a0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java @@ -23,8 +23,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Mono; public class CosmosItem extends CosmosResource{ @@ -65,10 +63,10 @@ public Mono read(CosmosItemRequestOptions options) { options = new CosmosItemRequestOptions(); } RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase().getDocClientWrapper() + return container.getDatabase().getDocClientWrapper() .readDocument(getLink(), requestOptions) .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) - .toSingle())); + .single(); } /** @@ -102,11 +100,11 @@ public Mono replace(Object item, CosmosItemRequestOptions op options = new CosmosItemRequestOptions(); } RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase() + return container.getDatabase() .getDocClientWrapper() .replaceDocument(getLink(), doc, requestOptions) .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) - .toSingle())); + .single(); } /** @@ -136,12 +134,11 @@ public Mono delete(CosmosItemRequestOptions options){ options = new CosmosItemRequestOptions(); } RequestOptions requestOptions = options.toRequestOptions(); - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(container.getDatabase() + return container.getDatabase() .getDocClientWrapper() .deleteDocument(getLink(), requestOptions) .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), container)) - .toSingle())); + .single(); } void setContainer(CosmosContainer container) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java index 72e2b845ff334..4681a566f5ea9 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java @@ -23,8 +23,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Mono; public class CosmosPermission extends CosmosResource{ @@ -48,11 +46,11 @@ public class CosmosPermission extends CosmosResource{ */ public Mono read(RequestOptions options) { - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(cosmosUser.getDatabase() + return cosmosUser.getDatabase() .getDocClientWrapper() .readPermission(getLink(),options) .map(response -> new CosmosPermissionResponse(response, cosmosUser)) - .toSingle())); + .single(); } /** @@ -68,11 +66,11 @@ public Mono read(RequestOptions options) { */ public Mono replace(CosmosPermissionSettings permissionSettings, RequestOptions options) { - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(cosmosUser.getDatabase() + return cosmosUser.getDatabase() .getDocClientWrapper() .replacePermission(permissionSettings.getV2Permissions(), options) .map(response -> new CosmosPermissionResponse(response, cosmosUser)) - .toSingle())); + .single(); } /** @@ -89,11 +87,11 @@ public Mono delete(CosmosPermissionsRequestOptions opt if(options == null){ options = new CosmosPermissionsRequestOptions(); } - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(cosmosUser.getDatabase() + return cosmosUser.getDatabase() .getDocClientWrapper() .deletePermission(getLink(), options.toRequestOptions()) .map(response -> new CosmosPermissionResponse(response, cosmosUser)) - .toSingle())); + .single(); } @Override diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java index 319b32a187afd..c051939992ded 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java @@ -37,14 +37,16 @@ public class CosmosPermissionResponse extends CosmosResponse getFromV2Results(List results) { return results.stream().map(permission -> new CosmosPermissionSettings(permission.toJson())).collect(Collectors.toList()); } @@ -42,6 +41,17 @@ public CosmosPermissionSettings() { super(); } + /** + * Sets the id + * + * @param id the name of the resource. + * @return the cosmos permission settings with id set + */ + public CosmosPermissionSettings id(String id) { + super.id(id); + return this; + } + /** * Initialize a permission object from json string. * @@ -56,7 +66,7 @@ public CosmosPermissionSettings(String jsonString) { * * @return the resource link. */ - public String getResourceLink() { + public String resourceLink() { return super.getString(Constants.Properties.RESOURCE_LINK); } @@ -65,8 +75,9 @@ public String getResourceLink() { * * @param resourceLink the resource link. */ - public void setResourceLink(String resourceLink) { + public CosmosPermissionSettings resourceLink(String resourceLink) { super.set(Constants.Properties.RESOURCE_LINK, resourceLink); + return this; } /** @@ -74,7 +85,7 @@ public void setResourceLink(String resourceLink) { * * @return the permission mode. */ - public PermissionMode getPermissionMode() { + public PermissionMode permissionMode() { String value = super.getString(Constants.Properties.PERMISSION_MODE); return PermissionMode.valueOf(StringUtils.upperCase(value)); } @@ -84,9 +95,10 @@ public PermissionMode getPermissionMode() { * * @param permissionMode the permission mode. */ - public void setPermissionMode(PermissionMode permissionMode) { + public CosmosPermissionSettings permissionMode(PermissionMode permissionMode) { this.set(Constants.Properties.PERMISSION_MODE, permissionMode.toString().toLowerCase()); + return this; } /** @@ -94,7 +106,7 @@ public void setPermissionMode(PermissionMode permissionMode) { * * @return the access token. */ - public String getToken() { + public String token() { return super.getString(Constants.Properties.TOKEN); } @@ -120,11 +132,12 @@ public String getToken() { * * @param partitionkey the partition key. */ - public void setResourcePartitionKey(PartitionKey partitionkey) { + public CosmosPermissionSettings resourcePartitionKey(PartitionKey partitionkey) { super.set(Constants.Properties.RESOURCE_PARTITION_KEY, partitionkey.getInternalPartitionKey().toJson()); + return this; } - public Permission getV2Permissions() { - return null; + Permission getV2Permissions() { + return new Permission(this.toJson()); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java index a3c6210b68cb7..c27633186a3ff 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java @@ -23,8 +23,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Mono; public class CosmosStoredProcedure extends CosmosResource { @@ -50,16 +48,16 @@ protected String parentLink() { * READ a stored procedure by the stored procedure link. *

* After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the read stored + * The {@link Mono} upon successful completion will contain a single resource response with the read stored * procedure. * In case of failure the {@link Mono} will error. * - * @param options the request options. + * @param options the request options. * @return an {@link Mono} containing the single resource response with the read stored procedure or an error. */ - public Mono read(RequestOptions options){ - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(cosmosContainer.getDatabase().getDocClientWrapper().readStoredProcedure(getLink(), options) - .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)).toSingle())); + public Mono read(RequestOptions options) { + return cosmosContainer.getDatabase().getDocClientWrapper().readStoredProcedure(getLink(), options) + .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)).single(); } /** @@ -69,16 +67,15 @@ public Mono read(RequestOptions options){ * The {@link Mono} upon successful completion will contain a single resource response for the deleted stored procedure. * In case of failure the {@link Mono} will error. * - * @param options the request options. + * @param options the request options. * @return an {@link Mono} containing the single resource response for the deleted stored procedure or an error. */ - public Mono delete(CosmosRequestOptions options){ - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(cosmosContainer.getDatabase() - .getDocClientWrapper() - .deleteStoredProcedure(getLink(), options.toRequestOptions()) - .map(response -> new CosmosResponse(response.getResource())) - .toSingle())); + public Mono delete(CosmosRequestOptions options) { + return cosmosContainer.getDatabase() + .getDocClientWrapper() + .deleteStoredProcedure(getLink(), options.toRequestOptions()) + .map(response -> new CosmosResponse(response.getResource())) + .single(); } /** @@ -88,17 +85,16 @@ public Mono delete(CosmosRequestOptions options){ * The {@link Mono} upon successful completion will contain a single resource response with the stored procedure response. * In case of failure the {@link Mono} will error. * - * @param procedureParams the array of procedure parameter values. - * @param options the request options. + * @param procedureParams the array of procedure parameter values. + * @param options the request options. * @return an {@link Mono} containing the single resource response with the stored procedure response or an error. */ - public Mono execute(Object[] procedureParams, RequestOptions options){ - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(cosmosContainer.getDatabase() - .getDocClientWrapper() - .executeStoredProcedure(getLink(), options, procedureParams) - .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)) - .toSingle())); + public Mono execute(Object[] procedureParams, RequestOptions options) { + return cosmosContainer.getDatabase() + .getDocClientWrapper() + .executeStoredProcedure(getLink(), options, procedureParams) + .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)) + .single(); } /** @@ -109,17 +105,16 @@ public Mono execute(Object[] procedureParams, Req * In case of failure the {@link Mono} will error. * * @param storedProcedureSettings the stored procedure settings. - * @param options the request options. + * @param options the request options. * @return an {@link Mono} containing the single resource response with the replaced stored procedure or an error. */ public Mono replace(CosmosStoredProcedureSettings storedProcedureSettings, - RequestOptions options){ - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(cosmosContainer.getDatabase() - .getDocClientWrapper() - .replaceStoredProcedure(new StoredProcedure(storedProcedureSettings.toJson()), options) - .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)) - .toSingle())); + RequestOptions options) { + return cosmosContainer.getDatabase() + .getDocClientWrapper() + .replaceStoredProcedure(new StoredProcedure(storedProcedureSettings.toJson()), options) + .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)) + .single(); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java index 84811f31ef463..c6755ab824ec3 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java @@ -23,11 +23,9 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Mono; -public class CosmosTrigger extends CosmosResource{ +public class CosmosTrigger extends CosmosResource { private CosmosContainer container; @@ -53,16 +51,15 @@ protected String parentLink() { * The {@link Mono} upon successful completion will contain a single resource response for the read trigger. * In case of failure the {@link Mono} will error. * - * @param options the request options. + * @param options the request options. * @return an {@link Mono} containing the single resource response for the read cosmos trigger or an error. */ - public Mono read(RequestOptions options){ - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(container.getDatabase() - .getDocClientWrapper() - .readTrigger(getLink(), options) - .map(response -> new CosmosTriggerResponse(response, container)) - .toSingle())); + public Mono read(RequestOptions options) { + return container.getDatabase() + .getDocClientWrapper() + .readTrigger(getLink(), options) + .map(response -> new CosmosTriggerResponse(response, container)) + .single(); } @@ -74,16 +71,15 @@ public Mono read(RequestOptions options){ * In case of failure the {@link Mono} will error. * * @param triggerSettings the cosmos trigger settings. - * @param options the request options. + * @param options the request options. * @return an {@link Mono} containing the single resource response with the replaced cosmos trigger or an error. */ - public Mono replace(CosmosTriggerSettings triggerSettings, RequestOptions options){ - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(container.getDatabase() - .getDocClientWrapper() - .replaceTrigger(new Trigger(triggerSettings.toJson()), options) - .map(response -> new CosmosTriggerResponse(response, container)) - .toSingle())); + public Mono replace(CosmosTriggerSettings triggerSettings, RequestOptions options) { + return container.getDatabase() + .getDocClientWrapper() + .replaceTrigger(new Trigger(triggerSettings.toJson()), options) + .map(response -> new CosmosTriggerResponse(response, container)) + .single(); } /** @@ -93,16 +89,15 @@ public Mono replace(CosmosTriggerSettings triggerSettings * The {@link Mono} upon successful completion will contain a single resource response for the deleted trigger. * In case of failure the {@link Mono} will error. * - * @param options the request options. + * @param options the request options. * @return an {@link Mono} containing the single resource response for the deleted cosmos trigger or an error. */ - public Mono delete(CosmosRequestOptions options){ - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(container.getDatabase() - .getDocClientWrapper() - .deleteTrigger(getLink(), options.toRequestOptions()) - .map(response -> new CosmosResponse(response.getResource())) - .toSingle())); + public Mono delete(CosmosRequestOptions options) { + return container.getDatabase() + .getDocClientWrapper() + .deleteTrigger(getLink(), options.toRequestOptions()) + .map(response -> new CosmosResponse(response.getResource())) + .single(); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java index 0a04703beef9c..0424c37de31b9 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java @@ -1,8 +1,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -27,9 +25,9 @@ public Mono read() { * @return a {@link Mono} containing the single resource response with the read user or an error. */ public Mono read(RequestOptions options) { - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.database.getDocClientWrapper() + return this.database.getDocClientWrapper() .readUser(getLink(), options) - .map(response -> new CosmosUserResponse(response, database)).toSingle())); + .map(response -> new CosmosUserResponse(response, database)).single(); } /** @@ -40,9 +38,9 @@ public Mono read(RequestOptions options) { * @return a {@link Mono} containing the single resource response with the replaced user or an error. */ public Mono replace(CosmosUserSettings userSettings, RequestOptions options) { - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.database.getDocClientWrapper() + return this.database.getDocClientWrapper() .replaceUser(userSettings.getV2User(), options) - .map(response -> new CosmosUserResponse(response, database)).toSingle())); + .map(response -> new CosmosUserResponse(response, database)).single(); } /** @@ -52,9 +50,9 @@ public Mono replace(CosmosUserSettings userSettings, Request * @return a {@link Mono} containing the single resource response with the deleted user or an error. */ public Mono delete(RequestOptions options) { - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(this.database.getDocClientWrapper() + return this.database.getDocClientWrapper() .deleteUser(getLink(), options) - .map(response -> new CosmosUserResponse(response, database)).toSingle())); + .map(response -> new CosmosUserResponse(response, database)).single(); } /** @@ -73,10 +71,10 @@ public Mono createPermission(CosmosPermissionSettings options = new CosmosPermissionsRequestOptions(); } Permission permission = permissionSettings.getV2Permissions(); - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(database.getDocClientWrapper() + return database.getDocClientWrapper() .createPermission(getLink(), permission, options.toRequestOptions()) .map(response -> new CosmosPermissionResponse(response, this)) - .toSingle())); + .single(); } /** @@ -95,10 +93,10 @@ public Mono upsertPermission(CosmosPermissionSettings if(options == null){ options = new CosmosPermissionsRequestOptions(); } - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(database.getDocClientWrapper() + return database.getDocClientWrapper() .upsertPermission(getLink(), permission, options.toRequestOptions()) .map(response -> new CosmosPermissionResponse(response, this)) - .toSingle())); + .single(); } @@ -113,11 +111,10 @@ public Mono upsertPermission(CosmosPermissionSettings * @return an {@link Flux} containing one or several feed response pages of the read permissions or an error. */ public Flux> listPermissions(FeedOptions options) { - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(getDatabase().getDocClientWrapper() + return getDatabase().getDocClientWrapper() .readPermissions(getLink(), options) .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); } /** @@ -132,11 +129,19 @@ public Flux> listPermissions(FeedOptions * @return an {@link Flux} containing one or several feed response pages of the obtained permissions or an error. */ public Flux> queryPermissions(String query, FeedOptions options) { - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable(getDatabase().getDocClientWrapper() + return getDatabase().getDocClientWrapper() .queryPermissions(getLink(), query, options) .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionSettings.getFromV2Results(response.results()), - response.responseHeaders())))); + response.responseHeaders())); + } + + /** + * Get cosmos permission without making a call to backend + * @param id the id + * @return the cosmos permission + */ + public CosmosPermission getPermission(String id){ + return new CosmosPermission(id, this); } @Override diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java index 5c8e9ca89bddb..b17afd20f11fd 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java @@ -23,11 +23,9 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Mono; -public class CosmosUserDefinedFunction extends CosmosResource{ +public class CosmosUserDefinedFunction extends CosmosResource { private CosmosContainer container; @@ -40,39 +38,39 @@ public class CosmosUserDefinedFunction extends CosmosResource{ * READ a user defined function. *

* After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response for the read user defined + * The {@link Mono} upon successful completion will contain a single resource response for the read user defined * function. * In case of failure the {@link Mono} will error. + * * @param options the request options. * @return an {@link Mono} containing the single resource response for the read user defined function or an error. */ - public Mono read(RequestOptions options){ - return RxJava2Adapter.singleToMono(RxJavaInterop.toV2Single(container.getDatabase().getDocClientWrapper().readUserDefinedFunction(getLink(), options) - .map(response -> new CosmosUserDefinedFunctionResponse(response, container)).toSingle())); + public Mono read(RequestOptions options) { + return container.getDatabase().getDocClientWrapper().readUserDefinedFunction(getLink(), options) + .map(response -> new CosmosUserDefinedFunctionResponse(response, container)).single(); } /** * Replaces a cosmos user defined function. *

* After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the replaced user + * The {@link Mono} upon successful completion will contain a single resource response with the replaced user * defined function. * In case of failure the {@link Mono} will error. * - * @param udfSettings the cosmos user defined function settings. - * @param options the request options. - * @return an {@link Mono} containing the single resource response with the replaced cosmos user defined function + * @param udfSettings the cosmos user defined function settings. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the replaced cosmos user defined function * or an error. */ public Mono replace(CosmosUserDefinedFunctionSettings udfSettings, - RequestOptions options){ - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(container.getDatabase() - .getDocClientWrapper() - .replaceUserDefinedFunction(new UserDefinedFunction(udfSettings.toJson()) - , options) - .map(response -> new CosmosUserDefinedFunctionResponse(response, container)) - .toSingle())); + RequestOptions options) { + return container.getDatabase() + .getDocClientWrapper() + .replaceUserDefinedFunction(new UserDefinedFunction(udfSettings.toJson()) + , options) + .map(response -> new CosmosUserDefinedFunctionResponse(response, container)) + .single(); } /** @@ -86,13 +84,12 @@ public Mono replace(CosmosUserDefinedFunction * @return an {@link Mono} containing the single resource response for the deleted cosmos user defined function or * an error. */ - public Mono delete(CosmosRequestOptions options){ - return RxJava2Adapter.singleToMono( - RxJavaInterop.toV2Single(container.getDatabase() - .getDocClientWrapper() - .deleteUserDefinedFunction(this.getLink(), options.toRequestOptions()) - .map(response -> new CosmosResponse(response.getResource())) - .toSingle())); + public Mono delete(CosmosRequestOptions options) { + return container.getDatabase() + .getDocClientWrapper() + .deleteUserDefinedFunction(this.getLink(), options.toRequestOptions()) + .map(response -> new CosmosResponse(response.getResource())) + .single(); } @Override diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java index ad1efea18e057..98a4d3cea5672 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java @@ -13,6 +13,15 @@ public CosmosUserSettings() { super(); } + /** + * Sets the id + * @param id the name of the resource. + * @return the current instance of cosmos user settings + */ + public CosmosUserSettings id(String id) { + return (CosmosUserSettings) super.id(id); + } + /** * Initialize a user object from json string. * diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java index c8870be98941a..6460e7e0fca6d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java @@ -40,8 +40,6 @@ import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; -import hu.akarnokd.rxjava.interop.RxJavaInterop; -import reactor.adapter.rxjava.RxJava2Adapter; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; @@ -91,9 +89,7 @@ public ChangeFeedContextClientImpl(CosmosContainer cosmosContainer, Scheduler rx @Override public Flux> readPartitionKeyRangeFeed(String partitionKeyRangesOrCollectionLink, FeedOptions feedOptions) { - return RxJava2Adapter.flowableToFlux( - RxJavaInterop.toV2Flowable( - this.documentClient.readPartitionKeyRanges(partitionKeyRangesOrCollectionLink, feedOptions))) + return this.documentClient.readPartitionKeyRanges(partitionKeyRangesOrCollectionLink, feedOptions) .subscribeOn(this.rxScheduler); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java index 59a2d5c34ff4b..c7b2b60dae307 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java @@ -29,13 +29,12 @@ import com.azure.data.cosmos.internal.query.Paginator; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import rx.Observable; -import rx.Single; -import rx.functions.Func1; -import rx.functions.Func2; +import reactor.core.publisher.Flux; import java.util.HashMap; import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; class ChangeFeedQueryImpl { @@ -134,18 +133,17 @@ private ChangeFeedOptions getChangeFeedOptions(ChangeFeedOptions options, String return newOps; } - public Observable> executeAsync() { + public Flux> executeAsync() { - Func2 createRequestFunc = (continuationToken, pageSize) -> this.createDocumentServiceRequest(continuationToken, pageSize); + BiFunction createRequestFunc = this::createDocumentServiceRequest; - // TODO: clean up if we want to use single vs observable. - Func1>> executeFunc = request -> this.executeRequestAsync(request).toObservable(); + Function>> executeFunc = this::executeRequestAsync; return Paginator.getPaginatedChangeFeedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, options.maxItemCount() != null ? options.maxItemCount(): -1); } - private Single> executeRequestAsync(RxDocumentServiceRequest request) { - return client.readFeed(request).toSingle() + private Flux> executeRequestAsync(RxDocumentServiceRequest request) { + return client.readFeed(request) .map( rsp -> BridgeInternal.toChaneFeedResponsePage(rsp, klass)); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java index 8a1262f426e88..94ac800cb3a8b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java @@ -65,6 +65,8 @@ import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; import com.azure.data.cosmos.internal.directconnectivity.GlobalAddressResolver; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpClientConfig; import com.azure.data.cosmos.internal.query.DocumentQueryExecutionContextFactory; import com.azure.data.cosmos.internal.query.IDocumentQueryClient; import com.azure.data.cosmos.internal.query.IDocumentQueryExecutionContext; @@ -73,16 +75,11 @@ import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClientBuilder; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; -import rx.functions.Func1; -import rx.functions.Func2; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -95,6 +92,8 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.function.BiFunction; +import java.util.function.Function; import static com.azure.data.cosmos.BridgeInternal.documentFromObject; import static com.azure.data.cosmos.BridgeInternal.getAltLink; @@ -141,7 +140,7 @@ public class RxDocumentClientImpl implements AsyncDocumentClient, IAuthorization * supported. */ private final QueryCompatibilityMode queryCompatibilityMode = QueryCompatibilityMode.Default; - private final CompositeHttpClient rxClient; + private final HttpClient reactorHttpClient; private final GlobalEndpointManager globalEndpointManager; private final RetryPolicy retryPolicy; private volatile boolean useMultipleWriteLocations; @@ -215,9 +214,9 @@ public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken ConsistencyLevel consistencyLevel, Configs configs) { logger.info( - "Initializing DocumentClient with" - + " serviceEndpoint [{}], ConnectionPolicy [{}], ConsistencyLevel [{}]", - serviceEndpoint, connectionPolicy, consistencyLevel); + "Initializing DocumentClient with" + + " serviceEndpoint [{}], connectionPolicy [{}], consistencyLevel [{}], directModeProtocol [{}]", + serviceEndpoint, connectionPolicy, consistencyLevel, configs.getProtocol()); this.configs = configs; this.masterKeyOrResourceToken = masterKeyOrResourceToken; @@ -250,7 +249,7 @@ public RxDocumentClientImpl(URI serviceEndpoint, String masterKeyOrResourceToken userAgentContainer.setSuffix(userAgentSuffix); } - this.rxClient = httpClientBuilder().build(); + this.reactorHttpClient = httpClient(); this.globalEndpointManager = new GlobalEndpointManager(asDatabaseAccountManagerInternal(), this.connectionPolicy, /**/configs); this.retryPolicy = new RetryPolicy(this.globalEndpointManager, this.connectionPolicy); this.resetSessionTokenRetryPolicy = retryPolicy; @@ -272,14 +271,14 @@ private void initializeGatewayConfigurationReader() { resourceToken, this.connectionPolicy, this.authorizationTokenProvider, - this.rxClient); + this.reactorHttpClient); - DatabaseAccount databaseAccount = this.gatewayConfigurationReader.initializeReaderAsync().toBlocking().value(); + DatabaseAccount databaseAccount = this.gatewayConfigurationReader.initializeReaderAsync().block(); this.useMultipleWriteLocations = this.connectionPolicy.usingMultipleWriteLocations() && BridgeInternal.isEnableMultipleWriteLocations(databaseAccount); // TODO: add support for openAsync // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/332589 - this.globalEndpointManager.refreshLocationAsync(databaseAccount).await(); + this.globalEndpointManager.refreshLocationAsync(databaseAccount).block(); } public void init() { @@ -291,7 +290,7 @@ public void init() { this.queryCompatibilityMode, this.userAgentContainer, this.globalEndpointManager, - this.rxClient); + this.reactorHttpClient); this.globalEndpointManager.init(); this.initializeGatewayConfigurationReader(); @@ -319,7 +318,7 @@ private void initializeDirectConnectivity() { ); this.addressResolver = new GlobalAddressResolver( - this.rxClient, + this.reactorHttpClient, this.globalEndpointManager, this.configs.getProtocol(), this, @@ -343,7 +342,7 @@ public URI getServiceEndpoint() { } @Override - public Observable getDatabaseAccountFromEndpoint(URI endpoint) { + public Flux getDatabaseAccountFromEndpoint(URI endpoint) { logger.info("Getting database account endpoint from {}", endpoint); return RxDocumentClientImpl.this.getDatabaseAccountFromEndpoint(endpoint); } @@ -360,24 +359,24 @@ RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, - CompositeHttpClient rxClient) { + HttpClient httpClient) { return new RxGatewayStoreModel(sessionContainer, consistencyLevel, queryCompatibilityMode, userAgentContainer, globalEndpointManager, - rxClient); + httpClient); } - private CompositeHttpClientBuilder httpClientBuilder() { + private HttpClient httpClient() { - HttpClientFactory factory = new HttpClientFactory(this.configs) + HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs) .withMaxIdleConnectionTimeoutInMillis(this.connectionPolicy.idleConnectionTimeoutInMillis()) .withPoolSize(this.connectionPolicy.maxPoolSize()) .withHttpProxy(this.connectionPolicy.proxy()) .withRequestTimeoutInMillis(this.connectionPolicy.requestTimeoutInMillis()); - return factory.toHttpClientBuilder(); + return HttpClient.createFixed(httpClientConfig); } private void createStoreModel(boolean subscribeRntbdStatus) { @@ -430,12 +429,12 @@ public ConnectionPolicy getConnectionPolicy() { } @Override - public Observable> createDatabase(Database database, RequestOptions options) { + public Flux> createDatabase(Database database, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createDatabaseInternal(database, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> createDatabaseInternal(Database database, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { + private Flux> createDatabaseInternal(Database database, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (database == null) { @@ -455,17 +454,17 @@ private Observable> createDatabaseInternal(Database d return this.create(request).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in creating a database. due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> deleteDatabase(String databaseLink, RequestOptions options) { + public Flux> deleteDatabase(String databaseLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> deleteDatabaseInternal(String databaseLink, RequestOptions options, + private Flux> deleteDatabaseInternal(String databaseLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { @@ -485,17 +484,17 @@ private Observable> deleteDatabaseInternal(String dat return this.delete(request).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in deleting a database. due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readDatabase(String databaseLink, RequestOptions options) { + public Flux> readDatabase(String databaseLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDatabaseInternal(databaseLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> readDatabaseInternal(String databaseLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { + private Flux> readDatabaseInternal(String databaseLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); @@ -513,12 +512,12 @@ private Observable> readDatabaseInternal(String datab return this.read(request).map(response -> toResourceResponse(response, Database.class)); } catch (Exception e) { logger.debug("Failure in reading a database. due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readDatabases(FeedOptions options) { + public Flux> readDatabases(FeedOptions options) { return readFeed(options, ResourceType.Database, Database.class, Paths.DATABASES_ROOT); } @@ -559,7 +558,7 @@ private String parentResourceLinkToQueryLink(String parentResouceLink, ResourceT } } - private Observable> createQuery( + private Flux> createQuery( String parentResourceLink, SqlQuerySpec sqlQuery, FeedOptions options, @@ -570,33 +569,31 @@ private Observable> createQuery( UUID activityId = Utils.randomUUID(); IDocumentQueryClient queryClient = DocumentQueryClientImpl(RxDocumentClientImpl.this); - Observable> executionContext = + Flux> executionContext = DocumentQueryExecutionContextFactory.createDocumentQueryExecutionContextAsync(queryClient, resourceTypeEnum, klass, sqlQuery , options, queryResourceLink, false, activityId); - return executionContext.single().flatMap(ex -> { - return ex.executeAsync(); - }); + return executionContext.flatMap(IDocumentQueryExecutionContext::executeAsync); } @Override - public Observable> queryDatabases(String query, FeedOptions options) { + public Flux> queryDatabases(String query, FeedOptions options) { return queryDatabases(new SqlQuerySpec(query), options); } @Override - public Observable> queryDatabases(SqlQuerySpec querySpec, FeedOptions options) { + public Flux> queryDatabases(SqlQuerySpec querySpec, FeedOptions options) { return createQuery(Paths.DATABASES_ROOT, querySpec, options, Database.class, ResourceType.Database); } @Override - public Observable> createCollection(String databaseLink, + public Flux> createCollection(String databaseLink, DocumentCollection collection, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> this.createCollectionInternal(databaseLink, collection, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> createCollectionInternal(String databaseLink, + private Flux> createCollectionInternal(String databaseLink, DocumentCollection collection, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(databaseLink)) { @@ -628,18 +625,18 @@ private Observable> createCollectionInterna }); } catch (Exception e) { logger.debug("Failure in creating a collection. due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> replaceCollection(DocumentCollection collection, + public Flux> replaceCollection(DocumentCollection collection, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceCollectionInternal(collection, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> replaceCollectionInternal(DocumentCollection collection, + private Flux> replaceCollectionInternal(DocumentCollection collection, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (collection == null) { @@ -673,18 +670,18 @@ private Observable> replaceCollectionIntern } catch (Exception e) { logger.debug("Failure in replacing a collection. due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> deleteCollection(String collectionLink, + public Flux> deleteCollection(String collectionLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> deleteCollectionInternal(String collectionLink, + private Flux> deleteCollectionInternal(String collectionLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(collectionLink)) { @@ -705,26 +702,26 @@ private Observable> deleteCollectionInterna } catch (Exception e) { logger.debug("Failure in deleting a collection, due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } - private Observable delete(RxDocumentServiceRequest request) { + private Flux delete(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.DELETE); return getStoreProxy(request).processMessage(request); } - private Observable read(RxDocumentServiceRequest request) { + private Flux read(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.GET); return getStoreProxy(request).processMessage(request); } - Observable readFeed(RxDocumentServiceRequest request) { + Flux readFeed(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.GET); return gatewayProxy.processMessage(request); } - private Observable query(RxDocumentServiceRequest request) { + private Flux query(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.POST); return this.getStoreProxy(request).processMessage(request) .map(response -> { @@ -735,13 +732,13 @@ private Observable query(RxDocumentServiceRequest req } @Override - public Observable> readCollection(String collectionLink, + public Flux> readCollection(String collectionLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readCollectionInternal(collectionLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> readCollectionInternal(String collectionLink, + private Flux> readCollectionInternal(String collectionLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here @@ -766,12 +763,12 @@ private Observable> readCollectionInternal( } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in reading a collection, due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readCollections(String databaseLink, FeedOptions options) { + public Flux> readCollections(String databaseLink, FeedOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); @@ -782,13 +779,13 @@ public Observable> readCollections(String datab } @Override - public Observable> queryCollections(String databaseLink, String query, + public Flux> queryCollections(String databaseLink, String query, FeedOptions options) { return createQuery(databaseLink, new SqlQuerySpec(query), options, DocumentCollection.class, ResourceType.DocumentCollection); } @Override - public Observable> queryCollections(String databaseLink, + public Flux> queryCollections(String databaseLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(databaseLink, querySpec, options, DocumentCollection.class, ResourceType.DocumentCollection); } @@ -922,10 +919,10 @@ private Map getMediaHeaders(MediaOptions options) { return requestHeaders; } - private Single addPartitionKeyInformation(RxDocumentServiceRequest request, Document document, + private Mono addPartitionKeyInformation(RxDocumentServiceRequest request, Document document, RequestOptions options) { - Single collectionObs = this.collectionCache.resolveCollectionAsync(request); + Mono collectionObs = this.collectionCache.resolveCollectionAsync(request); return collectionObs .map(collection -> { addPartitionKeyInformation(request, document, options, collection); @@ -933,8 +930,8 @@ private Single addPartitionKeyInformation(RxDocumentSe }); } - private Single addPartitionKeyInformation(RxDocumentServiceRequest request, Document document, RequestOptions options, - Single collectionObs) { + private Mono addPartitionKeyInformation(RxDocumentServiceRequest request, Document document, RequestOptions options, + Mono collectionObs) { return collectionObs.map(collection -> { addPartitionKeyInformation(request, document, options, collection); @@ -1000,7 +997,7 @@ private static PartitionKeyInternal extractPartitionKeyValueFromDocument( return null; } - private Single getCreateDocumentRequest(String documentCollectionLink, Object document, + private Mono getCreateDocumentRequest(String documentCollectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, OperationType operationType) { if (StringUtils.isEmpty(documentCollectionLink)) { @@ -1025,7 +1022,7 @@ private Single getCreateDocumentRequest(String documen RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, ResourceType.Document, path, typedDocument, requestHeaders, options); - Single collectionObs = this.collectionCache.resolveCollectionAsync(request); + Mono collectionObs = this.collectionCache.resolveCollectionAsync(request); return addPartitionKeyInformation(request, typedDocument, options, collectionObs); } @@ -1095,13 +1092,13 @@ void captureSessionToken(RxDocumentServiceRequest request, RxDocumentServiceResp this.sessionContainer.setSessionToken(request, response.getResponseHeaders()); } - private Observable create(RxDocumentServiceRequest request) { + private Flux create(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.POST); RxStoreModel storeProxy = this.getStoreProxy(request); return storeProxy.processMessage(request); } - private Observable upsert(RxDocumentServiceRequest request) { + private Flux upsert(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.POST); Map headers = request.getHeaders(); @@ -1120,13 +1117,13 @@ private Observable upsert(RxDocumentServiceRequest re ); } - private Observable replace(RxDocumentServiceRequest request) { + private Flux replace(RxDocumentServiceRequest request) { populateHeaders(request, HttpConstants.HttpMethods.PUT); return getStoreProxy(request).processMessage(request); } @Override - public Observable> createDocument(String collectionLink, Object document, + public Flux> createDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { @@ -1137,17 +1134,17 @@ public Observable> createDocument(String collectionLi return ObservableHelper.inlineIfPossibleAsObs(() -> createDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } - private Observable> createDocumentInternal(String collectionLink, Object document, + private Flux> createDocumentInternal(String collectionLink, Object document, RequestOptions options, final boolean disableAutomaticIdGeneration, IDocumentClientRetryPolicy requestRetryPolicy) { try { logger.debug("Creating a Document. collectionLink: [{}]", collectionLink); - Single requestObs = getCreateDocumentRequest(collectionLink, document, + Mono requestObs = getCreateDocumentRequest(collectionLink, document, options, disableAutomaticIdGeneration, OperationType.Create); - Observable responseObservable = requestObs - .toObservable() + Flux responseObservable = requestObs + .flux() .flatMap(req -> { if (requestRetryPolicy != null) { requestRetryPolicy.onBeforeSendRequest(req); @@ -1156,22 +1153,17 @@ private Observable> createDocumentInternal(String col return create(req); }); - Observable> createObservable = - responseObservable - .map(serviceResponse -> { - return toResourceResponse(serviceResponse, Document.class); - }); - - return createObservable; + return responseObservable + .map(serviceResponse -> toResourceResponse(serviceResponse, Document.class)); } catch (Exception e) { logger.debug("Failure in creating a document due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> upsertDocument(String collectionLink, Object document, + public Flux> upsertDocument(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); @@ -1182,15 +1174,15 @@ public Observable> upsertDocument(String collectionLi return ObservableHelper.inlineIfPossibleAsObs(() -> upsertDocumentInternal(collectionLink, document, options, disableAutomaticIdGeneration, finalRetryPolicyInstance), requestRetryPolicy); } - private Observable> upsertDocumentInternal(String collectionLink, Object document, + private Flux> upsertDocumentInternal(String collectionLink, Object document, RequestOptions options, boolean disableAutomaticIdGeneration, IDocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a Document. collectionLink: [{}]", collectionLink); - Observable reqObs = getCreateDocumentRequest(collectionLink, document, - options, disableAutomaticIdGeneration, OperationType.Upsert).toObservable(); + Flux reqObs = getCreateDocumentRequest(collectionLink, document, + options, disableAutomaticIdGeneration, OperationType.Upsert).flux(); - Observable responseObservable = reqObs.flatMap(req -> { + Flux responseObservable = reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(req); } @@ -1201,12 +1193,12 @@ private Observable> upsertDocumentInternal(String col } catch (Exception e) { logger.debug("Failure in upserting a document due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> replaceDocument(String documentLink, Object document, + public Flux> replaceDocument(String documentLink, Object document, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); @@ -1218,7 +1210,7 @@ public Observable> replaceDocument(String documentLin return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(documentLink, document, options, finalRequestRetryPolicy), requestRetryPolicy); } - private Observable> replaceDocumentInternal(String documentLink, Object document, + private Flux> replaceDocumentInternal(String documentLink, Object document, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { @@ -1235,12 +1227,12 @@ private Observable> replaceDocumentInternal(String do } catch (Exception e) { logger.debug("Failure in replacing a document due to [{}]", e.getMessage()); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> replaceDocument(Document document, RequestOptions options) { + public Flux> replaceDocument(Document document, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); if (options == null || options.getPartitionKey() == null) { String collectionLink = document.selfLink(); @@ -1250,7 +1242,7 @@ public Observable> replaceDocument(Document document, return ObservableHelper.inlineIfPossibleAsObs(() -> replaceDocumentInternal(document, options, finalRequestRetryPolicy), requestRetryPolicy); } - private Observable> replaceDocumentInternal(Document document, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { + private Flux> replaceDocumentInternal(Document document, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (document == null) { @@ -1261,11 +1253,11 @@ private Observable> replaceDocumentInternal(Document } catch (Exception e) { logger.debug("Failure in replacing a database due to [{}]", e.getMessage()); - return Observable.error(e); + return Flux.error(e); } } - private Observable> replaceDocumentInternal(String documentLink, Document document, + private Flux> replaceDocumentInternal(String documentLink, Document document, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { if (document == null) { @@ -1280,10 +1272,10 @@ private Observable> replaceDocumentInternal(String do validateResource(document); - Single collectionObs = collectionCache.resolveCollectionAsync(request); - Single requestObs = addPartitionKeyInformation(request, document, options, collectionObs); + Mono collectionObs = collectionCache.resolveCollectionAsync(request); + Mono requestObs = addPartitionKeyInformation(request, document, options, collectionObs); - return requestObs.toObservable().flatMap(req -> { + return requestObs.flux().flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } @@ -1292,12 +1284,12 @@ private Observable> replaceDocumentInternal(String do } @Override - public Observable> deleteDocument(String documentLink, RequestOptions options) { + public Flux> deleteDocument(String documentLink, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteDocumentInternal(documentLink, options, requestRetryPolicy), requestRetryPolicy); } - private Observable> deleteDocumentInternal(String documentLink, RequestOptions options, + private Flux> deleteDocumentInternal(String documentLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { @@ -1310,11 +1302,11 @@ private Observable> deleteDocumentInternal(String doc RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.Document, path, requestHeaders, options); - Single collectionObs = collectionCache.resolveCollectionAsync(request); + Mono collectionObs = collectionCache.resolveCollectionAsync(request); - Single requestObs = addPartitionKeyInformation(request, null, options, collectionObs); + Mono requestObs = addPartitionKeyInformation(request, null, options, collectionObs); - return requestObs.toObservable().flatMap(req -> { + return requestObs.flux().flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(req); } @@ -1323,17 +1315,17 @@ private Observable> deleteDocumentInternal(String doc } catch (Exception e) { logger.debug("Failure in deleting a document due to [{}]", e.getMessage()); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readDocument(String documentLink, RequestOptions options) { + public Flux> readDocument(String documentLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readDocumentInternal(documentLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> readDocumentInternal(String documentLink, RequestOptions options, + private Flux> readDocumentInternal(String documentLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(documentLink)) { @@ -1346,11 +1338,11 @@ private Observable> readDocumentInternal(String docum RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Document, path, requestHeaders, options); - Single collectionObs = this.collectionCache.resolveCollectionAsync(request); + Mono collectionObs = this.collectionCache.resolveCollectionAsync(request); - Single requestObs = addPartitionKeyInformation(request, null, options, collectionObs); + Mono requestObs = addPartitionKeyInformation(request, null, options, collectionObs); - return requestObs.toObservable().flatMap(req -> { + return requestObs.flux().flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); } @@ -1359,12 +1351,12 @@ private Observable> readDocumentInternal(String docum } catch (Exception e) { logger.debug("Failure in reading a document due to [{}]", e.getMessage()); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readDocuments(String collectionLink, FeedOptions options) { + public Flux> readDocuments(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); @@ -1374,7 +1366,7 @@ public Observable> readDocuments(String collectionLink, F } @Override - public Observable> queryDocuments(String collectionLink, String query, + public Flux> queryDocuments(String collectionLink, String query, FeedOptions options) { return queryDocuments(collectionLink, new SqlQuerySpec(query), options); } @@ -1410,8 +1402,8 @@ public ConsistencyLevel getDesiredConsistencyLevelAsync() { } @Override - public Single executeQueryAsync(RxDocumentServiceRequest request) { - return RxDocumentClientImpl.this.query(request).toSingle(); + public Mono executeQueryAsync(RxDocumentServiceRequest request) { + return RxDocumentClientImpl.this.query(request).single(); } @Override @@ -1421,7 +1413,7 @@ public QueryCompatibilityMode getQueryCompatibilityMode() { } @Override - public Single readFeedAsync(RxDocumentServiceRequest request) { + public Mono readFeedAsync(RxDocumentServiceRequest request) { // TODO Auto-generated method stub return null; } @@ -1429,13 +1421,13 @@ public Single readFeedAsync(RxDocumentServiceRequest } @Override - public Observable> queryDocuments(String collectionLink, SqlQuerySpec querySpec, + public Flux> queryDocuments(String collectionLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(collectionLink, querySpec, options, Document.class, ResourceType.Document); } @Override - public Observable> queryDocumentChangeFeed(final String collectionLink, + public Flux> queryDocumentChangeFeed(final String collectionLink, final ChangeFeedOptions changeFeedOptions) { if (StringUtils.isEmpty(collectionLink)) { @@ -1449,7 +1441,7 @@ public Observable> queryDocumentChangeFeed(final String c } @Override - public Observable> readPartitionKeyRanges(final String collectionLink, + public Flux> readPartitionKeyRanges(final String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { @@ -1499,13 +1491,13 @@ private RxDocumentServiceRequest getUserDefinedFunctionRequest(String collection } @Override - public Observable> createStoredProcedure(String collectionLink, + public Flux> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } - private Observable> createStoredProcedureInternal(String collectionLink, + private Flux> createStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription @@ -1526,18 +1518,18 @@ private Observable> createStoredProcedureInter } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in creating a StoredProcedure due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> upsertStoredProcedure(String collectionLink, + public Flux> upsertStoredProcedure(String collectionLink, StoredProcedure storedProcedure, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertStoredProcedureInternal(collectionLink, storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } - private Observable> upsertStoredProcedureInternal(String collectionLink, + private Flux> upsertStoredProcedureInternal(String collectionLink, StoredProcedure storedProcedure, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription @@ -1558,18 +1550,18 @@ private Observable> upsertStoredProcedureInter } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in upserting a StoredProcedure due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> replaceStoredProcedure(StoredProcedure storedProcedure, + public Flux> replaceStoredProcedure(StoredProcedure storedProcedure, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceStoredProcedureInternal(storedProcedure, options, requestRetryPolicy), requestRetryPolicy); } - private Observable> replaceStoredProcedureInternal(StoredProcedure storedProcedure, + private Flux> replaceStoredProcedureInternal(StoredProcedure storedProcedure, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { @@ -1593,18 +1585,18 @@ private Observable> replaceStoredProcedureInte } catch (Exception e) { logger.debug("Failure in replacing a StoredProcedure due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> deleteStoredProcedure(String storedProcedureLink, + public Flux> deleteStoredProcedure(String storedProcedureLink, RequestOptions options) { IDocumentClientRetryPolicy requestRetryPolicy = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteStoredProcedureInternal(storedProcedureLink, options, requestRetryPolicy), requestRetryPolicy); } - private Observable> deleteStoredProcedureInternal(String storedProcedureLink, + private Flux> deleteStoredProcedureInternal(String storedProcedureLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription @@ -1631,18 +1623,18 @@ private Observable> deleteStoredProcedureInter } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in deleting a StoredProcedure due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readStoredProcedure(String storedProcedureLink, + public Flux> readStoredProcedure(String storedProcedureLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readStoredProcedureInternal(storedProcedureLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> readStoredProcedureInternal(String storedProcedureLink, + private Flux> readStoredProcedureInternal(String storedProcedureLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here @@ -1670,12 +1662,12 @@ private Observable> readStoredProcedureInterna } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in reading a StoredProcedure due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readStoredProcedures(String collectionLink, + public Flux> readStoredProcedures(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { @@ -1687,30 +1679,30 @@ public Observable> readStoredProcedures(String col } @Override - public Observable> queryStoredProcedures(String collectionLink, String query, + public Flux> queryStoredProcedures(String collectionLink, String query, FeedOptions options) { return queryStoredProcedures(collectionLink, new SqlQuerySpec(query), options); } @Override - public Observable> queryStoredProcedures(String collectionLink, + public Flux> queryStoredProcedures(String collectionLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(collectionLink, querySpec, options, StoredProcedure.class, ResourceType.StoredProcedure); } @Override - public Observable executeStoredProcedure(String storedProcedureLink, + public Flux executeStoredProcedure(String storedProcedureLink, Object[] procedureParams) { return this.executeStoredProcedure(storedProcedureLink, null, procedureParams); } @Override - public Observable executeStoredProcedure(String storedProcedureLink, + public Flux executeStoredProcedure(String storedProcedureLink, RequestOptions options, Object[] procedureParams) { return ObservableHelper.inlineIfPossibleAsObs(() -> executeStoredProcedureInternal(storedProcedureLink, options, procedureParams), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } - private Observable executeStoredProcedureInternal(String storedProcedureLink, + private Flux executeStoredProcedureInternal(String storedProcedureLink, RequestOptions options, Object[] procedureParams) { try { @@ -1725,7 +1717,7 @@ private Observable executeStoredProcedureInternal(Strin procedureParams != null ? RxDocumentClientImpl.serializeProcedureParams(procedureParams) : "", requestHeaders, options); - Observable reqObs = addPartitionKeyInformation(request, null, options).toObservable(); + Flux reqObs = addPartitionKeyInformation(request, null, options).flux(); return reqObs.flatMap(req -> create(request) .map(response -> { this.captureSessionToken(request, response); @@ -1734,18 +1726,18 @@ private Observable executeStoredProcedureInternal(Strin } catch (Exception e) { logger.debug("Failure in executing a StoredProcedure due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> createTrigger(String collectionLink, Trigger trigger, + public Flux> createTrigger(String collectionLink, Trigger trigger, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> createTriggerInternal(String collectionLink, Trigger trigger, + private Flux> createTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { @@ -1761,18 +1753,18 @@ private Observable> createTriggerInternal(String colle } catch (Exception e) { logger.debug("Failure in creating a Trigger due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> upsertTrigger(String collectionLink, Trigger trigger, + public Flux> upsertTrigger(String collectionLink, Trigger trigger, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertTriggerInternal(collectionLink, trigger, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> upsertTriggerInternal(String collectionLink, Trigger trigger, + private Flux> upsertTriggerInternal(String collectionLink, Trigger trigger, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { @@ -1788,7 +1780,7 @@ private Observable> upsertTriggerInternal(String colle } catch (Exception e) { logger.debug("Failure in upserting a Trigger due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @@ -1812,12 +1804,12 @@ private RxDocumentServiceRequest getTriggerRequest(String collectionLink, Trigge } @Override - public Observable> replaceTrigger(Trigger trigger, RequestOptions options) { + public Flux> replaceTrigger(Trigger trigger, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceTriggerInternal(trigger, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> replaceTriggerInternal(Trigger trigger, RequestOptions options, + private Flux> replaceTriggerInternal(Trigger trigger, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { @@ -1841,17 +1833,17 @@ private Observable> replaceTriggerInternal(Trigger tri } catch (Exception e) { logger.debug("Failure in replacing a Trigger due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> deleteTrigger(String triggerLink, RequestOptions options) { + public Flux> deleteTrigger(String triggerLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> deleteTriggerInternal(String triggerLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { + private Flux> deleteTriggerInternal(String triggerLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { throw new IllegalArgumentException("triggerLink"); @@ -1871,17 +1863,17 @@ private Observable> deleteTriggerInternal(String trigg } catch (Exception e) { logger.debug("Failure in deleting a Trigger due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readTrigger(String triggerLink, RequestOptions options) { + public Flux> readTrigger(String triggerLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readTriggerInternal(triggerLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> readTriggerInternal(String triggerLink, RequestOptions options, + private Flux> readTriggerInternal(String triggerLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(triggerLink)) { @@ -1902,12 +1894,12 @@ private Observable> readTriggerInternal(String trigger } catch (Exception e) { logger.debug("Failure in reading a Trigger due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readTriggers(String collectionLink, FeedOptions options) { + public Flux> readTriggers(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); @@ -1918,25 +1910,25 @@ public Observable> readTriggers(String collectionLink, Fee } @Override - public Observable> queryTriggers(String collectionLink, String query, + public Flux> queryTriggers(String collectionLink, String query, FeedOptions options) { return queryTriggers(collectionLink, new SqlQuerySpec(query), options); } @Override - public Observable> queryTriggers(String collectionLink, SqlQuerySpec querySpec, + public Flux> queryTriggers(String collectionLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(collectionLink, querySpec, options, Trigger.class, ResourceType.Trigger); } @Override - public Observable> createUserDefinedFunction(String collectionLink, + public Flux> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> createUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> createUserDefinedFunctionInternal(String collectionLink, + private Flux> createUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription @@ -1956,18 +1948,18 @@ private Observable> createUserDefinedFunct } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in creating a UserDefinedFunction due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> upsertUserDefinedFunction(String collectionLink, + public Flux> upsertUserDefinedFunction(String collectionLink, UserDefinedFunction udf, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserDefinedFunctionInternal(collectionLink, udf, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> upsertUserDefinedFunctionInternal(String collectionLink, + private Flux> upsertUserDefinedFunctionInternal(String collectionLink, UserDefinedFunction udf, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription @@ -1987,18 +1979,18 @@ private Observable> upsertUserDefinedFunct } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in upserting a UserDefinedFunction due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> replaceUserDefinedFunction(UserDefinedFunction udf, + public Flux> replaceUserDefinedFunction(UserDefinedFunction udf, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserDefinedFunctionInternal(udf, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, + private Flux> replaceUserDefinedFunctionInternal(UserDefinedFunction udf, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription @@ -2026,18 +2018,18 @@ private Observable> replaceUserDefinedFunc } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in replacing a UserDefinedFunction due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> deleteUserDefinedFunction(String udfLink, + public Flux> deleteUserDefinedFunction(String udfLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> deleteUserDefinedFunctionInternal(String udfLink, + private Flux> deleteUserDefinedFunctionInternal(String udfLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription @@ -2063,18 +2055,18 @@ private Observable> deleteUserDefinedFunct } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in deleting a UserDefinedFunction due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readUserDefinedFunction(String udfLink, + public Flux> readUserDefinedFunction(String udfLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserDefinedFunctionInternal(udfLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> readUserDefinedFunctionInternal(String udfLink, + private Flux> readUserDefinedFunctionInternal(String udfLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { // we are using an observable factory here // observable will be created fresh upon subscription @@ -2100,12 +2092,12 @@ private Observable> readUserDefinedFunctio } catch (Exception e) { // this is only in trace level to capture what's going on logger.debug("Failure in reading a UserDefinedFunction due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readUserDefinedFunctions(String collectionLink, + public Flux> readUserDefinedFunctions(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { @@ -2117,24 +2109,24 @@ public Observable> readUserDefinedFunctions(St } @Override - public Observable> queryUserDefinedFunctions(String collectionLink, + public Flux> queryUserDefinedFunctions(String collectionLink, String query, FeedOptions options) { return queryUserDefinedFunctions(collectionLink, new SqlQuerySpec(query), options); } @Override - public Observable> queryUserDefinedFunctions(String collectionLink, + public Flux> queryUserDefinedFunctions(String collectionLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(collectionLink, querySpec, options, UserDefinedFunction.class, ResourceType.UserDefinedFunction); } @Override - public Observable> readConflict(String conflictLink, RequestOptions options) { + public Flux> readConflict(String conflictLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> readConflictInternal(String conflictLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { + private Flux> readConflictInternal(String conflictLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(conflictLink)) { @@ -2147,7 +2139,7 @@ private Observable> readConflictInternal(String confl RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, ResourceType.Conflict, path, requestHeaders, options); - Observable reqObs = addPartitionKeyInformation(request, null, options).toObservable(); + Flux reqObs = addPartitionKeyInformation(request, null, options).flux(); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { @@ -2158,12 +2150,12 @@ private Observable> readConflictInternal(String confl } catch (Exception e) { logger.debug("Failure in reading a Conflict due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readConflicts(String collectionLink, FeedOptions options) { + public Flux> readConflicts(String collectionLink, FeedOptions options) { if (StringUtils.isEmpty(collectionLink)) { throw new IllegalArgumentException("collectionLink"); @@ -2174,24 +2166,24 @@ public Observable> readConflicts(String collectionLink, F } @Override - public Observable> queryConflicts(String collectionLink, String query, + public Flux> queryConflicts(String collectionLink, String query, FeedOptions options) { return queryConflicts(collectionLink, new SqlQuerySpec(query), options); } @Override - public Observable> queryConflicts(String collectionLink, SqlQuerySpec querySpec, + public Flux> queryConflicts(String collectionLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(collectionLink, querySpec, options, Conflict.class, ResourceType.Conflict); } @Override - public Observable> deleteConflict(String conflictLink, RequestOptions options) { + public Flux> deleteConflict(String conflictLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteConflictInternal(conflictLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> deleteConflictInternal(String conflictLink, RequestOptions options, + private Flux> deleteConflictInternal(String conflictLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { @@ -2205,7 +2197,7 @@ private Observable> deleteConflictInternal(String con RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Delete, ResourceType.Conflict, path, requestHeaders, options); - Observable reqObs = addPartitionKeyInformation(request, null, options).toObservable(); + Flux reqObs = addPartitionKeyInformation(request, null, options).flux(); return reqObs.flatMap(req -> { if (retryPolicyInstance != null) { retryPolicyInstance.onBeforeSendRequest(request); @@ -2216,16 +2208,16 @@ private Observable> deleteConflictInternal(String con } catch (Exception e) { logger.debug("Failure in deleting a Conflict due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> createUser(String databaseLink, User user, RequestOptions options) { + public Flux> createUser(String databaseLink, User user, RequestOptions options) { return ObservableHelper.inlineIfPossibleAsObs(() -> createUserInternal(databaseLink, user, options), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } - private Observable> createUserInternal(String databaseLink, User user, RequestOptions options) { + private Flux> createUserInternal(String databaseLink, User user, RequestOptions options) { try { logger.debug("Creating a User. databaseLink [{}], user id [{}]", databaseLink, user.id()); RxDocumentServiceRequest request = getUserRequest(databaseLink, user, options, OperationType.Create); @@ -2233,17 +2225,17 @@ private Observable> createUserInternal(String databaseLin } catch (Exception e) { logger.debug("Failure in creating a User due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> upsertUser(String databaseLink, User user, RequestOptions options) { + public Flux> upsertUser(String databaseLink, User user, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertUserInternal(databaseLink, user, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> upsertUserInternal(String databaseLink, User user, RequestOptions options, + private Flux> upsertUserInternal(String databaseLink, User user, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { logger.debug("Upserting a User. databaseLink [{}], user id [{}]", databaseLink, user.id()); @@ -2256,7 +2248,7 @@ private Observable> upsertUserInternal(String databaseLin } catch (Exception e) { logger.debug("Failure in upserting a User due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @@ -2280,12 +2272,12 @@ private RxDocumentServiceRequest getUserRequest(String databaseLink, User user, } @Override - public Observable> replaceUser(User user, RequestOptions options) { + public Flux> replaceUser(User user, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replaceUserInternal(user, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> replaceUserInternal(User user, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { + private Flux> replaceUserInternal(User user, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (user == null) { throw new IllegalArgumentException("user"); @@ -2305,17 +2297,17 @@ private Observable> replaceUserInternal(User user, Reques } catch (Exception e) { logger.debug("Failure in replacing a User due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } - public Observable> deleteUser(String userLink, RequestOptions options) { + public Flux> deleteUser(String userLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deleteUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> deleteUserInternal(String userLink, RequestOptions options, + private Flux> deleteUserInternal(String userLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { @@ -2336,16 +2328,16 @@ private Observable> deleteUserInternal(String userLink, R } catch (Exception e) { logger.debug("Failure in deleting a User due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readUser(String userLink, RequestOptions options) { + public Flux> readUser(String userLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readUserInternal(userLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> readUserInternal(String userLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { + private Flux> readUserInternal(String userLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); @@ -2363,12 +2355,12 @@ private Observable> readUserInternal(String userLink, Req } catch (Exception e) { logger.debug("Failure in reading a User due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readUsers(String databaseLink, FeedOptions options) { + public Flux> readUsers(String databaseLink, FeedOptions options) { if (StringUtils.isEmpty(databaseLink)) { throw new IllegalArgumentException("databaseLink"); @@ -2379,23 +2371,23 @@ public Observable> readUsers(String databaseLink, FeedOptions } @Override - public Observable> queryUsers(String databaseLink, String query, FeedOptions options) { + public Flux> queryUsers(String databaseLink, String query, FeedOptions options) { return queryUsers(databaseLink, new SqlQuerySpec(query), options); } @Override - public Observable> queryUsers(String databaseLink, SqlQuerySpec querySpec, + public Flux> queryUsers(String databaseLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(databaseLink, querySpec, options, User.class, ResourceType.User); } @Override - public Observable> createPermission(String userLink, Permission permission, + public Flux> createPermission(String userLink, Permission permission, RequestOptions options) { return ObservableHelper.inlineIfPossibleAsObs(() -> createPermissionInternal(userLink, permission, options), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } - private Observable> createPermissionInternal(String userLink, Permission permission, + private Flux> createPermissionInternal(String userLink, Permission permission, RequestOptions options) { try { @@ -2406,18 +2398,18 @@ private Observable> createPermissionInternal(String } catch (Exception e) { logger.debug("Failure in creating a Permission due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> upsertPermission(String userLink, Permission permission, + public Flux> upsertPermission(String userLink, Permission permission, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> upsertPermissionInternal(userLink, permission, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> upsertPermissionInternal(String userLink, Permission permission, + private Flux> upsertPermissionInternal(String userLink, Permission permission, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { @@ -2432,7 +2424,7 @@ private Observable> upsertPermissionInternal(String } catch (Exception e) { logger.debug("Failure in upserting a Permission due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @@ -2456,12 +2448,12 @@ private RxDocumentServiceRequest getPermissionRequest(String userLink, Permissio } @Override - public Observable> replacePermission(Permission permission, RequestOptions options) { + public Flux> replacePermission(Permission permission, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> replacePermissionInternal(permission, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> replacePermissionInternal(Permission permission, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { + private Flux> replacePermissionInternal(Permission permission, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (permission == null) { throw new IllegalArgumentException("permission"); @@ -2482,17 +2474,17 @@ private Observable> replacePermissionInternal(Permi } catch (Exception e) { logger.debug("Failure in replacing a Permission due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> deletePermission(String permissionLink, RequestOptions options) { + public Flux> deletePermission(String permissionLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> deletePermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> deletePermissionInternal(String permissionLink, RequestOptions options, + private Flux> deletePermissionInternal(String permissionLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance) { try { @@ -2513,17 +2505,17 @@ private Observable> deletePermissionInternal(String } catch (Exception e) { logger.debug("Failure in deleting a Permission due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readPermission(String permissionLink, RequestOptions options) { + public Flux> readPermission(String permissionLink, RequestOptions options) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readPermissionInternal(permissionLink, options, retryPolicyInstance), retryPolicyInstance); } - private Observable> readPermissionInternal(String permissionLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance ) { + private Flux> readPermissionInternal(String permissionLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance ) { try { if (StringUtils.isEmpty(permissionLink)) { throw new IllegalArgumentException("permissionLink"); @@ -2541,12 +2533,12 @@ private Observable> readPermissionInternal(String p } catch (Exception e) { logger.debug("Failure in reading a Permission due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readPermissions(String userLink, FeedOptions options) { + public Flux> readPermissions(String userLink, FeedOptions options) { if (StringUtils.isEmpty(userLink)) { throw new IllegalArgumentException("userLink"); @@ -2557,23 +2549,23 @@ public Observable> readPermissions(String userLink, Fee } @Override - public Observable> queryPermissions(String userLink, String query, + public Flux> queryPermissions(String userLink, String query, FeedOptions options) { return queryPermissions(userLink, new SqlQuerySpec(query), options); } @Override - public Observable> queryPermissions(String userLink, SqlQuerySpec querySpec, + public Flux> queryPermissions(String userLink, SqlQuerySpec querySpec, FeedOptions options) { return createQuery(userLink, querySpec, options, Permission.class, ResourceType.Permission); } @Override - public Observable> replaceOffer(Offer offer) { + public Flux> replaceOffer(Offer offer) { return ObservableHelper.inlineIfPossibleAsObs(() -> replaceOfferInternal(offer), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } - private Observable> replaceOfferInternal(Offer offer) { + private Flux> replaceOfferInternal(Offer offer) { try { if (offer == null) { throw new IllegalArgumentException("offer"); @@ -2588,17 +2580,17 @@ private Observable> replaceOfferInternal(Offer offer) { } catch (Exception e) { logger.debug("Failure in replacing an Offer due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readOffer(String offerLink) { + public Flux> readOffer(String offerLink) { IDocumentClientRetryPolicy retryPolicyInstance = this.resetSessionTokenRetryPolicy.getRequestPolicy(); return ObservableHelper.inlineIfPossibleAsObs(() -> readOfferInternal(offerLink, retryPolicyInstance), retryPolicyInstance); } - private Observable> readOfferInternal(String offerLink, IDocumentClientRetryPolicy retryPolicyInstance) { + private Flux> readOfferInternal(String offerLink, IDocumentClientRetryPolicy retryPolicyInstance) { try { if (StringUtils.isEmpty(offerLink)) { throw new IllegalArgumentException("offerLink"); @@ -2616,17 +2608,17 @@ private Observable> readOfferInternal(String offerLink, } catch (Exception e) { logger.debug("Failure in reading an Offer due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @Override - public Observable> readOffers(FeedOptions options) { + public Flux> readOffers(FeedOptions options) { return readFeed(options, ResourceType.Offer, Offer.class, Utils.joinPath(Paths.OFFERS_PATH_SEGMENT, null)); } - private Observable> readFeedCollectionChild(FeedOptions options, ResourceType resourceType, + private Flux> readFeedCollectionChild(FeedOptions options, ResourceType resourceType, Class klass, String resourceLink) { if (options == null) { options = new FeedOptions(); @@ -2637,7 +2629,7 @@ private Observable> readFeedCollectionChild final FeedOptions finalFeedOptions = options; RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(options.partitionKey()); - Func2 createRequestFunc = (continuationToken, pageSize) -> { + BiFunction createRequestFunc = (continuationToken, pageSize) -> { Map requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); @@ -2648,12 +2640,12 @@ private Observable> readFeedCollectionChild return request; }; - Func1>> executeFunc = request -> { + Function>> executeFunc = request -> { return ObservableHelper.inlineIfPossibleAsObs(() -> { - Single collectionObs = this.collectionCache.resolveCollectionAsync(request); - Single requestObs = this.addPartitionKeyInformation(request, null, requestOptions, collectionObs); + Mono collectionObs = this.collectionCache.resolveCollectionAsync(request); + Mono requestObs = this.addPartitionKeyInformation(request, null, requestOptions, collectionObs); - return requestObs.toObservable().flatMap(req -> this.readFeed(req) + return requestObs.flux().flatMap(req -> this.readFeed(req) .map(response -> toFeedResponsePage(response, klass))); }, this.resetSessionTokenRetryPolicy.getRequestPolicy()); }; @@ -2661,14 +2653,14 @@ private Observable> readFeedCollectionChild return Paginator.getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, klass, maxPageSize); } - private Observable> readFeed(FeedOptions options, ResourceType resourceType, Class klass, String resourceLink) { + private Flux> readFeed(FeedOptions options, ResourceType resourceType, Class klass, String resourceLink) { if (options == null) { options = new FeedOptions(); } int maxPageSize = options.maxItemCount() != null ? options.maxItemCount() : -1; final FeedOptions finalFeedOptions = options; - Func2 createRequestFunc = (continuationToken, pageSize) -> { + BiFunction createRequestFunc = (continuationToken, pageSize) -> { Map requestHeaders = new HashMap<>(); if (continuationToken != null) { requestHeaders.put(HttpConstants.HttpHeaders.CONTINUATION, continuationToken); @@ -2679,7 +2671,7 @@ private Observable> readFeed(FeedOptions op return request; }; - Func1>> executeFunc = request -> { + Function>> executeFunc = request -> { return ObservableHelper.inlineIfPossibleAsObs(() -> readFeed(request).map(response -> toFeedResponsePage(response, klass)), this.resetSessionTokenRetryPolicy.getRequestPolicy()); }; @@ -2688,21 +2680,21 @@ private Observable> readFeed(FeedOptions op } @Override - public Observable> queryOffers(String query, FeedOptions options) { + public Flux> queryOffers(String query, FeedOptions options) { return queryOffers(new SqlQuerySpec(query), options); } @Override - public Observable> queryOffers(SqlQuerySpec querySpec, FeedOptions options) { + public Flux> queryOffers(SqlQuerySpec querySpec, FeedOptions options) { return createQuery(null, querySpec, options, Offer.class, ResourceType.Offer); } @Override - public Observable getDatabaseAccount() { + public Flux getDatabaseAccount() { return ObservableHelper.inlineIfPossibleAsObs(() -> getDatabaseAccountInternal(), this.resetSessionTokenRetryPolicy.getRequestPolicy()); } - private Observable getDatabaseAccountInternal() { + private Flux getDatabaseAccountInternal() { try { logger.debug("Getting Database Account"); RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, @@ -2713,7 +2705,7 @@ private Observable getDatabaseAccountInternal() { } catch (Exception e) { logger.debug("Failure in getting Database Account due to [{}]", e.getMessage(), e); - return Observable.error(e); + return Flux.error(e); } } @@ -2729,10 +2721,10 @@ public RxPartitionKeyRangeCache getPartitionKeyRangeCache() { return partitionKeyRangeCache; } - public Observable getDatabaseAccountFromEndpoint(URI endpoint) { - return Observable.defer(() -> { + public Flux getDatabaseAccountFromEndpoint(URI endpoint) { + return Flux.defer(() -> { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(OperationType.Read, - ResourceType.DatabaseAccount, "", (HashMap) null, (Object) null); + ResourceType.DatabaseAccount, "", null, (Object) null); this.populateHeaders(request, HttpConstants.HttpMethods.GET); request.setEndpointOverride(endpoint); @@ -2821,9 +2813,9 @@ public void close() { LifeCycleUtils.closeQuietly(this.storeClientFactory); try { - this.rxClient.shutdown(); + this.reactorHttpClient.shutdown(); } catch (Exception e) { - logger.warn("Failure in shutting down rxClient", e); + logger.warn("Failure in shutting down reactorHttpClient", e); } } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java index b0af21cb3a3d5..3815b214d5051 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java @@ -42,10 +42,9 @@ import org.apache.commons.lang3.tuple.ImmutablePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import rx.Observable; -import rx.Single; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; -import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -73,24 +72,24 @@ public RxPartitionKeyRangeCache(AsyncDocumentClient client, RxCollectionCache co * @see IPartitionKeyRangeCache#tryLookupAsync(java.lang.STRING, com.azure.data.cosmos.internal.routing.CollectionRoutingMap) */ @Override - public Single tryLookupAsync(String collectionRid, CollectionRoutingMap previousValue, Map properties) { + public Mono tryLookupAsync(String collectionRid, CollectionRoutingMap previousValue, Map properties) { return routingMapCache.getAsync( collectionRid, previousValue, () -> getRoutingMapForCollectionAsync(collectionRid, previousValue, properties)) - .onErrorResumeNext(err -> { + .onErrorResume(err -> { logger.debug("tryLookupAsync on collectionRid {} encountered failure", collectionRid, err); CosmosClientException dce = Utils.as(err, CosmosClientException.class); if (dce != null && Exceptions.isStatusCode(dce, HttpConstants.StatusCodes.NOTFOUND)) { - return Single.just(null); + return Mono.empty(); } - return Single.error(err); + return Mono.error(err); }); } @Override - public Single tryLookupAsync(String collectionRid, CollectionRoutingMap previousValue, boolean forceRefreshCollectionRoutingMap, + public Mono tryLookupAsync(String collectionRid, CollectionRoutingMap previousValue, boolean forceRefreshCollectionRoutingMap, Map properties) { return tryLookupAsync(collectionRid, previousValue, properties); } @@ -99,82 +98,70 @@ public Single tryLookupAsync(String collectionRid, Collect * @see IPartitionKeyRangeCache#tryGetOverlappingRangesAsync(java.lang.STRING, com.azure.data.cosmos.internal.routing.RANGE, boolean) */ @Override - public Single> tryGetOverlappingRangesAsync(String collectionRid, Range range, boolean forceRefresh, + public Mono> tryGetOverlappingRangesAsync(String collectionRid, Range range, boolean forceRefresh, Map properties) { - Single routingMapObs = tryLookupAsync(collectionRid, null, properties); + Mono routingMapObs = tryLookupAsync(collectionRid, null, properties); return routingMapObs.flatMap(routingMap -> { - if (forceRefresh && routingMap != null) { + if (forceRefresh) { logger.debug("tryGetOverlappingRangesAsync with forceRefresh on collectionRid {}", collectionRid); return tryLookupAsync(collectionRid, routingMap, properties); } - return Single.just(routingMap); - - }).map(routingMap -> { - if (routingMap != null) { - // TODO: the routingMap.getOverlappingRanges(range) returns Collection - // maybe we should consider changing to ArrayList to avoid conversion - return new ArrayList<>(routingMap.getOverlappingRanges(range)); - } else { - logger.debug("Routing Map Null for collection: {} for range: {}, forceRefresh:{}", collectionRid, range.toString(), forceRefresh); - return null; - } - }); + return Mono.just(routingMap); + }).switchIfEmpty(Mono.empty()).map(routingMap -> routingMap.getOverlappingRanges(range)).switchIfEmpty(Mono.defer(() -> { + logger.debug("Routing Map Null for collection: {} for range: {}, forceRefresh:{}", collectionRid, range.toString(), forceRefresh); + return Mono.empty(); + })); } /* (non-Javadoc) * @see IPartitionKeyRangeCache#tryGetPartitionKeyRangeByIdAsync(java.lang.STRING, java.lang.STRING, boolean) */ @Override - public Single tryGetPartitionKeyRangeByIdAsync(String collectionResourceId, String partitionKeyRangeId, + public Mono tryGetPartitionKeyRangeByIdAsync(String collectionResourceId, String partitionKeyRangeId, boolean forceRefresh, Map properties) { - Single routingMapObs = tryLookupAsync(collectionResourceId, null, properties); + Mono routingMapObs = tryLookupAsync(collectionResourceId, null, properties); return routingMapObs.flatMap(routingMap -> { if (forceRefresh && routingMap != null) { return tryLookupAsync(collectionResourceId, routingMap, properties); } + return Mono.justOrEmpty(routingMap); - return Single.just(routingMap); - - }).map(routingMap -> { - if (routingMap != null) { - return routingMap.getRangeByPartitionKeyRangeId(partitionKeyRangeId); - } else { - logger.debug("Routing Map Null for collection: {}, PartitionKeyRangeId: {}, forceRefresh:{}", collectionResourceId, partitionKeyRangeId, forceRefresh); - return null; - } - }); + }).switchIfEmpty(Mono.defer(Mono::empty)).map(routingMap -> routingMap.getRangeByPartitionKeyRangeId(partitionKeyRangeId)).switchIfEmpty(Mono.defer(() -> { + logger.debug("Routing Map Null for collection: {}, PartitionKeyRangeId: {}, forceRefresh:{}", collectionResourceId, partitionKeyRangeId, forceRefresh); + return null; + })); } /* (non-Javadoc) * @see IPartitionKeyRangeCache#tryGetRangeByPartitionKeyRangeId(java.lang.STRING, java.lang.STRING) */ @Override - public Single tryGetRangeByPartitionKeyRangeId(String collectionRid, String partitionKeyRangeId, Map properties) { - Single routingMapObs = routingMapCache.getAsync( + public Mono tryGetRangeByPartitionKeyRangeId(String collectionRid, String partitionKeyRangeId, Map properties) { + Mono routingMapObs = routingMapCache.getAsync( collectionRid, null, () -> getRoutingMapForCollectionAsync(collectionRid, null, properties)); return routingMapObs.map(routingMap -> routingMap.getRangeByPartitionKeyRangeId(partitionKeyRangeId)) - .onErrorResumeNext(err -> { + .onErrorResume(err -> { CosmosClientException dce = Utils.as(err, CosmosClientException.class); logger.debug("tryGetRangeByPartitionKeyRangeId on collectionRid {} and partitionKeyRangeId {} encountered failure", collectionRid, partitionKeyRangeId, err); if (dce != null && Exceptions.isStatusCode(dce, HttpConstants.StatusCodes.NOTFOUND)) { - return Single.just(null); + return Mono.empty(); } - return Single.error(dce); + return Mono.error(dce); }); } - private Single getRoutingMapForCollectionAsync( + private Mono getRoutingMapForCollectionAsync( String collectionRid, CollectionRoutingMap previousRoutingMap, Map properties) { @@ -184,7 +171,7 @@ private Single getRoutingMapForCollectionAsync( // here we stick to what main java sdk does, investigate later. - Single> rangesObs = getPartitionKeyRange(collectionRid, false, properties); + Mono> rangesObs = getPartitionKeyRange(collectionRid, false, properties); return rangesObs.flatMap(ranges -> { @@ -210,14 +197,14 @@ private Single getRoutingMapForCollectionAsync( if (routingMap == null) { // RANGE information either doesn't exist or is not complete. - return Single.error(new NotFoundException(String.format("GetRoutingMapForCollectionAsync(collectionRid: {%s}), RANGE information either doesn't exist or is not complete.", collectionRid))); + return Mono.error(new NotFoundException(String.format("GetRoutingMapForCollectionAsync(collectionRid: {%s}), RANGE information either doesn't exist or is not complete.", collectionRid))); } - return Single.just(routingMap); + return Mono.just(routingMap); }); } - private Single> getPartitionKeyRange(String collectionRid, boolean forceRefresh, Map properties) { + private Mono> getPartitionKeyRange(String collectionRid, boolean forceRefresh, Map properties) { RxDocumentServiceRequest request = RxDocumentServiceRequest.create( OperationType.ReadFeed, collectionRid, @@ -226,7 +213,7 @@ private Single> getPartitionKeyRange(String collectionRi ); //this request doesn't actually go to server request.requestContext.resolvedCollectionRid = collectionRid; - Single collectionObs = collectionCache.resolveCollectionAsync(request); + Mono collectionObs = collectionCache.resolveCollectionAsync(request); return collectionObs.flatMap(coll -> { @@ -234,10 +221,9 @@ private Single> getPartitionKeyRange(String collectionRi if (properties != null) { feedOptions.properties(properties); } - Observable> rs = client.readPartitionKeyRanges(coll.selfLink(), feedOptions) + return client.readPartitionKeyRanges(coll.selfLink(), feedOptions) // maxConcurrent = 1 to makes it in the right order - .flatMap(p -> Observable.from(p.results()), 1).toList(); - return rs.toSingle(); + .flatMap(p -> Flux.fromIterable(p.results()), 1).collectList(); }); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java index 3d0fb93b71678..271aaaf299da0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java @@ -39,12 +39,10 @@ import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import rx.Completable; -import rx.Single; +import reactor.core.publisher.Mono; import java.net.URL; import java.util.ArrayList; @@ -52,10 +50,11 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; -import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; +; + public class GlobalAddressResolver implements IAddressResolver { private final static int MaxBackupReadRegions = 3; private final GlobalEndpointManager endpointManager; @@ -70,10 +69,10 @@ public class GlobalAddressResolver implements IAddressResolver { private GatewayAddressCache gatewayAddressCache; private AddressResolver addressResolver; - private CompositeHttpClient httpClient; + private HttpClient httpClient; public GlobalAddressResolver( - CompositeHttpClient httpClient, + HttpClient httpClient, GlobalEndpointManager endpointManager, Protocol protocol, IAuthorizationTokenProvider tokenProvider, @@ -104,25 +103,23 @@ public GlobalAddressResolver( } } - Completable openAsync(DocumentCollection collection) { - Single routingMap = this.routingMapProvider.tryLookupAsync(collection.id(), null, null); - return routingMap.flatMapCompletable(collectionRoutingMap -> { - if (collectionRoutingMap == null) { - return Completable.complete(); - } + Mono openAsync(DocumentCollection collection) { + Mono routingMap = this.routingMapProvider.tryLookupAsync(collection.id(), null, null); + return routingMap.flatMap(collectionRoutingMap -> { List ranges = ((List)collectionRoutingMap.getOrderedPartitionKeyRanges()).stream().map(range -> new PartitionKeyRangeIdentity(collection.resourceId(), range.id())).collect(Collectors.toList()); - List tasks = new ArrayList<>(); + List> tasks = new ArrayList<>(); for (EndpointCache endpointCache : this.addressCacheByEndpoint.values()) { tasks.add(endpointCache.addressCache.openAsync(collection, ranges)); } - return Completable.mergeDelayError(tasks); - }); + // TODO: Not sure if this will work. + return Mono.whenDelayError(tasks); + }).switchIfEmpty(Mono.defer(Mono::empty)); } @Override - public Single resolveAsync(RxDocumentServiceRequest request, boolean forceRefresh) { + public Mono resolveAsync(RxDocumentServiceRequest request, boolean forceRefresh) { IAddressResolver resolver = this.getAddressResolver(request); return resolver.resolveAsync(request, forceRefresh); } @@ -153,10 +150,10 @@ private EndpointCache getOrAddEndpoint(URL endpoint) { List allEndpoints = new ArrayList(this.endpointManager.getWriteEndpoints()); allEndpoints.addAll(this.endpointManager.getReadEndpoints()); Collections.reverse(allEndpoints); - Queue endpoints = new LinkedList<>(allEndpoints); + LinkedList endpoints = new LinkedList<>(allEndpoints); while (this.addressCacheByEndpoint.size() > this.maxEndpoints) { if (endpoints.size() > 0) { - URL dequeueEnpoint = ((LinkedList) endpoints).pop(); + URL dequeueEnpoint = endpoints.pop(); if (this.addressCacheByEndpoint.get(dequeueEnpoint) != null) { this.addressCacheByEndpoint.remove(dequeueEnpoint); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java index b94f12975433e..0dce9b08dc15d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java @@ -54,16 +54,22 @@ public final String getTestName() { @BeforeMethod(alwaysRun = true) public final void setTestName(Method method) { + String testClassAndMethodName = Strings.lenientFormat("%s::%s", + method.getDeclaringClass().getSimpleName(), + method.getName()); - String connectionMode = this.clientBuilder.getConnectionPolicy().connectionMode() == ConnectionMode.DIRECT - ? "Direct " + this.clientBuilder.getConfigs().getProtocol() - : "Gateway"; + if (this.clientBuilder.getConnectionPolicy() != null && this.clientBuilder.getConfigs() != null) { + String connectionMode = this.clientBuilder.getConnectionPolicy().connectionMode() == ConnectionMode.DIRECT + ? "Direct " + this.clientBuilder.getConfigs().getProtocol() + : "Gateway"; - this.testName = Strings.lenientFormat("%s::%s[%s with %s consistency]", - method.getDeclaringClass().getSimpleName(), - method.getName(), - connectionMode, - clientBuilder.getDesiredConsistencyLevel()); + this.testName = Strings.lenientFormat("%s[%s with %s consistency]", + testClassAndMethodName, + connectionMode, + clientBuilder.getDesiredConsistencyLevel()); + } else { + this.testName = testClassAndMethodName; + } } @AfterMethod(alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java index 0c496ab37d9b6..eefb4fa49401a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java @@ -24,79 +24,73 @@ import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.HttpClientFactory; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.Paths; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpClientConfig; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpRequest; import com.azure.data.cosmos.rx.FeedResponseListValidator; import com.azure.data.cosmos.rx.TestConfigurations; import com.azure.data.cosmos.rx.TestSuiteBase; -import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; -import org.apache.commons.io.IOUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import rx.Observable; +import reactor.core.scheduler.Schedulers; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; -import java.util.Map; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; -public class CosmosPartitionKeyTests extends TestSuiteBase { +public final class CosmosPartitionKeyTests extends TestSuiteBase { private final static String NON_PARTITIONED_CONTAINER_ID = "NonPartitionContainer" + UUID.randomUUID().toString(); private final static String NON_PARTITIONED_CONTAINER_DOCUEMNT_ID = "NonPartitionContainer_Document" + UUID.randomUUID().toString(); private CosmosClient client; private CosmosDatabase createdDatabase; - private CosmosClientBuilder clientBuilder; @Factory(dataProvider = "clientBuilders") public CosmosPartitionKeyTests(CosmosClientBuilder clientBuilder) { - this.clientBuilder = clientBuilder; + super(clientBuilder); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws URISyntaxException, IOException { - client = clientBuilder.build(); + assertThat(this.client).isNull(); + client = clientBuilder().build(); createdDatabase = getSharedCosmosDatabase(client); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeDeleteDatabase(createdDatabase); - safeClose(client); + assertThat(this.client).isNotNull(); + this.client.close(); } private void createContainerWithoutPk() throws URISyntaxException, IOException { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); - HttpClientFactory factory = new HttpClientFactory(new Configs()) + HttpClientConfig httpClientConfig = new HttpClientConfig(new Configs()) .withMaxIdleConnectionTimeoutInMillis(connectionPolicy.idleConnectionTimeoutInMillis()) .withPoolSize(connectionPolicy.maxPoolSize()) .withHttpProxy(connectionPolicy.proxy()) .withRequestTimeoutInMillis(connectionPolicy.requestTimeoutInMillis()); - CompositeHttpClient httpClient = factory.toHttpClientBuilder().build(); + HttpClient httpClient = HttpClient.createFixed(httpClientConfig); // CREATE a non partitioned collection using the rest API and older version String resourceId = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.id(); @@ -118,22 +112,10 @@ private void createContainerWithoutPk() throws URISyntaxException, IOException { 0] + "//" + Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.id() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/"; URI uri = new URI(resourceUri); - HttpClientRequest httpRequest = HttpClientRequest.create(HttpMethod.POST, uri.toString()); - - for (Map.Entry entry : headers.entrySet()) { - httpRequest.withHeader(entry.getKey(), entry.getValue()); - } - - httpRequest.withContent(request.getContent()); - - RxClient.ServerInfo serverInfo = new RxClient.ServerInfo(uri.getHost(), uri.getPort()); - - InputStream responseStream = httpClient.submit(serverInfo, httpRequest).flatMap(clientResponse -> { - return toInputStream(clientResponse.getContent()); - }) - .toBlocking().single(); - String createdContainerAsString = IOUtils.readLines(responseStream, "UTF-8").get(0); - assertThat(createdContainerAsString).contains("\"id\":\"" + NON_PARTITIONED_CONTAINER_ID + "\""); + HttpRequest httpRequest = new HttpRequest(HttpMethod.POST, uri, uri.getPort(), new HttpHeaders(headers)); + httpRequest.withBody(request.getContent()); + String body = httpClient.send(httpRequest).block().bodyAsString().block(); + assertThat(body).contains("\"id\":\"" + NON_PARTITIONED_CONTAINER_ID + "\""); // CREATE a document in the non partitioned collection using the rest API and older version resourceId = Paths.DATABASES_PATH_SEGMENT + "/" + createdDatabase.id() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/" + collection.id(); @@ -151,24 +133,14 @@ private void createContainerWithoutPk() throws URISyntaxException, IOException { + createdDatabase.id() + "/" + Paths.COLLECTIONS_PATH_SEGMENT + "/" + collection.id() + "/" + Paths.DOCUMENTS_PATH_SEGMENT + "/"; uri = new URI(resourceUri); - httpRequest = HttpClientRequest.create(HttpMethod.POST, uri.toString()); - - for (Map.Entry entry : headers.entrySet()) { - httpRequest.withHeader(entry.getKey(), entry.getValue()); - } + httpRequest = new HttpRequest(HttpMethod.POST, uri, uri.getPort(), new HttpHeaders(headers)); + httpRequest.withBody(request.getContent()); - httpRequest.withContent(request.getContent()); - - serverInfo = new RxClient.ServerInfo(uri.getHost(), uri.getPort()); - - responseStream = httpClient.submit(serverInfo, httpRequest).flatMap(clientResponse -> { - return toInputStream(clientResponse.getContent()); - }).toBlocking().single(); - String createdItemAsString = IOUtils.readLines(responseStream, "UTF-8").get(0); - assertThat(createdItemAsString).contains("\"id\":\"" + NON_PARTITIONED_CONTAINER_DOCUEMNT_ID + "\""); + body = httpClient.send(httpRequest).block().bodyAsString().block(); + assertThat(body).contains("\"id\":\"" + NON_PARTITIONED_CONTAINER_DOCUEMNT_ID + "\""); } - @Test(groups = { "simple" }, timeOut = 10 * TIMEOUT) + @Test(groups = { "simple" }) public void testNonPartitionedCollectionOperations() throws Exception { createContainerWithoutPk(); CosmosContainer createdContainer = createdDatabase.getContainer(NON_PARTITIONED_CONTAINER_ID); @@ -306,17 +278,4 @@ public void testMultiPartitionCollectionReadDocumentWithNoPk() throws Interrupte validateSuccess(readMono, validator); } - private Observable toInputStream(Observable contentObservable) { - return contentObservable.reduce(new ByteArrayOutputStream(), (out, bb) -> { - try { - bb.readBytes(out, bb.readableBytes()); - return out; - } catch (java.io.IOException e) { - throw new RuntimeException(e); - } - }).map(out -> { - return new ByteArrayInputStream(out.toByteArray()); - }); - } - } diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java index f3e6d41eda935..0080e5ad5a4ee 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java @@ -76,6 +76,8 @@ private Resource getResource(T resourceResponse) { return ((CosmosUserDefinedFunctionResponse)resourceResponse).settings(); } else if (resourceResponse instanceof CosmosUserResponse) { return ((CosmosUserResponse)resourceResponse).settings(); + } else if (resourceResponse instanceof CosmosPermissionResponse) { + return ((CosmosPermissionResponse) resourceResponse).settings(); } return null; } @@ -252,5 +254,28 @@ public void validate(CosmosUserDefinedFunctionResponse resourceResponse) { }); return this; } + + public Builder withPermissionMode(PermissionMode mode) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosPermissionResponse resourceResponse) { + assertThat(resourceResponse.settings().permissionMode()).isEqualTo(mode); + } + }); + return this; + + } + + public Builder withPermissionResourceLink(String resourceLink) { + validators.add(new CosmosResponseValidator() { + + @Override + public void validate(CosmosPermissionResponse resourceResponse) { + assertThat(resourceResponse.settings().resourceLink()).isEqualTo(resourceLink); + } + }); + return this; + } } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java b/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java index 054bbcf8595a6..d26fc1562d70a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java @@ -54,16 +54,22 @@ public final String getTestName() { @BeforeMethod(alwaysRun = true) public final void setTestName(Method method) { + String testClassAndMethodName = Strings.lenientFormat("%s::%s", + method.getDeclaringClass().getSimpleName(), + method.getName()); - String connectionMode = this.clientBuilder.getConnectionPolicy().connectionMode() == ConnectionMode.DIRECT - ? "Direct " + this.clientBuilder.getConfigs().getProtocol() - : "Gateway"; + if (this.clientBuilder.getConnectionPolicy() != null && this.clientBuilder.getConfigs() != null) { + String connectionMode = this.clientBuilder.getConnectionPolicy().connectionMode() == ConnectionMode.DIRECT + ? "Direct " + this.clientBuilder.getConfigs().getProtocol() + : "Gateway"; - this.testName = Strings.lenientFormat("%s::%s[%s with %s consistency]", - method.getDeclaringClass().getSimpleName(), - method.getName(), - connectionMode, - clientBuilder.getDesiredConsistencyLevel()); + this.testName = Strings.lenientFormat("%s[%s with %s consistency]", + testClassAndMethodName, + connectionMode, + clientBuilder.getDesiredConsistencyLevel()); + } else { + this.testName = testClassAndMethodName; + } } @AfterMethod(alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java index 73b0f2fd62d24..061db1e08477c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java @@ -55,13 +55,13 @@ public void barrierBasic() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, resourceType, "/dbs/7mVFAA==/colls/7mVFAP1jpeU=", randomResource, (Map) null); - BarrierRequestHelper.createAsync(request, authTokenProvider, 10l, 10l).toCompletable().await(); + BarrierRequestHelper.createAsync(request, authTokenProvider, 10l, 10l).block(); request = RxDocumentServiceRequest.create(operationType, resourceType, "/dbs/7mVFAA==", randomResource, null); request.setResourceId("3"); try { - BarrierRequestHelper.createAsync(request, authTokenProvider, 10l, 10l).toCompletable().await(); + BarrierRequestHelper.createAsync(request, authTokenProvider, 10l, 10l).block(); } catch (Exception e) { if (!BarrierRequestHelper.isCollectionHeadBarrierRequest(resourceType, operationType)) { fail("Should not fail for non-collection head combinations"); @@ -83,7 +83,7 @@ public void barrierDBFeed() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, resourceType, "/dbs/7mVFAA==/colls/7mVFAP1jpeU=", randomResource, (Map) null); - RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(request, authTokenProvider, 11l, 10l).toBlocking().value(); + RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.HeadFeed); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.Database); @@ -105,7 +105,7 @@ public void barrierDocumentQueryNameBasedRequest() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, resourceType, "/dbs/dbname/colls/collname", randomResource, (Map) null); - RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(request, authTokenProvider, 11l, 10l).toBlocking().value(); + RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.Head); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.DocumentCollection); @@ -127,7 +127,7 @@ public void barrierDocumentReadNameBasedRequest() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, resourceType, "/dbs/dbname/colls/collname", randomResource, (Map) null); - RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(request, authTokenProvider, 11l, 10l).toBlocking().value(); + RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.Head); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.DocumentCollection); @@ -151,7 +151,7 @@ public void barrierDocumentReadRidBasedRequest() { RxDocumentServiceRequest request = RxDocumentServiceRequest.create(operationType, "7mVFAA==", resourceType, (Map) null); - RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(request, authTokenProvider, 11l, 10l).toBlocking().value(); + RxDocumentServiceRequest barrierRequest = BarrierRequestHelper.createAsync(request, authTokenProvider, 11l, 10l).block(); assertThat(barrierRequest.getOperationType()).isEqualTo(OperationType.Head); assertThat(barrierRequest.getResourceType()).isEqualTo(ResourceType.DocumentCollection); diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java index cd90b80b4fba4..fb27309978719 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java @@ -53,7 +53,7 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.lang.reflect.Method; import java.util.ArrayList; @@ -111,7 +111,7 @@ public void executeStoredProc() { storedProcedure.id(UUID.randomUUID().toString()); storedProcedure.setBody("function() {var x = 10;}"); - Observable> createObservable = client + Flux> createObservable = client .createStoredProcedure(getCollectionLink(), storedProcedure, null); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() @@ -130,7 +130,7 @@ public void executeStoredProc() { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey("dummy")); StoredProcedureResponse storedProcedureResponse = client - .executeStoredProcedure(storedProcLink, options, null).toBlocking().single(); + .executeStoredProcedure(storedProcLink, options, null).single().block(); assertThat(storedProcedureResponse.getStatusCode()).isEqualTo(200); @@ -145,7 +145,7 @@ public void executeStoredProc() { public void create() { final Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client.createDocument( + Flux> createObservable = client.createDocument( this.getCollectionLink(), docDefinition, null, false); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() @@ -163,7 +163,7 @@ public void create() { @Test(groups = { "direct" }, timeOut = TIMEOUT) public void read() throws Exception { Document docDefinition = this.getDocumentDefinition(); - Document document = client.createDocument(getCollectionLink(), docDefinition, null, false).toBlocking().single().getResource(); + Document document = client.createDocument(getCollectionLink(), docDefinition, null, false).single().block().getResource(); // give times to replicas to catch up after a write waitIfNeededForReplicasToCatchUp(clientBuilder()); @@ -195,8 +195,8 @@ public void upsert() throws Exception { final Document docDefinition = getDocumentDefinition(); final Document document = client.createDocument(getCollectionLink(), docDefinition, null, false) - .toBlocking() .single() + .block() .getResource(); // give times to replicas to catch up after a write @@ -233,7 +233,7 @@ public void crossPartitionQuery() { documentList.add(docDefinition); } - documentList = bulkInsert(client, getCollectionLink(), documentList).map(ResourceResponse::getResource).toList().toBlocking().single(); + documentList = bulkInsert(client, getCollectionLink(), documentList).map(ResourceResponse::getResource).collectList().single().block(); waitIfNeededForReplicasToCatchUp(clientBuilder()); @@ -241,7 +241,7 @@ public void crossPartitionQuery() { options.enableCrossPartitionQuery(true); options.maxDegreeOfParallelism(-1); options.maxItemCount(100); - Observable> results = client.queryDocuments(getCollectionLink(), "SELECT * FROM r", options); + Flux> results = client.queryDocuments(getCollectionLink(), "SELECT * FROM r", options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(documentList.size()) diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java index 35e6df8a426f4..b6635dfca30ee 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java @@ -31,19 +31,19 @@ import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.HttpClientFactory; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentClientImpl; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.TestSuiteBase; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpClientConfig; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import com.azure.data.cosmos.rx.TestConfigurations; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; +import io.reactivex.subscribers.TestSubscriber; import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; @@ -53,8 +53,7 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Single; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Mono; import java.net.URL; import java.time.Instant; @@ -117,14 +116,14 @@ public void getServerAddressesViaGateway(List partitionKeyRangeIds, protocol, authorizationTokenProvider, null, - getCompositeHttpClient(configs)); + getHttpClient(configs)); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Document, collectionLink + "/docs/", getDocumentDefinition(), new HashMap<>()); - Single> addresses = cache.getServerAddressesViaGatewayAsync( + Mono> addresses = cache.getServerAddressesViaGatewayAsync( req, createdCollection.resourceId(), partitionKeyRangeIds, false); PartitionReplicasAddressesValidator validator = new PartitionReplicasAddressesValidator.Builder() @@ -146,14 +145,14 @@ public void getMasterAddressesViaGatewayAsync(Protocol protocol) throws Exceptio protocol, authorizationTokenProvider, null, - getCompositeHttpClient(configs)); + getHttpClient(configs)); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Database, "/dbs", new Database(), new HashMap<>()); - Single> addresses = cache.getMasterAddressesViaGatewayAsync(req, ResourceType.Database, + Mono> addresses = cache.getMasterAddressesViaGatewayAsync(req, ResourceType.Database, null, "/dbs/", false, false, null); PartitionReplicasAddressesValidator validator = new PartitionReplicasAddressesValidator.Builder() @@ -187,7 +186,7 @@ public void tryGetAddresses_ForDataPartitions(String partitionKeyRangeId, String protocol, authorizationTokenProvider, null, - getCompositeHttpClient(configs)); + getHttpClient(configs)); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Document, @@ -198,11 +197,11 @@ public void tryGetAddresses_ForDataPartitions(String partitionKeyRangeId, String PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, partitionKeyRangeId); boolean forceRefreshPartitionAddresses = false; - Single addressesInfosFromCacheObs = cache.tryGetAddresses(req, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); + Mono addressesInfosFromCacheObs = cache.tryGetAddresses(req, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); ArrayList addressInfosFromCache = Lists.newArrayList(getSuccessResult(addressesInfosFromCacheObs, TIMEOUT)); - Single> masterAddressFromGatewayObs = cache.getServerAddressesViaGatewayAsync(req, + Mono> masterAddressFromGatewayObs = cache.getServerAddressesViaGatewayAsync(req, collectionRid, ImmutableList.of(partitionKeyRangeId), false); List

expectedAddresses = getSuccessResult(masterAddressFromGatewayObs, TIMEOUT); @@ -242,10 +241,10 @@ public void tryGetAddresses_ForDataPartitions_AddressCachedByOpenAsync_NoHttpReq List pkriList = allPartitionKeyRangeIds.stream().map( pkri -> new PartitionKeyRangeIdentity(collectionRid, pkri)).collect(Collectors.toList()); - cache.openAsync(createdCollection, pkriList).await(); + cache.openAsync(createdCollection, pkriList).block(); - assertThat(httpClientWrapper.capturedRequest).asList().hasSize(1); - httpClientWrapper.capturedRequest.clear(); + assertThat(httpClientWrapper.capturedRequests).asList().hasSize(1); + httpClientWrapper.capturedRequests.clear(); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Document, @@ -254,19 +253,19 @@ public void tryGetAddresses_ForDataPartitions_AddressCachedByOpenAsync_NoHttpReq PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, partitionKeyRangeId); boolean forceRefreshPartitionAddresses = false; - Single addressesInfosFromCacheObs = cache.tryGetAddresses(req, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); + Mono addressesInfosFromCacheObs = cache.tryGetAddresses(req, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); ArrayList addressInfosFromCache = Lists.newArrayList(getSuccessResult(addressesInfosFromCacheObs, TIMEOUT)); // no new request is made - assertThat(httpClientWrapper.capturedRequest) + assertThat(httpClientWrapper.capturedRequests) .describedAs("no http request: addresses already cached by openAsync") .asList().hasSize(0); - Single> masterAddressFromGatewayObs = cache.getServerAddressesViaGatewayAsync(req, + Mono> masterAddressFromGatewayObs = cache.getServerAddressesViaGatewayAsync(req, collectionRid, ImmutableList.of(partitionKeyRangeId), false); List
expectedAddresses = getSuccessResult(masterAddressFromGatewayObs, TIMEOUT); - assertThat(httpClientWrapper.capturedRequest) + assertThat(httpClientWrapper.capturedRequests) .describedAs("getServerAddressesViaGatewayAsync will read addresses from gateway") .asList().hasSize(1); @@ -297,10 +296,10 @@ public void tryGetAddresses_ForDataPartitions_ForceRefresh( List pkriList = allPartitionKeyRangeIds.stream().map( pkri -> new PartitionKeyRangeIdentity(collectionRid, pkri)).collect(Collectors.toList()); - cache.openAsync(createdCollection, pkriList).await(); + cache.openAsync(createdCollection, pkriList).block(); - assertThat(httpClientWrapper.capturedRequest).asList().hasSize(1); - httpClientWrapper.capturedRequest.clear(); + assertThat(httpClientWrapper.capturedRequests).asList().hasSize(1); + httpClientWrapper.capturedRequests.clear(); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Document, @@ -308,19 +307,19 @@ public void tryGetAddresses_ForDataPartitions_ForceRefresh( new Database(), new HashMap<>()); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, partitionKeyRangeId); - Single addressesInfosFromCacheObs = cache.tryGetAddresses(req, partitionKeyRangeIdentity, true); + Mono addressesInfosFromCacheObs = cache.tryGetAddresses(req, partitionKeyRangeIdentity, true); ArrayList addressInfosFromCache = Lists.newArrayList(getSuccessResult(addressesInfosFromCacheObs, TIMEOUT)); // no new request is made - assertThat(httpClientWrapper.capturedRequest) + assertThat(httpClientWrapper.capturedRequests) .describedAs("force refresh fetched from gateway") .asList().hasSize(1); - Single> masterAddressFromGatewayObs = cache.getServerAddressesViaGatewayAsync(req, + Mono> masterAddressFromGatewayObs = cache.getServerAddressesViaGatewayAsync(req, collectionRid, ImmutableList.of(partitionKeyRangeId), false); List
expectedAddresses = getSuccessResult(masterAddressFromGatewayObs, TIMEOUT); - assertThat(httpClientWrapper.capturedRequest) + assertThat(httpClientWrapper.capturedRequests) .describedAs("getServerAddressesViaGatewayAsync will read addresses from gateway") .asList().hasSize(2); @@ -354,10 +353,10 @@ public void tryGetAddresses_ForDataPartitions_Suboptimal_Refresh( List pkriList = allPartitionKeyRangeIds.stream().map( pkri -> new PartitionKeyRangeIdentity(collectionRid, pkri)).collect(Collectors.toList()); - origCache.openAsync(createdCollection, pkriList).await(); + origCache.openAsync(createdCollection, pkriList).block(); - assertThat(httpClientWrapper.capturedRequest).asList().hasSize(1); - httpClientWrapper.capturedRequest.clear(); + assertThat(httpClientWrapper.capturedRequests).asList().hasSize(1); + httpClientWrapper.capturedRequests.clear(); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Document, @@ -365,11 +364,11 @@ public void tryGetAddresses_ForDataPartitions_Suboptimal_Refresh( new Database(), new HashMap<>()); PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(collectionRid, partitionKeyRangeId); - Single addressesInfosFromCacheObs = origCache.tryGetAddresses(req, partitionKeyRangeIdentity, true); + Mono addressesInfosFromCacheObs = origCache.tryGetAddresses(req, partitionKeyRangeIdentity, true); ArrayList addressInfosFromCache = Lists.newArrayList(getSuccessResult(addressesInfosFromCacheObs, TIMEOUT)); // no new request is made - assertThat(httpClientWrapper.capturedRequest) + assertThat(httpClientWrapper.capturedRequests) .describedAs("force refresh fetched from gateway") .asList().hasSize(1); @@ -378,7 +377,7 @@ public void tryGetAddresses_ForDataPartitions_Suboptimal_Refresh( final AtomicInteger fetchCounter = new AtomicInteger(0); Mockito.doAnswer(new Answer() { @Override - public Single> answer(InvocationOnMock invocationOnMock) throws Throwable { + public Mono> answer(InvocationOnMock invocationOnMock) throws Throwable { RxDocumentServiceRequest req = invocationOnMock.getArgumentAt(0, RxDocumentServiceRequest.class); String collectionRid = invocationOnMock.getArgumentAt(1, String.class); @@ -388,7 +387,7 @@ public Single> answer(InvocationOnMock invocationOnMock) throws Th int cnt = fetchCounter.getAndIncrement(); if (cnt == 0) { - Single> res = origCache.getServerAddressesViaGatewayAsync(req, + Mono> res = origCache.getServerAddressesViaGatewayAsync(req, collectionRid, partitionKeyRangeIds, forceRefresh); @@ -405,22 +404,22 @@ public Single> answer(InvocationOnMock invocationOnMock) throws Th }).when(spyCache).getServerAddressesViaGatewayAsync(Matchers.any(RxDocumentServiceRequest.class), Matchers.anyString(), Matchers.anyList(), Matchers.anyBoolean()); - httpClientWrapper.capturedRequest.clear(); + httpClientWrapper.capturedRequests.clear(); // force refresh to replace existing with sub-optimal addresses addressesInfosFromCacheObs = spyCache.tryGetAddresses(req, partitionKeyRangeIdentity, true); AddressInformation[] suboptimalAddresses = getSuccessResult(addressesInfosFromCacheObs, TIMEOUT); - assertThat(httpClientWrapper.capturedRequest) + assertThat(httpClientWrapper.capturedRequests) .describedAs("getServerAddressesViaGatewayAsync will read addresses from gateway") .asList().hasSize(1); - httpClientWrapper.capturedRequest.clear(); + httpClientWrapper.capturedRequests.clear(); assertThat(suboptimalAddresses).hasSize(ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize - 1); assertThat(fetchCounter.get()).isEqualTo(1); // no refresh, use cache addressesInfosFromCacheObs = spyCache.tryGetAddresses(req, partitionKeyRangeIdentity, false); suboptimalAddresses = getSuccessResult(addressesInfosFromCacheObs, TIMEOUT); - assertThat(httpClientWrapper.capturedRequest) + assertThat(httpClientWrapper.capturedRequests) .describedAs("getServerAddressesViaGatewayAsync will read addresses from gateway") .asList().hasSize(0); assertThat(suboptimalAddresses).hasSize(ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize - 1); @@ -432,7 +431,7 @@ public Single> answer(InvocationOnMock invocationOnMock) throws Th addressesInfosFromCacheObs = spyCache.tryGetAddresses(req, partitionKeyRangeIdentity, false); AddressInformation[] addresses = getSuccessResult(addressesInfosFromCacheObs, TIMEOUT); assertThat(addresses).hasSize(ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize); - assertThat(httpClientWrapper.capturedRequest) + assertThat(httpClientWrapper.capturedRequests) .describedAs("getServerAddressesViaGatewayAsync will read addresses from gateway") .asList().hasSize(1); assertThat(fetchCounter.get()).isEqualTo(2); @@ -448,7 +447,7 @@ public void tryGetAddresses_ForMasterPartition(Protocol protocol) throws Excepti protocol, authorizationTokenProvider, null, - getCompositeHttpClient(configs)); + getHttpClient(configs)); RxDocumentServiceRequest req = RxDocumentServiceRequest.create(OperationType.Create, ResourceType.Database, @@ -457,11 +456,11 @@ public void tryGetAddresses_ForMasterPartition(Protocol protocol) throws Excepti PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity("M"); boolean forceRefreshPartitionAddresses = false; - Single addressesInfosFromCacheObs = cache.tryGetAddresses(req, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); + Mono addressesInfosFromCacheObs = cache.tryGetAddresses(req, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); ArrayList addressInfosFromCache = Lists.newArrayList(getSuccessResult(addressesInfosFromCacheObs, TIMEOUT)); - Single> masterAddressFromGatewayObs = cache.getMasterAddressesViaGatewayAsync(req, ResourceType.Database, + Mono> masterAddressFromGatewayObs = cache.getMasterAddressesViaGatewayAsync(req, ResourceType.Database, null, "/dbs/", false, false, null); List
expectedAddresses = getSuccessResult(masterAddressFromGatewayObs, TIMEOUT); @@ -508,15 +507,15 @@ public void tryGetAddresses_ForMasterPartition_MasterPartitionAddressAlreadyCach AddressInformation[] expectedAddresses = cache.tryGetAddresses(req, partitionKeyRangeIdentity, forceRefreshPartitionAddresses) - .toBlocking().value(); + .block(); - assertThat(clientWrapper.capturedRequest).asList().hasSize(1); - clientWrapper.capturedRequest.clear(); + assertThat(clientWrapper.capturedRequests).asList().hasSize(1); + clientWrapper.capturedRequests.clear(); TimeUnit.SECONDS.sleep(waitTimeInBetweenAttemptsInSeconds); - Single addressesObs = cache.tryGetAddresses(req, + Mono addressesObs = cache.tryGetAddresses(req, partitionKeyRangeIdentity, forceRefreshPartitionAddresses); @@ -525,7 +524,7 @@ public void tryGetAddresses_ForMasterPartition_MasterPartitionAddressAlreadyCach assertExactlyEqual(actualAddresses, expectedAddresses); // the cache address is used. no new http request is sent - assertThat(clientWrapper.capturedRequest).asList().hasSize(0); + assertThat(clientWrapper.capturedRequests).asList().hasSize(0); } @Test(groups = { "direct" }, timeOut = TIMEOUT) @@ -553,12 +552,12 @@ public void tryGetAddresses_ForMasterPartition_ForceRefresh() throws Exception { AddressInformation[] expectedAddresses = cache.tryGetAddresses(req, partitionKeyRangeIdentity, false) - .toBlocking().value(); + .block(); - assertThat(clientWrapper.capturedRequest).asList().hasSize(1); - clientWrapper.capturedRequest.clear(); + assertThat(clientWrapper.capturedRequests).asList().hasSize(1); + clientWrapper.capturedRequests.clear(); - Single addressesObs = cache.tryGetAddresses(req, + Mono addressesObs = cache.tryGetAddresses(req, partitionKeyRangeIdentity, true); @@ -567,7 +566,7 @@ public void tryGetAddresses_ForMasterPartition_ForceRefresh() throws Exception { assertExactlyEqual(actualAddresses, expectedAddresses); // the cache address is used. no new http request is sent - assertThat(clientWrapper.capturedRequest).asList().hasSize(1); + assertThat(clientWrapper.capturedRequests).asList().hasSize(1); } private static List
removeOneReplica(List
addresses) { @@ -597,7 +596,7 @@ public void tryGetAddresses_SuboptimalMasterPartition_NotStaleEnough_NoRefresh() final AtomicInteger getMasterAddressesViaGatewayAsyncInvocation = new AtomicInteger(0); Mockito.doAnswer(new Answer() { @Override - public Single> answer(InvocationOnMock invocationOnMock) throws Throwable { + public Mono> answer(InvocationOnMock invocationOnMock) throws Throwable { RxDocumentServiceRequest request = invocationOnMock.getArgumentAt(0, RxDocumentServiceRequest.class); ResourceType resourceType = invocationOnMock.getArgumentAt(1, ResourceType.class); @@ -609,7 +608,7 @@ public Single> answer(InvocationOnMock invocationOnMock) throws Th int cnt = getMasterAddressesViaGatewayAsyncInvocation.getAndIncrement(); if (cnt == 0) { - Single> res = origCache.getMasterAddressesViaGatewayAsync( + Mono> res = origCache.getMasterAddressesViaGatewayAsync( request, resourceType, resourceAddress, @@ -646,12 +645,12 @@ public Single> answer(InvocationOnMock invocationOnMock) throws Th AddressInformation[] expectedAddresses = spyCache.tryGetAddresses(req, partitionKeyRangeIdentity, false) - .toBlocking().value(); + .block(); - assertThat(clientWrapper.capturedRequest).asList().hasSize(1); - clientWrapper.capturedRequest.clear(); + assertThat(clientWrapper.capturedRequests).asList().hasSize(1); + clientWrapper.capturedRequests.clear(); - Single addressesObs = spyCache.tryGetAddresses(req, + Mono addressesObs = spyCache.tryGetAddresses(req, partitionKeyRangeIdentity, false); @@ -660,7 +659,7 @@ public Single> answer(InvocationOnMock invocationOnMock) throws Th assertExactlyEqual(actualAddresses, expectedAddresses); // the cache address is used. no new http request is sent - assertThat(clientWrapper.capturedRequest).asList().hasSize(0); + assertThat(clientWrapper.capturedRequests).asList().hasSize(0); Instant end = Instant.now(); assertThat(end.minusSeconds(refreshPeriodInSeconds)).isBefore(start); @@ -687,7 +686,7 @@ public void tryGetAddresses_SuboptimalMasterPartition_Stale_DoRefresh() throws E final AtomicInteger getMasterAddressesViaGatewayAsyncInvocation = new AtomicInteger(0); Mockito.doAnswer(new Answer() { @Override - public Single> answer(InvocationOnMock invocationOnMock) throws Throwable { + public Mono> answer(InvocationOnMock invocationOnMock) throws Throwable { System.out.print("fetch"); @@ -701,7 +700,7 @@ public Single> answer(InvocationOnMock invocationOnMock) throws Th int cnt = getMasterAddressesViaGatewayAsyncInvocation.getAndIncrement(); if (cnt == 0) { - Single> res = origCache.getMasterAddressesViaGatewayAsync( + Mono> res = origCache.getMasterAddressesViaGatewayAsync( request, resourceType, resourceAddress, @@ -737,7 +736,7 @@ public Single> answer(InvocationOnMock invocationOnMock) throws Th AddressInformation[] subOptimalAddresses = spyCache.tryGetAddresses(req, partitionKeyRangeIdentity, false) - .toBlocking().value(); + .block(); assertThat(getMasterAddressesViaGatewayAsyncInvocation.get()).isEqualTo(1); assertThat(subOptimalAddresses).hasSize(ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize - 1); @@ -747,22 +746,22 @@ public Single> answer(InvocationOnMock invocationOnMock) throws Th Instant end = Instant.now(); assertThat(end.minusSeconds(refreshPeriodInSeconds)).isAfter(start); - assertThat(clientWrapper.capturedRequest).asList().hasSize(1); - clientWrapper.capturedRequest.clear(); + assertThat(clientWrapper.capturedRequests).asList().hasSize(1); + clientWrapper.capturedRequests.clear(); - Single addressesObs = spyCache.tryGetAddresses(req, + Mono addressesObs = spyCache.tryGetAddresses(req, partitionKeyRangeIdentity, false); AddressInformation[] actualAddresses = getSuccessResult(addressesObs, TIMEOUT); // the cache address is used. no new http request is sent - assertThat(clientWrapper.capturedRequest).asList().hasSize(1); + assertThat(clientWrapper.capturedRequests).asList().hasSize(1); assertThat(getMasterAddressesViaGatewayAsyncInvocation.get()).isEqualTo(2); assertThat(actualAddresses).hasSize(ServiceConfig.SystemReplicationPolicy.MaxReplicaSetSize); List
fetchedAddresses = origCache.getMasterAddressesViaGatewayAsync(req, ResourceType.Database, - null, "/dbs/", false, false, null).toBlocking().value(); + null, "/dbs/", false, false, null).block(); assertSameAs(ImmutableList.copyOf(actualAddresses), fetchedAddresses); } @@ -798,25 +797,25 @@ public static void assertExactlyEqual(List actual, List T getSuccessResult(Single observable, long timeout) { + public static T getSuccessResult(Mono observable, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - return testSubscriber.getOnNextEvents().get(0); + return testSubscriber.values().get(0); } - public static void validateSuccess(Single> observable, + public static void validateSuccess(Mono> observable, PartitionReplicasAddressesValidator validator, long timeout) { TestSubscriber> testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } @BeforeClass(groups = { "direct" }, timeOut = SETUP_TIMEOUT) @@ -848,14 +847,12 @@ static protected DocumentCollection getCollectionDefinition() { return collectionDefinition; } - private CompositeHttpClient getCompositeHttpClient(Configs configs) { - CompositeHttpClient httpClient = new HttpClientFactory(configs) - .toHttpClientBuilder().build(); - return httpClient; + private HttpClient getHttpClient(Configs configs) { + return HttpClient.createFixed(new HttpClientConfig(configs)); } private HttpClientUnderTestWrapper getHttpClientUnderTestWrapper(Configs configs) { - CompositeHttpClient origHttpClient = getCompositeHttpClient(configs); + HttpClient origHttpClient = getHttpClient(configs); return new HttpClientUnderTestWrapper(origHttpClient); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java index 910f373f6c40d..745835ff61407 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java @@ -30,36 +30,26 @@ import com.azure.data.cosmos.DatabaseAccount; import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; -import com.azure.data.cosmos.internal.SpyClientUnderTestFactory.ClientUnderTest; import com.azure.data.cosmos.internal.TestSuiteBase; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; import com.azure.data.cosmos.rx.TestConfigurations; -import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufUtil; -import io.netty.handler.codec.http.DefaultHttpHeaders; -import io.netty.handler.codec.http.DefaultHttpResponse; -import io.netty.handler.codec.http.HttpHeaders; -import io.netty.handler.codec.http.HttpResponse; -import io.netty.handler.codec.http.HttpResponseStatus; -import io.netty.handler.codec.http.HttpVersion; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import io.reactivex.subscribers.TestSubscriber; import org.apache.commons.io.IOUtils; -import org.mockito.Matchers; import org.mockito.Mockito; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; -import rx.Single; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; import java.net.URI; +import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; @@ -67,8 +57,7 @@ public class GatewayServiceConfigurationReaderTest extends TestSuiteBase { private static final int TIMEOUT = 8000; - private CompositeHttpClient mockHttpClient; - private CompositeHttpClient httpClient; + private HttpClient mockHttpClient; private BaseAuthorizationTokenProvider baseAuthorizationTokenProvider; private ConnectionPolicy connectionPolicy; private GatewayServiceConfigurationReader mockGatewayServiceConfigurationReader; @@ -85,12 +74,11 @@ public GatewayServiceConfigurationReaderTest(Builder clientBuilder) { @BeforeClass(groups = "simple") public void setup() throws Exception { client = clientBuilder().build(); - mockHttpClient = (CompositeHttpClient) Mockito.mock(CompositeHttpClient.class); - - ClientUnderTest clientUnderTest = SpyClientUnderTestFactory.createClientUnderTest(this.clientBuilder()); - httpClient = clientUnderTest.getSpyHttpClient(); + SpyClientUnderTestFactory.ClientUnderTest clientUnderTest = SpyClientUnderTestFactory.createClientUnderTest(this.clientBuilder()); + HttpClient httpClient = clientUnderTest.getSpyHttpClient(); baseAuthorizationTokenProvider = new BaseAuthorizationTokenProvider(TestConfigurations.MASTER_KEY); connectionPolicy = ConnectionPolicy.defaultPolicy(); + mockHttpClient = Mockito.mock(HttpClient.class); mockGatewayServiceConfigurationReader = new GatewayServiceConfigurationReader(new URI(TestConfigurations.HOST), false, TestConfigurations.MASTER_KEY, connectionPolicy, baseAuthorizationTokenProvider, mockHttpClient); @@ -103,6 +91,8 @@ public void setup() throws Exception { databaseAccountJson = IOUtils .toString(getClass().getClassLoader().getResourceAsStream("databaseAccount.json"), "UTF-8"); expectedDatabaseAccount = new DatabaseAccount(databaseAccountJson); + HttpResponse mockResponse = getMockResponse(databaseAccountJson); + Mockito.when(mockHttpClient.send(Mockito.any(HttpRequest.class))).thenReturn(Mono.just(mockResponse)); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) @@ -111,93 +101,74 @@ public void afterClass() { } @Test(groups = "simple") - public void mockInitializeReaderAsync() throws Exception { - - HttpClientResponse mockedResponse = getMockResponse(databaseAccountJson); - - Mockito.when(mockHttpClient.submit(Matchers.any(RxClient.ServerInfo.class), Matchers.any())) - .thenReturn(Observable.just(mockedResponse)); - - Single databaseAccount = mockGatewayServiceConfigurationReader.initializeReaderAsync(); + public void mockInitializeReaderAsync() { + Mono databaseAccount = mockGatewayServiceConfigurationReader.initializeReaderAsync(); validateSuccess(databaseAccount, expectedDatabaseAccount); } @Test(groups = "simple") public void mockInitializeReaderAsyncWithResourceToken() throws Exception { + HttpResponse mockResponse = getMockResponse(databaseAccountJson); + Mockito.when(mockHttpClient.send(Mockito.any(HttpRequest.class))).thenReturn(Mono.just(mockResponse)); + mockGatewayServiceConfigurationReader = new GatewayServiceConfigurationReader(new URI(TestConfigurations.HOST), true, "SampleResourceToken", connectionPolicy, baseAuthorizationTokenProvider, mockHttpClient); - HttpClientResponse mockedResponse = getMockResponse(databaseAccountJson); - - Mockito.when(mockHttpClient.submit(Matchers.any(RxClient.ServerInfo.class), Matchers.any())) - .thenReturn(Observable.just(mockedResponse)); - - Single databaseAccount = mockGatewayServiceConfigurationReader.initializeReaderAsync(); + Mono databaseAccount = mockGatewayServiceConfigurationReader.initializeReaderAsync(); validateSuccess(databaseAccount, expectedDatabaseAccount); } @Test(groups = "simple") public void initializeReaderAsync() { - Single databaseAccount = gatewayServiceConfigurationReader.initializeReaderAsync(); + Mono databaseAccount = gatewayServiceConfigurationReader.initializeReaderAsync(); validateSuccess(databaseAccount); } - public static void validateSuccess(Single observable) { + public static void validateSuccess(Mono observable) { TestSubscriber testSubscriber = new TestSubscriber(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - assertThat(BridgeInternal.getQueryEngineConfiuration(testSubscriber.getOnNextEvents().get(0)).size() > 0).isTrue(); - assertThat(BridgeInternal.getReplicationPolicy(testSubscriber.getOnNextEvents().get(0))).isNotNull(); - assertThat(BridgeInternal.getSystemReplicationPolicy(testSubscriber.getOnNextEvents().get(0))).isNotNull(); + DatabaseAccount databaseAccount = testSubscriber.values().get(0); + assertThat(BridgeInternal.getQueryEngineConfiuration(databaseAccount).size() > 0).isTrue(); + assertThat(BridgeInternal.getReplicationPolicy(databaseAccount)).isNotNull(); + assertThat(BridgeInternal.getSystemReplicationPolicy(databaseAccount)).isNotNull(); } - public static void validateSuccess(Single observable, DatabaseAccount expectedDatabaseAccount) - throws InterruptedException { + public static void validateSuccess(Mono observable, DatabaseAccount expectedDatabaseAccount) { TestSubscriber testSubscriber = new TestSubscriber(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(TIMEOUT, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - assertThat(testSubscriber.getOnNextEvents().get(0).id()).isEqualTo(expectedDatabaseAccount.id()); - assertThat(testSubscriber.getOnNextEvents().get(0).getAddressesLink()) + DatabaseAccount databaseAccount = testSubscriber.values().get(0); + assertThat(databaseAccount.id()).isEqualTo(expectedDatabaseAccount.id()); + assertThat(databaseAccount.getAddressesLink()) .isEqualTo(expectedDatabaseAccount.getAddressesLink()); - assertThat(testSubscriber.getOnNextEvents().get(0).getWritableLocations().iterator().next().getEndpoint()) + assertThat(databaseAccount.getWritableLocations().iterator().next().getEndpoint()) .isEqualTo(expectedDatabaseAccount.getWritableLocations().iterator().next().getEndpoint()); - assertThat(BridgeInternal.getSystemReplicationPolicy(testSubscriber.getOnNextEvents().get(0)).getMaxReplicaSetSize()) + assertThat(BridgeInternal.getSystemReplicationPolicy(databaseAccount).getMaxReplicaSetSize()) .isEqualTo(BridgeInternal.getSystemReplicationPolicy(expectedDatabaseAccount).getMaxReplicaSetSize()); - assertThat(BridgeInternal.getSystemReplicationPolicy(testSubscriber.getOnNextEvents().get(0)).getMaxReplicaSetSize()) + assertThat(BridgeInternal.getSystemReplicationPolicy(databaseAccount).getMaxReplicaSetSize()) .isEqualTo(BridgeInternal.getSystemReplicationPolicy(expectedDatabaseAccount).getMaxReplicaSetSize()); - assertThat(BridgeInternal.getQueryEngineConfiuration(testSubscriber.getOnNextEvents().get(0))) + assertThat(BridgeInternal.getQueryEngineConfiuration(databaseAccount)) .isEqualTo(BridgeInternal.getQueryEngineConfiuration(expectedDatabaseAccount)); } - private HttpClientResponse getMockResponse(String databaseAccountJson) { - HttpClientResponse resp = Mockito.mock(HttpClientResponse.class); - Mockito.doReturn(HttpResponseStatus.valueOf(200)).when(resp).getStatus(); - Mockito.doReturn(Observable.just(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, databaseAccountJson))) - .when(resp).getContent(); - - HttpHeaders httpHeaders = new DefaultHttpHeaders(); - DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, - HttpResponseStatus.valueOf(200), httpHeaders); - - try { - Constructor constructor = HttpResponseHeaders.class - .getDeclaredConstructor(HttpResponse.class); - constructor.setAccessible(true); - HttpResponseHeaders httpResponseHeaders = constructor.newInstance(httpResponse); - Mockito.doReturn(httpResponseHeaders).when(resp).getHeaders(); - - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException - | NoSuchMethodException | SecurityException e) { - throw new IllegalStateException("Failed to instantiate class object.", e); - } - return resp; + private HttpResponse getMockResponse(String databaseAccountJson) { + HttpResponse httpResponse = Mockito.mock(HttpResponse.class); + Mockito.doReturn(200).when(httpResponse).statusCode(); + Mockito.doReturn(Flux.just(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, databaseAccountJson))) + .when(httpResponse).body(); + Mockito.doReturn(Mono.just(databaseAccountJson)) + .when(httpResponse).bodyAsString(StandardCharsets.UTF_8); + + Mockito.doReturn(new HttpHeaders()).when(httpResponse).headers(); + return httpResponse; } } \ No newline at end of file diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetryTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetryTest.java deleted file mode 100644 index 0f42898f0b14e..0000000000000 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConnectionPoolExhaustedRetryTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.azure.data.cosmos.internal; - -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.RetryOptions; -import io.reactivex.netty.client.PoolExhaustedException; -import org.mockito.Mockito; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.net.URL; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ConnectionPoolExhaustedRetryTest { - private static final int TIMEOUT = 10000; - - @DataProvider(name = "exceptionProvider") - public Object[][] exceptionProvider() { - return new Object[][]{ - {Mockito.mock(PoolExhaustedException.class)}, - {new CosmosClientException(-1, Mockito.mock(PoolExhaustedException.class))}, - }; - } - - @Test(groups = {"unit"}, timeOut = TIMEOUT, dataProvider = "exceptionProvider") - public void retryOnConnectionPoolExhausted(Exception exception) throws Exception { - GlobalEndpointManager globalEndpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(new URL("http://localhost")).when(globalEndpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); - ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(globalEndpointManager, false, Mockito.mock(RetryOptions.class)); - - clientRetryPolicy.onBeforeSendRequest(Mockito.mock(RxDocumentServiceRequest.class)); - IRetryPolicy.ShouldRetryResult shouldRetryResult = clientRetryPolicy.shouldRetry(exception).toBlocking().value(); - assertThat(shouldRetryResult.shouldRetry).isTrue(); - assertThat(shouldRetryResult.backOffTime).isGreaterThanOrEqualTo(ConnectionPoolExhaustedRetry.RETRY_WAIT_TIME); - - Mockito.verify(globalEndpointManager, Mockito.times(1)).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); - Mockito.verify(globalEndpointManager, Mockito.times(1)).CanUseMultipleWriteLocations(Mockito.any(RxDocumentServiceRequest.class)); - Mockito.verifyNoMoreInteractions(globalEndpointManager); - } - - @Test(groups = {"unit"}, timeOut = TIMEOUT, dataProvider = "exceptionProvider") - public void retryOnConnectionPoolExhausted_Exhausted(Exception exception) throws Exception { - GlobalEndpointManager globalEndpointManager = Mockito.mock(GlobalEndpointManager.class); - Mockito.doReturn(new URL("http://localhost")).when(globalEndpointManager).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); - ClientRetryPolicy clientRetryPolicy = new ClientRetryPolicy(globalEndpointManager, false, Mockito.mock(RetryOptions.class)); - - clientRetryPolicy.onBeforeSendRequest(Mockito.mock(RxDocumentServiceRequest.class)); - for (int i = 0; i < ConnectionPoolExhaustedRetry.MAX_RETRY_COUNT; i++) { - IRetryPolicy.ShouldRetryResult shouldRetryResult = clientRetryPolicy.shouldRetry(exception).toBlocking().value(); - assertThat(shouldRetryResult.shouldRetry).isTrue(); - assertThat(shouldRetryResult.backOffTime).isGreaterThanOrEqualTo(ConnectionPoolExhaustedRetry.RETRY_WAIT_TIME); - } - - IRetryPolicy.ShouldRetryResult shouldRetryResult = clientRetryPolicy.shouldRetry(exception).toBlocking().value(); - assertThat(shouldRetryResult.shouldRetry).isFalse(); - assertThat(shouldRetryResult.backOffTime).isNull(); - // no interaction with global endpoint manager - Mockito.verify(globalEndpointManager, Mockito.times(1)).resolveServiceEndpoint(Mockito.any(RxDocumentServiceRequest.class)); - Mockito.verify(globalEndpointManager, Mockito.times(1)).CanUseMultipleWriteLocations(Mockito.any(RxDocumentServiceRequest.class)); - Mockito.verifyNoMoreInteractions(globalEndpointManager); - } -} diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java index 67960aeebf1b6..75972cde51fef 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java @@ -40,7 +40,7 @@ import com.azure.data.cosmos.rx.TestConfigurations; import org.testng.SkipException; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.UUID; @@ -276,19 +276,20 @@ private void validateSubstatusCodeOnNotFoundExceptionInSessionReadAsync(boolean partitionKeyDefinition.paths(paths); documentCollection.setPartitionKey(partitionKeyDefinition); - DocumentCollection collection = client.createCollection(createdDatabase.selfLink(), documentCollection, null).toBlocking().first().getResource(); + DocumentCollection collection = client.createCollection(createdDatabase.selfLink(), documentCollection + , null).blockFirst().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey("1")); Document documentDefinition = new Document(); documentDefinition.id("1"); - Document document = client.createDocument(collection.selfLink(), documentDefinition, requestOptions, false).toBlocking().first().getResource(); + Document document = client.createDocument(collection.selfLink(), documentDefinition, requestOptions, false).blockFirst().getResource(); - Observable> deleteObservable = client.deleteDocument(document.selfLink(), requestOptions); + Flux> deleteObservable = client.deleteDocument(document.selfLink(), requestOptions); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .nullResource().build(); validateSuccess(deleteObservable, validator); - Observable> readObservable = client.readDocument(document.selfLink(), requestOptions); + Flux> readObservable = client.readDocument(document.selfLink(), requestOptions); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().unknownSubStatusCode().build(); validateFailure(readObservable, notFoundValidator); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java index 24ba11254e8aa..f472bed820437 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java @@ -40,9 +40,8 @@ import com.azure.data.cosmos.rx.TestConfigurations; import org.apache.commons.lang3.Range; import org.testng.annotations.Test; -import rx.Completable; -import rx.Observable; -import rx.functions.Action1; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.List; @@ -66,7 +65,8 @@ public void validateReadSessionOnAsyncReplication() throws InterruptedException .withConnectionPolicy(connectionPolicy) .withConsistencyLevel(ConsistencyLevel.SESSION).build(); - Document document = this.initClient.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, false).toBlocking().first().getResource(); + Document document = this.initClient.createDocument(createdCollection.selfLink(), getDocumentDefinition(), + null, false).blockFirst().getResource(); Thread.sleep(5000);//WaitForServerReplication boolean readLagging = this.validateReadSession(document); //assertThat(readLagging).isTrue(); //Will fail if batch repl is turned off @@ -86,7 +86,8 @@ public void validateWriteSessionOnAsyncReplication() throws InterruptedException .withConnectionPolicy(connectionPolicy) .withConsistencyLevel(ConsistencyLevel.SESSION).build(); - Document document = this.initClient.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, false).toBlocking().first().getResource(); + Document document = this.initClient.createDocument(createdCollection.selfLink(), getDocumentDefinition(), + null, false).blockFirst().getResource(); Thread.sleep(5000);//WaitForServerReplication boolean readLagging = this.validateWriteSession(document); //assertThat(readLagging).isTrue(); //Will fail if batch repl is turned off @@ -195,12 +196,13 @@ public void validateNoChargeOnFailedSessionRead() throws Exception { .build(); try { // CREATE collection - DocumentCollection parentResource = writeClient.createCollection(createdDatabase.selfLink(), getCollectionDefinition(), null).toBlocking().first().getResource(); + DocumentCollection parentResource = writeClient.createCollection(createdDatabase.selfLink(), + getCollectionDefinition(), null).blockFirst().getResource(); // Document to lock pause/resume clients Document documentDefinition = getDocumentDefinition(); documentDefinition.id("test" + documentDefinition.id()); - ResourceResponse childResource = writeClient.createDocument(parentResource.selfLink(), documentDefinition, null, true).toBlocking().first(); + ResourceResponse childResource = writeClient.createDocument(parentResource.selfLink(), documentDefinition, null, true).blockFirst(); logger.info("Created {} child resource", childResource.getResource().resourceId()); String token = childResource.getSessionToken().split(":")[0] + ":" + this.createSessionToken(SessionTokenHelper.parse(childResource.getSessionToken()), 100000000).convertToString(); @@ -209,7 +211,7 @@ public void validateNoChargeOnFailedSessionRead() throws Exception { feedOptions.partitionKey(new PartitionKey(PartitionKeyInternal.Empty.toJson())); feedOptions.sessionToken(token); FailureValidator validator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.NOTFOUND).subStatusCode(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE).build(); - Observable> feedObservable = readSecondaryClient.readDocuments(parentResource.selfLink(), feedOptions); + Flux> feedObservable = readSecondaryClient.readDocuments(parentResource.selfLink(), feedOptions); validateQueryFailure(feedObservable, validator); } finally { safeClose(writeClient); @@ -228,7 +230,7 @@ public void validateStrongReadOnOldDocument() { // Note that we need multiple CONSISTENCY_TEST_TIMEOUT // SEE: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 - @Test(groups = {"direct"}, timeOut = 2 * CONSISTENCY_TEST_TIMEOUT) + @Test(groups = {"direct"}, timeOut = 4 * CONSISTENCY_TEST_TIMEOUT) public void validateSessionTokenAsync() { // Validate that document query never fails // with NotFoundException @@ -248,54 +250,51 @@ public void validateSessionTokenAsync() { .build(); try { - Document lastDocument = client.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, true) - .toBlocking() - .first() - .getResource(); - - Completable task1 = ParallelAsync.forEachAsync(Range.between(0, 1000), 5, new Action1() { - @Override - public void call(Integer index) { - client.createDocument(createdCollection.selfLink(), documents.get(index % documents.size()), null, true).toBlocking().first(); - } - }); - - Completable task2 = ParallelAsync.forEachAsync(Range.between(0, 1000), 5, new Action1() { - @Override - public void call(Integer index) { - try { - FeedOptions feedOptions = new FeedOptions(); - feedOptions.enableCrossPartitionQuery(true); - FeedResponse queryResponse = client.queryDocuments(createdCollection.selfLink(), "SELECT * FROM c WHERE c.Id = 'foo'", feedOptions).toBlocking().first(); - String lsnHeaderValue = queryResponse.responseHeaders().get(WFConstants.BackendHeaders.LSN); - long lsn = Long.valueOf(lsnHeaderValue); - String sessionTokenHeaderValue = queryResponse.responseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); - ISessionToken sessionToken = SessionTokenHelper.parse(sessionTokenHeaderValue); - logger.info("SESSION Token = {}, LSN = {}", sessionToken.convertToString(), lsn); - assertThat(lsn).isEqualTo(sessionToken.getLSN()); - } catch (Exception ex) { - CosmosClientException clientException = (CosmosClientException) ex.getCause(); - if (clientException.statusCode() != 0) { - if (clientException.statusCode() == HttpConstants.StatusCodes.REQUEST_TIMEOUT) { - // ignore - } else if (clientException.statusCode() == HttpConstants.StatusCodes.NOTFOUND) { - String lsnHeaderValue = clientException.responseHeaders().get(WFConstants.BackendHeaders.LSN); - long lsn = Long.valueOf(lsnHeaderValue); - String sessionTokenHeaderValue = clientException.responseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); - ISessionToken sessionToken = SessionTokenHelper.parse(sessionTokenHeaderValue); - - logger.info("SESSION Token = {}, LSN = {}", sessionToken.convertToString(), lsn); - assertThat(lsn).isEqualTo(sessionToken.getLSN()); - } else { - throw ex; - } + Document lastDocument = client.createDocument(createdCollection.selfLink(), getDocumentDefinition(), + null, true) + .blockFirst() + .getResource(); + + Mono task1 = ParallelAsync.forEachAsync(Range.between(0, 1000), 5, index -> client.createDocument(createdCollection.selfLink(), documents.get(index % documents.size()), + null, true) + .blockFirst()); + + Mono task2 = ParallelAsync.forEachAsync(Range.between(0, 1000), 5, index -> { + try { + FeedOptions feedOptions = new FeedOptions(); + feedOptions.enableCrossPartitionQuery(true); + FeedResponse queryResponse = client.queryDocuments(createdCollection.selfLink(), + "SELECT * FROM c WHERE c.Id = " + + "'foo'", feedOptions) + .blockFirst(); + String lsnHeaderValue = queryResponse.responseHeaders().get(WFConstants.BackendHeaders.LSN); + long lsn = Long.valueOf(lsnHeaderValue); + String sessionTokenHeaderValue = queryResponse.responseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); + ISessionToken sessionToken = SessionTokenHelper.parse(sessionTokenHeaderValue); + logger.info("SESSION Token = {}, LSN = {}", sessionToken.convertToString(), lsn); + assertThat(lsn).isEqualTo(sessionToken.getLSN()); + } catch (Exception ex) { + CosmosClientException clientException = (CosmosClientException) ex.getCause(); + if (clientException.statusCode() != 0) { + if (clientException.statusCode() == HttpConstants.StatusCodes.REQUEST_TIMEOUT) { + // ignore + } else if (clientException.statusCode() == HttpConstants.StatusCodes.NOTFOUND) { + String lsnHeaderValue = clientException.responseHeaders().get(WFConstants.BackendHeaders.LSN); + long lsn = Long.valueOf(lsnHeaderValue); + String sessionTokenHeaderValue = clientException.responseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); + ISessionToken sessionToken = SessionTokenHelper.parse(sessionTokenHeaderValue); + + logger.info("SESSION Token = {}, LSN = {}", sessionToken.convertToString(), lsn); + assertThat(lsn).isEqualTo(sessionToken.getLSN()); } else { throw ex; } + } else { + throw ex; } } }); - Completable.mergeDelayError(task1, task2).await(); + Mono.whenDelayError(task1, task2).block(); } finally { safeClose(client); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java index 7eef6c9b585a4..a54430f7d4f5c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java @@ -52,7 +52,7 @@ import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; -import rx.Observable; +import reactor.core.publisher.Flux; import java.lang.reflect.Constructor; import java.lang.reflect.Field; @@ -88,15 +88,15 @@ void validateStrongConsistency(Resource resourceToWorkWith) throws Exception { Thread.sleep(1000); //Timestamp is in granularity of seconds. Resource updatedResource = null; if (resourceToWorkWith instanceof User) { - updatedResource = this.writeClient.upsertUser(createdDatabase.selfLink(), (User) writeResource, null).toBlocking().first().getResource(); + updatedResource = this.writeClient.upsertUser(createdDatabase.selfLink(), (User) writeResource, null).blockFirst().getResource(); } else if (resourceToWorkWith instanceof Document) { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(resourceToWorkWith.get("mypk"))); - updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), (Document) writeResource, options, false).toBlocking().first().getResource(); + updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), (Document) writeResource, options, false).blockFirst().getResource(); } assertThat(updatedResource.timestamp().isAfter(sourceTimestamp)).isTrue(); - User readResource = this.readClient.readUser(resourceToWorkWith.selfLink(), null).toBlocking().first().getResource(); + User readResource = this.readClient.readUser(resourceToWorkWith.selfLink(), null).blockFirst().getResource(); assertThat(updatedResource.timestamp().equals(readResource.timestamp())); } } @@ -106,13 +106,13 @@ void validateConsistentLSN() { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentDefinition.get("mypk"))); Document document = createDocument(this.writeClient, createdDatabase.id(), createdCollection.id(), documentDefinition); - ResourceResponse response = this.writeClient.deleteDocument(document.selfLink(), options).toBlocking().single(); + ResourceResponse response = this.writeClient.deleteDocument(document.selfLink(), options).single().block(); assertThat(response.getStatusCode()).isEqualTo(204); long quorumAckedLSN = Long.parseLong((String) response.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); assertThat(quorumAckedLSN > 0).isTrue(); FailureValidator validator = new FailureValidator.Builder().statusCode(404).lsnGreaterThan(quorumAckedLSN).build(); - Observable> readObservable = this.readClient.readDocument(document.selfLink(), options); + Flux> readObservable = this.readClient.readDocument(document.selfLink(), options); validateFailure(readObservable, validator); } @@ -121,14 +121,14 @@ void validateConsistentLSNAndQuorumAckedLSN() { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentDefinition.get("mypk"))); Document document = createDocument(this.writeClient, createdDatabase.id(), createdCollection.id(), documentDefinition); - ResourceResponse response = this.writeClient.deleteDocument(document.selfLink(), options).toBlocking().single(); + ResourceResponse response = this.writeClient.deleteDocument(document.selfLink(), options).single().block(); assertThat(response.getStatusCode()).isEqualTo(204); long quorumAckedLSN = Long.parseLong((String) response.getResponseHeaders().get(WFConstants.BackendHeaders.QUORUM_ACKED_LSN)); assertThat(quorumAckedLSN > 0).isTrue(); FailureValidator validator = new FailureValidator.Builder().statusCode(404).lsnGreaterThanEqualsTo(quorumAckedLSN).exceptionQuorumAckedLSNInNotNull().build(); - Observable> readObservable = this.readClient.deleteDocument(document.selfLink(), options); + Flux> readObservable = this.readClient.deleteDocument(document.selfLink(), options); validateFailure(readObservable, validator); } @@ -172,10 +172,10 @@ void validateStrongConsistency(Document documentToWorkWith) throws InterruptedEx Thread.sleep(1000);//Timestamp is in granularity of seconds. RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentToWorkWith.get("mypk"))); - Document updatedDocument = this.writeClient.replaceDocument(writeDocument, options).toBlocking().first().getResource(); + Document updatedDocument = this.writeClient.replaceDocument(writeDocument, options).blockFirst().getResource(); assertThat(updatedDocument.timestamp().isAfter(sourceTimestamp)).isTrue(); - Document readDocument = this.readClient.readDocument(documentToWorkWith.selfLink(), options).toBlocking().first().getResource(); + Document readDocument = this.readClient.readDocument(documentToWorkWith.selfLink(), options).blockFirst().getResource(); assertThat(updatedDocument.timestamp().equals(readDocument.timestamp())); } } @@ -201,7 +201,7 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { DocumentCollection coll = null; { // self link - ResourceResponse collection = writeClient.createCollection(createdDatabase.selfLink(), getCollectionDefinition(), null).toBlocking().first(); + ResourceResponse collection = writeClient.createCollection(createdDatabase.selfLink(), getCollectionDefinition(), null).blockFirst(); String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(collection.getResource().selfLink()); String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(BridgeInternal.getAltLink(collection.getResource())); System.out.println("BridgeInternal.getAltLink(collection.getResource()) " + BridgeInternal.getAltLink(collection.getResource())); @@ -209,13 +209,13 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { assertThat(collection.getSessionToken()).isEqualTo(globalSessionToken2); coll = collection.getResource(); - ResourceResponse collectionRead = writeClient.readCollection(coll.selfLink(), null).toBlocking().first(); + ResourceResponse collectionRead = writeClient.readCollection(coll.selfLink(), null).blockFirst(); // timesync might bump the version, comment out the check //assertThat(collection.sessionToken()).isEqualTo(collectionRead.sessionToken()); } { // name link - ResourceResponse collection = writeClient.createCollection(BridgeInternal.getAltLink(createdDatabase), getCollectionDefinition(), null).toBlocking().first(); + ResourceResponse collection = writeClient.createCollection(BridgeInternal.getAltLink(createdDatabase), getCollectionDefinition(), null).blockFirst(); String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(collection.getResource().selfLink()); String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(BridgeInternal.getAltLink(collection.getResource())); @@ -223,7 +223,7 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { //assertThat(collection.sessionToken()).isEqualTo(globalSessionToken2); ResourceResponse collectionRead = - writeClient.readCollection(BridgeInternal.getAltLink(collection.getResource()), null).toBlocking().first(); + writeClient.readCollection(BridgeInternal.getAltLink(collection.getResource()), null).blockFirst(); // timesync might bump the version, comment out the check //assertThat(collection.sessionToken()).isEqualTo(collectionRead.sessionToken()); } @@ -232,7 +232,9 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { document2.id("test" + UUID.randomUUID().toString()); document2.set("customerid", 2); // name link - ResourceResponse document = writeClient.createDocument(BridgeInternal.getAltLink(coll), document2, null, false).toBlocking().first(); + ResourceResponse document = writeClient.createDocument(BridgeInternal.getAltLink(coll), + document2, null, false) + .blockFirst(); String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(coll.selfLink()); String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(BridgeInternal.getAltLink(coll)); @@ -244,7 +246,9 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { document2.id("test" + UUID.randomUUID().toString()); document2.set("customerid", 3); // name link - ResourceResponse document = writeClient.createDocument(BridgeInternal.getAltLink(coll), document2, null, false).toBlocking().first(); + ResourceResponse document = writeClient.createDocument(BridgeInternal.getAltLink(coll), + document2, null, false) + .blockFirst(); String globalSessionToken1 = ((SessionContainer) writeClient.getSession()).getSessionToken(coll.selfLink()); String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(BridgeInternal.getAltLink(coll)); @@ -267,20 +271,30 @@ boolean validateConsistentPrefix(Resource resourceToWorkWith) throws Interrupted Thread.sleep(1000); //Timestamp is in granularity of seconds. Resource updatedResource = null; if (resourceToWorkWith instanceof User) { - updatedResource = this.writeClient.upsertUser(createdDatabase.selfLink(), (User) writeResource, null).toBlocking().first().getResource(); + updatedResource = this.writeClient.upsertUser(createdDatabase.selfLink(), (User) writeResource, + null) + .blockFirst() + .getResource(); } else if (resourceToWorkWith instanceof Document) { - updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), (Document) writeResource, null, false).toBlocking().first().getResource(); + updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), + (Document) writeResource, null, false) + .blockFirst() + .getResource(); } assertThat(updatedResource.timestamp().isAfter(sourceTimestamp)).isTrue(); writeResource = updatedResource; Resource readResource = null; if (resourceToWorkWith instanceof User) { - readResource = this.readClient.readUser(resourceToWorkWith.selfLink(), null).toBlocking().first().getResource(); + readResource = this.readClient.readUser(resourceToWorkWith.selfLink(), null) + .blockFirst() + .getResource(); } else if (resourceToWorkWith instanceof Document) { RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(resourceToWorkWith.get("mypk"))); - readResource = this.readClient.readDocument(resourceToWorkWith.selfLink(), options).toBlocking().first().getResource(); + readResource = this.readClient.readDocument(resourceToWorkWith.selfLink(), options) + .blockFirst() + .getResource(); } assertThat(readResource.timestamp().compareTo(lastReadDateTime) >= 0).isTrue(); lastReadDateTime = readResource.timestamp(); @@ -302,7 +316,11 @@ boolean validateReadSession(Resource resourceToWorkWith) throws InterruptedExcep Thread.sleep(1000); Resource updatedResource = null; if (resourceToWorkWith instanceof Document) { - updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), writeResource, null, false).toBlocking().single().getResource(); + updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), writeResource, + null, false) + .single() + .block() + .getResource(); } assertThat(updatedResource.timestamp().isAfter(sourceTimestamp)).isTrue(); writeResource = updatedResource; @@ -311,7 +329,7 @@ boolean validateReadSession(Resource resourceToWorkWith) throws InterruptedExcep RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceToWorkWith.get("mypk"))); if (resourceToWorkWith instanceof Document) { - readResource = this.readClient.readDocument(resourceToWorkWith.selfLink(), requestOptions).toBlocking().first().getResource(); + readResource = this.readClient.readDocument(resourceToWorkWith.selfLink(), requestOptions).blockFirst().getResource(); } assertThat(readResource.timestamp().compareTo(lastReadDateTime) >= 0).isTrue(); lastReadDateTime = readResource.timestamp(); @@ -334,7 +352,7 @@ boolean validateWriteSession(Resource resourceToWorkWith) throws InterruptedExce Thread.sleep(1000); Resource updatedResource = null; if (resourceToWorkWith instanceof Document) { - updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), writeResource, null, false).toBlocking().single().getResource(); + updatedResource = this.writeClient.upsertDocument(createdCollection.selfLink(), writeResource, null, false).single().block().getResource(); } assertThat(updatedResource.timestamp().isAfter(sourceTimestamp)).isTrue(); writeResource = updatedResource; @@ -343,7 +361,10 @@ boolean validateWriteSession(Resource resourceToWorkWith) throws InterruptedExce RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceToWorkWith.get("mypk"))); if (resourceToWorkWith instanceof Document) { - readResource = this.readClient.readDocument(resourceToWorkWith.selfLink(), requestOptions).toBlocking().first().getResource(); + readResource = + this.readClient.readDocument(resourceToWorkWith.selfLink(), requestOptions) + .blockFirst() + .getResource(); } assertThat(readResource.timestamp().compareTo(lastReadDateTime) >= 0).isTrue(); lastReadDateTime = readResource.timestamp(); @@ -355,7 +376,11 @@ boolean validateWriteSession(Resource resourceToWorkWith) throws InterruptedExce //Now perform write on session and update our session token and lastReadTS Thread.sleep(1000); if (resourceToWorkWith instanceof Document) { - readResource = this.writeClient.upsertDocument(createdCollection.selfLink(), readResource, requestOptions, false).toBlocking().first().getResource(); //Now perform write on session + readResource = this.writeClient.upsertDocument(createdCollection.selfLink(), readResource, + requestOptions, false) + .blockFirst() + .getResource(); + //Now perform write on session } assertThat(readResource.timestamp().isAfter(lastReadDateTime)); @@ -390,18 +415,18 @@ void validateSessionContainerAfterCollectionDeletion(boolean useGateway) throws ResourceResponseValidator successValidatorCollection = new ResourceResponseValidator.Builder() .withId(collection.id()) .build(); - Observable> readObservableCollection = client2.readCollection(collection.selfLink(), null); + Flux> readObservableCollection = client2.readCollection(collection.selfLink(), null); validateSuccess(readObservableCollection, successValidatorCollection); for (int i = 0; i < 5; i++) { String documentId = "Generation1-" + i; Document documentDefinition = getDocumentDefinition(); documentDefinition.id(documentId); - Document documentCreated = client2.createDocument(collection.selfLink(), documentDefinition, null, true).toBlocking().first().getResource(); + Document documentCreated = client2.createDocument(collection.selfLink(), documentDefinition, null, true).blockFirst().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(documentCreated.get("mypk"))); - client2.readDocument(BridgeInternal.getAltLink(documentCreated), requestOptions).toBlocking().first(); - client2.readDocument(documentCreated.selfLink(), requestOptions).toBlocking().first(); + client2.readDocument(BridgeInternal.getAltLink(documentCreated), requestOptions).blockFirst(); + client2.readDocument(documentCreated.selfLink(), requestOptions).blockFirst(); } { @@ -421,7 +446,7 @@ void validateSessionContainerAfterCollectionDeletion(boolean useGateway) throws } // now delete collection use different client - client1.deleteCollection(collection.selfLink(), null).toBlocking().first(); + client1.deleteCollection(collection.selfLink(), null).blockFirst(); DocumentCollection collectionRandom1 = createCollection(client2, createdDatabase.id(), getCollectionDefinition()); DocumentCollection documentCollection = getCollectionDefinition(); @@ -430,13 +455,13 @@ void validateSessionContainerAfterCollectionDeletion(boolean useGateway) throws String documentId1 = "Generation2-" + 0; Document databaseDefinition2 = getDocumentDefinition(); databaseDefinition2.id(documentId1); - Document createdDocument = client1.createDocument(collectionSameName.selfLink(), databaseDefinition2, null, true).toBlocking().first().getResource(); + Document createdDocument = client1.createDocument(collectionSameName.selfLink(), databaseDefinition2, null, true).blockFirst().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(createdDocument.get("mypk"))); ResourceResponseValidator successValidator = new ResourceResponseValidator.Builder() .withId(createdDocument.id()) .build(); - Observable> readObservable = client1.readDocument(createdDocument.selfLink(), requestOptions); + Flux> readObservable = client1.readDocument(createdDocument.selfLink(), requestOptions); validateSuccess(readObservable, successValidator); { String token1 = ((SessionContainer) client1.getSession()).getSessionToken(BridgeInternal.getAltLink(collectionSameName)); @@ -472,7 +497,7 @@ void validateSessionContainerAfterCollectionDeletion(boolean useGateway) throws // verify deleting indeed delete the collection session token { Document documentTest = - client1.createDocument(BridgeInternal.getAltLink(collectionSameName), getDocumentDefinition(), null, true).toBlocking().first().getResource(); + client1.createDocument(BridgeInternal.getAltLink(collectionSameName), getDocumentDefinition(), null, true).blockFirst().getResource(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(documentTest.get("mypk"))); successValidator = new ResourceResponseValidator.Builder() @@ -481,7 +506,7 @@ void validateSessionContainerAfterCollectionDeletion(boolean useGateway) throws readObservable = client1.readDocument(documentTest.selfLink(), options); validateSuccess(readObservable, successValidator); - client1.deleteCollection(collectionSameName.selfLink(), null).toBlocking().first(); + client1.deleteCollection(collectionSameName.selfLink(), null).blockFirst(); String token1 = ((SessionContainer) client2.getSession()).getSessionToken(BridgeInternal.getAltLink(collectionSameName)); String token2 = ((SessionContainer) client2.getSession()).getSessionToken(collectionSameName.selfLink()); // currently we can't delete the token from Altlink when deleting using selflink @@ -514,11 +539,11 @@ void validateSessionTokenWithPreConditionFailure(boolean useGateway) throws Exce .build(); try { // write a document, and upsert to it to update etag. - ResourceResponse documentResponse = writeClient.createDocument(BridgeInternal.getAltLink(createdCollection), getDocumentDefinition(), null, true).toBlocking().first(); + ResourceResponse documentResponse = writeClient.createDocument(BridgeInternal.getAltLink(createdCollection), getDocumentDefinition(), null, true).blockFirst(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(documentResponse.getResource().get("mypk"))); ResourceResponse upsertResponse = - writeClient.upsertDocument(BridgeInternal.getAltLink(createdCollection), documentResponse.getResource(), requestOptions, true).toBlocking().first(); + writeClient.upsertDocument(BridgeInternal.getAltLink(createdCollection), documentResponse.getResource(), requestOptions, true).blockFirst(); // create a conditioned read request, with first write request's etag, so the read fails with PreconditionFailure AccessCondition ac = new AccessCondition(); @@ -527,7 +552,7 @@ void validateSessionTokenWithPreConditionFailure(boolean useGateway) throws Exce RequestOptions requestOptions1 = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(documentResponse.getResource().get("mypk"))); requestOptions1.setAccessCondition(ac); - Observable> preConditionFailureResponseObservable = validationClient.upsertDocument(BridgeInternal.getAltLink(createdCollection), + Flux> preConditionFailureResponseObservable = validationClient.upsertDocument(BridgeInternal.getAltLink(createdCollection), documentResponse.getResource(), requestOptions1, true); FailureValidator failureValidator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.PRECONDITION_FAILED).build(); validateFailure(preConditionFailureResponseObservable, failureValidator); @@ -560,13 +585,13 @@ void validateSessionTokenWithDocumentNotFoundException(boolean useGateway) throw DocumentCollection collectionDefinition = getCollectionDefinition(); collectionDefinition.id("TestCollection"); - ResourceResponse documentResponse = writeClient.createDocument(BridgeInternal.getAltLink(createdCollection), getDocumentDefinition(), null, true).toBlocking().first(); + ResourceResponse documentResponse = writeClient.createDocument(BridgeInternal.getAltLink(createdCollection), getDocumentDefinition(), null, true).blockFirst(); FailureValidator failureValidator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.NOTFOUND).build(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(documentResponse.getResource().get("mypk"))); // try to read a non existent document in the same partition that we previously wrote to - Observable> readObservable = validationClient.readDocument(BridgeInternal.getAltLink(documentResponse.getResource()) + "dummy", requestOptions); + Flux> readObservable = validationClient.readDocument(BridgeInternal.getAltLink(documentResponse.getResource()) + "dummy", requestOptions); validateFailure(readObservable, failureValidator); assertThat(isSessionEqual(((SessionContainer) validationClient.getSession()), (SessionContainer) writeClient.getSession())).isTrue(); } finally { @@ -589,7 +614,7 @@ void validateSessionTokenWithExpectedException(boolean useGateway) throws Except .build(); try { ResourceResponse documentResponse = - writeClient.createDocument(BridgeInternal.getAltLink(createdCollection), getDocumentDefinition(), null, false).toBlocking().first(); + writeClient.createDocument(BridgeInternal.getAltLink(createdCollection), getDocumentDefinition(), null, false).blockFirst(); String token = documentResponse.getResponseHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); // artificially bump to higher LSN @@ -599,7 +624,7 @@ void validateSessionTokenWithExpectedException(boolean useGateway) throws Except requestOptions.setPartitionKey(new PartitionKey(documentResponse.getResource().get("mypk"))); requestOptions.setSessionToken(higherLsnToken); // try to read a non existent document in the same partition that we previously wrote to - Observable> readObservable = writeClient.readDocument(BridgeInternal.getAltLink(documentResponse.getResource()), + Flux> readObservable = writeClient.readDocument(BridgeInternal.getAltLink(documentResponse.getResource()), requestOptions); validateFailure(readObservable, failureValidator); @@ -628,10 +653,10 @@ void validateSessionTokenWithConflictException(boolean useGateway) { try { Document documentDefinition = getDocumentDefinition(); ResourceResponse documentResponse = - writeClient.createDocument(BridgeInternal.getAltLink(createdCollection), documentDefinition, null, true).toBlocking().first(); + writeClient.createDocument(BridgeInternal.getAltLink(createdCollection), documentDefinition, null, true).blockFirst(); FailureValidator failureValidator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.CONFLICT).build(); - Observable> conflictDocumentResponse = validationClient.createDocument(BridgeInternal.getAltLink(createdCollection), + Flux> conflictDocumentResponse = validationClient.createDocument(BridgeInternal.getAltLink(createdCollection), documentDefinition, null, true); validateFailure(conflictDocumentResponse, failureValidator); @@ -665,7 +690,7 @@ void validateSessionTokenMultiPartitionCollection(boolean useGateway) throws Exc Document document1 = new Document(); document1.id("test" + UUID.randomUUID().toString()); document1.set("mypk", 1); - ResourceResponse childResource1 = writeClient.createDocument(createdCollection.selfLink(), document1, null, true).toBlocking().first(); + ResourceResponse childResource1 = writeClient.createDocument(createdCollection.selfLink(), document1, null, true).blockFirst(); logger.info("Created {} child resource", childResource1.getResource().resourceId()); assertThat(childResource1.getSessionToken()).isNotNull(); assertThat(childResource1.getSessionToken().contains(":")).isTrue(); @@ -676,7 +701,7 @@ void validateSessionTokenMultiPartitionCollection(boolean useGateway) throws Exc Document document2 = new Document(); document2.id("test" + UUID.randomUUID().toString()); document2.set("mypk", 2); - ResourceResponse childResource2 = writeClient.createDocument(createdCollection.selfLink(), document2, null, true).toBlocking().first(); + ResourceResponse childResource2 = writeClient.createDocument(createdCollection.selfLink(), document2, null, true).blockFirst(); assertThat(childResource2.getSessionToken()).isNotNull(); assertThat(childResource2.getSessionToken().contains(":")).isTrue(); String globalSessionToken2 = ((SessionContainer) writeClient.getSession()).getSessionToken(createdCollection.selfLink()); @@ -690,17 +715,17 @@ void validateSessionTokenMultiPartitionCollection(boolean useGateway) throws Exc RequestOptions option = new RequestOptions(); option.setSessionToken(sessionToken); option.setPartitionKey(new PartitionKey(2)); - writeClient.readDocument(childResource2.getResource().selfLink(), option).toBlocking().first(); + writeClient.readDocument(childResource2.getResource().selfLink(), option).blockFirst(); option = new RequestOptions(); option.setSessionToken(StringUtils.EMPTY); option.setPartitionKey(new PartitionKey(1)); - writeClient.readDocument(childResource1.getResource().selfLink(), option).toBlocking().first(); + writeClient.readDocument(childResource1.getResource().selfLink(), option).blockFirst(); option = new RequestOptions(); option.setSessionToken(sessionToken); option.setPartitionKey(new PartitionKey(1)); - Observable> readObservable = writeClient.readDocument(childResource1.getResource().selfLink(), option); + Flux> readObservable = writeClient.readDocument(childResource1.getResource().selfLink(), option); FailureValidator failureValidator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.NOTFOUND).subStatusCode(HttpConstants.SubStatusCodes.READ_SESSION_NOT_AVAILABLE).build(); validateFailure(readObservable, failureValidator); @@ -734,10 +759,10 @@ void validateSessionTokenFromCollectionReplaceIsServerToken(boolean useGateway) .build(); RxDocumentClientImpl client2 = null; try { - Document doc = client1.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, true).toBlocking().first().getResource(); + Document doc = client1.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, true).blockFirst().getResource(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(doc.get("mypk"))); - Document doc1 = client1.readDocument(BridgeInternal.getAltLink(doc), requestOptions).toBlocking().first().getResource(); + Document doc1 = client1.readDocument(BridgeInternal.getAltLink(doc), requestOptions).blockFirst().getResource(); String token1 = ((SessionContainer) client1.getSession()).getSessionToken(createdCollection.selfLink()); client2 = (RxDocumentClientImpl) new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) @@ -745,7 +770,7 @@ void validateSessionTokenFromCollectionReplaceIsServerToken(boolean useGateway) .withConnectionPolicy(connectionPolicy) .withConsistencyLevel(ConsistencyLevel.SESSION) .build(); - client2.replaceCollection(createdCollection, null).toBlocking().first(); + client2.replaceCollection(createdCollection, null).blockFirst(); String token2 = ((SessionContainer) client2.getSession()).getSessionToken(createdCollection.selfLink()); logger.info("Token after document and after collection replace {} = {}", token1, token2); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java index 92ba4e0726830..9ed9aed385d3d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java @@ -31,18 +31,18 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.SpyClientBuilder; +import com.azure.data.cosmos.internal.http.HttpRequest; import com.azure.data.cosmos.rx.Utils; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -120,32 +120,33 @@ public void queryWithContinuationTokenLimit(FeedOptions options, String query, b client.clearCapturedRequests(); - Observable> queryObservable = client + Flux> queryObservable = client .queryDocuments(collectionLink, query, options); - List results = queryObservable.flatMap(p -> Observable.from(p.results())) - .toList().toBlocking().single(); + List results = queryObservable.flatMap(p -> Flux.fromIterable(p.results())) + .collectList().block(); assertThat(results.size()).describedAs("total results").isGreaterThanOrEqualTo(1); - List> requests = client.getCapturedRequests(); + List requests = client.getCapturedRequests(); - for(HttpClientRequest req: requests) { + for(HttpRequest req: requests) { validateRequestHasContinuationTokenLimit(req, options.responseContinuationTokenLimitInKb()); } } - private void validateRequestHasContinuationTokenLimit(HttpClientRequest request, Integer expectedValue) { + private void validateRequestHasContinuationTokenLimit(HttpRequest request, Integer expectedValue) { + Map headers = request.headers().toMap(); if (expectedValue != null && expectedValue > 0) { - assertThat(request.getHeaders() - .contains(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB)) + assertThat(headers + .containsKey(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB)) .isTrue(); - assertThat(request.getHeaders() + assertThat(headers .get("x-ms-documentdb-responsecontinuationtokenlimitinkb")) .isEqualTo(Integer.toString(expectedValue)); } else { - assertThat(request.getHeaders() - .contains(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB)) + assertThat(headers + .containsKey(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB)) .isFalse(); } } @@ -154,7 +155,7 @@ public Document createDocument(AsyncDocumentClient client, String collectionLink Document docDefinition = getDocumentDefinition(cnt); return client - .createDocument(collectionLink, docDefinition, null, false).toBlocking().single().getResource(); + .createDocument(collectionLink, docDefinition, null, false).blockFirst().getResource(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) @@ -187,11 +188,11 @@ public void beforeClass() throws Exception { // do the query once to ensure the collection is cached. client.queryDocuments(getMultiPartitionCollectionLink(), "select * from root", options) - .toCompletable().await(); + .then().block(); // do the query once to ensure the collection is cached. client.queryDocuments(getSinglePartitionCollectionLink(), "select * from root", options) - .toCompletable().await(); + .then().block(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java index 3359891e1794e..0e6b045406a30 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java @@ -32,7 +32,7 @@ import org.testng.annotations.AfterClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.net.UnknownHostException; import java.time.Instant; @@ -58,7 +58,7 @@ public void createCollectionWithUnreachableHost() { Database database = SHARED_DATABASE; - Observable> createObservable = client + Flux> createObservable = client .createCollection(database.selfLink(), collectionDefinition, null); @@ -68,7 +68,7 @@ public void createCollectionWithUnreachableHost() { RxDocumentServiceRequest request = invocation.getArgumentAt(0, RxDocumentServiceRequest.class); if (request.getResourceType() == ResourceType.DocumentCollection) { - return Observable.error(new UnknownHostException()); + return Flux.error(new UnknownHostException()); } return origGatewayStoreModel.processMessage(request); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java index c6b940a8da28f..e454a20ee7a1e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java @@ -24,29 +24,29 @@ package com.azure.data.cosmos.internal; import org.apache.commons.lang3.Range; -import rx.Completable; -import rx.functions.Action1; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.List; +import java.util.function.Consumer; public class ParallelAsync { - static Completable forEachAsync(Range range, int partition, Action1 func) { + static Mono forEachAsync(Range range, int partition, Consumer func) { int partitionSize = (range.getMaximum() - range.getMinimum()) / partition; - List task = new ArrayList<>(); + List> task = new ArrayList<>(); int startRange = range.getMinimum(); for (int i = 0; i < partition; i++) { Range integerRange = Range.between(startRange, startRange + partitionSize); - task.add(Completable.defer(() -> { + task.add(Mono.defer(() -> { for(int j = integerRange.getMinimum(); j < integerRange.getMaximum();j++) { - func.call(j); + func.accept(j); } - return Completable.complete(); + return Mono.empty(); })); startRange = startRange + partitionSize ; } - return Completable.mergeDelayError(task); + return Mono.whenDelayError(task); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java index 67df79c0b960f..d5d5fb19e4a9a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java @@ -34,19 +34,18 @@ import com.azure.data.cosmos.rx.ResourceResponseValidator; import com.google.common.collect.ImmutableMap; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.lang.reflect.Method; +import java.time.Duration; import java.util.Map; import java.util.UUID; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.mockito.Matchers.anyObject; @@ -67,32 +66,29 @@ public RetryCreateDocumentTest(AsyncDocumentClient.Builder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void retryDocumentCreate() throws Exception { // create a document to ensure collection is cached - client.createDocument(collection.selfLink(), getDocumentDefinition(), null, false).toBlocking().single(); + client.createDocument(collection.selfLink(), getDocumentDefinition(), null, false).single().block(); Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client + Flux> createObservable = client .createDocument(collection.selfLink(), docDefinition, null, false); AtomicInteger count = new AtomicInteger(); - doAnswer(new Answer< Observable>() { - @Override - public Observable answer(InvocationOnMock invocation) throws Throwable { - RxDocumentServiceRequest req = (RxDocumentServiceRequest) invocation.getArguments()[0]; - if (req.getOperationType() != OperationType.Create) { - return client.getOrigGatewayStoreModel().processMessage(req); - } - - int currentAttempt = count.getAndIncrement(); - if (currentAttempt == 0) { - Map header = ImmutableMap.of( - HttpConstants.HttpHeaders.SUB_STATUS, - Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_MISMATCH)); - - return Observable.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, new Error() , header)); - } else { - return client.getOrigGatewayStoreModel().processMessage(req); - } + doAnswer((Answer>) invocation -> { + RxDocumentServiceRequest req = (RxDocumentServiceRequest) invocation.getArguments()[0]; + if (req.getOperationType() != OperationType.Create) { + return client.getOrigGatewayStoreModel().processMessage(req); + } + + int currentAttempt = count.getAndIncrement(); + if (currentAttempt == 0) { + Map header = ImmutableMap.of( + HttpConstants.HttpHeaders.SUB_STATUS, + Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_MISMATCH)); + + return Flux.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, new Error() , header)); + } else { + return client.getOrigGatewayStoreModel().processMessage(req); } }).when(client.getSpyGatewayStoreModel()).processMessage(anyObject()); @@ -106,36 +102,33 @@ public Observable answer(InvocationOnMock invocation) public void createDocument_noRetryOnNonRetriableFailure() throws Exception { AtomicInteger count = new AtomicInteger(); - doAnswer(new Answer< Observable>() { - @Override - public Observable answer(InvocationOnMock invocation) throws Throwable { - RxDocumentServiceRequest req = (RxDocumentServiceRequest) invocation.getArguments()[0]; - - if (req.getResourceType() != ResourceType.Document) { - return client.getOrigGatewayStoreModel().processMessage(req); - } - - int currentAttempt = count.getAndIncrement(); - if (currentAttempt == 0) { - return client.getOrigGatewayStoreModel().processMessage(req); - } else { - Map header = ImmutableMap.of( - HttpConstants.HttpHeaders.SUB_STATUS, - Integer.toString(2)); - - return Observable.error(new CosmosClientException(1, new Error() , header)); - } + doAnswer((Answer>) invocation -> { + RxDocumentServiceRequest req = (RxDocumentServiceRequest) invocation.getArguments()[0]; + + if (req.getResourceType() != ResourceType.Document) { + return client.getOrigGatewayStoreModel().processMessage(req); + } + + int currentAttempt = count.getAndIncrement(); + if (currentAttempt == 0) { + return client.getOrigGatewayStoreModel().processMessage(req); + } else { + Map header = ImmutableMap.of( + HttpConstants.HttpHeaders.SUB_STATUS, + Integer.toString(2)); + + return Flux.error(new CosmosClientException(1, new Error() , header)); } }).when(client.getSpyGatewayStoreModel()).processMessage(anyObject()); // create a document to ensure collection is cached client.createDocument(collection.selfLink(), getDocumentDefinition(), null, false) - .toBlocking() - .single(); + .single() + .block(); Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client + Flux> createObservable = client .createDocument(collection.selfLink(), docDefinition, null, false); // validate @@ -146,37 +139,34 @@ public Observable answer(InvocationOnMock invocation) @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createDocument_failImmediatelyOnNonRetriable() throws Exception { // create a document to ensure collection is cached - client.createDocument(collection.selfLink(), getDocumentDefinition(), null, false).toBlocking().single(); + client.createDocument(collection.selfLink(), getDocumentDefinition(), null, false).single().block(); AtomicInteger count = new AtomicInteger(); - doAnswer(new Answer< Observable>() { - @Override - public Observable answer(InvocationOnMock invocation) throws Throwable { - RxDocumentServiceRequest req = (RxDocumentServiceRequest) invocation.getArguments()[0]; - if (req.getOperationType() != OperationType.Create) { - return client.getOrigGatewayStoreModel().processMessage(req); - } - int currentAttempt = count.getAndIncrement(); - if (currentAttempt == 0) { - Map header = ImmutableMap.of( - HttpConstants.HttpHeaders.SUB_STATUS, - Integer.toString(2)); - - return Observable.error(new CosmosClientException(1, new Error() , header)); - } else { - return client.getOrigGatewayStoreModel().processMessage(req); - } + doAnswer((Answer>) invocation -> { + RxDocumentServiceRequest req = (RxDocumentServiceRequest) invocation.getArguments()[0]; + if (req.getOperationType() != OperationType.Create) { + return client.getOrigGatewayStoreModel().processMessage(req); + } + int currentAttempt = count.getAndIncrement(); + if (currentAttempt == 0) { + Map header = ImmutableMap.of( + HttpConstants.HttpHeaders.SUB_STATUS, + Integer.toString(2)); + + return Flux.error(new CosmosClientException(1, new Error() , header)); + } else { + return client.getOrigGatewayStoreModel().processMessage(req); } }).when(client.getSpyGatewayStoreModel()).processMessage(anyObject()); Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client + Flux> createObservable = client .createDocument(collection.selfLink(), docDefinition, null, false); // validate FailureValidator validator = new FailureValidator.Builder().statusCode(1).subStatusCode(2).build(); - validateFailure(createObservable.timeout(100, TimeUnit.MILLISECONDS), validator); + validateFailure(createObservable.timeout(Duration.ofMillis(100)), validator); } @BeforeMethod(groups = { "simple" }) diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java index 6791bd423ea15..d4ca6decd529f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java @@ -34,13 +34,12 @@ import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.rx.ResourceResponseValidator; import com.azure.data.cosmos.rx.TestConfigurations; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; @@ -77,11 +76,11 @@ public void retryCreateDocumentsOnSpike() throws Exception { client = SpyClientUnderTestFactory.createClientWithGatewaySpy(builder); // create a document to ensure collection is cached - client.createDocument(getCollectionLink(collection), getDocumentDefinition(), null, false).toBlocking().single(); + client.createDocument(getCollectionLink(collection), getDocumentDefinition(), null, false).blockFirst(); - List>> list = new ArrayList<>(); + List>> list = new ArrayList<>(); for(int i = 0; i < TOTAL_DOCS; i++) { - Observable> obs = client.createDocument(getCollectionLink(collection), getDocumentDefinition(), null, false); + Flux> obs = client.createDocument(getCollectionLink(collection), getDocumentDefinition(), null, false); list.add(obs); } @@ -89,19 +88,16 @@ public void retryCreateDocumentsOnSpike() throws Exception { AtomicInteger totalCount = new AtomicInteger(); AtomicInteger successCount = new AtomicInteger(); - doAnswer(new Answer< Observable>() { - @Override - public Observable answer(InvocationOnMock invocation) throws Throwable { + doAnswer((Answer>) invocation -> { RxDocumentServiceRequest req = (RxDocumentServiceRequest) invocation.getArguments()[0]; if (req.getResourceType() == ResourceType.Document && req.getOperationType() == OperationType.Create) { // increment the counter per Document CREATE operations totalCount.incrementAndGet(); } return client.getOrigGatewayStoreModel().processMessage(req).doOnNext(rsp -> successCount.incrementAndGet()); - } }).when(client.getSpyGatewayStoreModel()).processMessage(anyObject()); - List> rsps = Observable.merge(list, 100).toList().toSingle().toBlocking().value(); + List> rsps = Flux.merge(Flux.fromIterable(list), 100).collectList().single().block(); System.out.println("total: " + totalCount.get()); assertThat(rsps).hasSize(TOTAL_DOCS); assertThat(successCount.get()).isEqualTo(TOTAL_DOCS); @@ -113,28 +109,25 @@ public void retryDocumentCreate() throws Exception { client = SpyClientUnderTestFactory.createClientWithGatewaySpy(createGatewayRxDocumentClient()); // create a document to ensure collection is cached - client.createDocument(getCollectionLink(collection), getDocumentDefinition(), null, false).toBlocking().single(); + client.createDocument(getCollectionLink(collection), getDocumentDefinition(), null, false).blockFirst(); Document docDefinition = getDocumentDefinition(); - Observable> createObservable = client + Flux> createObservable = client .createDocument(collection.selfLink(), docDefinition, null, false); AtomicInteger count = new AtomicInteger(); - doAnswer(new Answer< Observable>() { - @Override - public Observable answer(InvocationOnMock invocation) throws Throwable { + doAnswer((Answer>) invocation -> { RxDocumentServiceRequest req = (RxDocumentServiceRequest) invocation.getArguments()[0]; if (req.getOperationType() != OperationType.Create) { return client.getOrigGatewayStoreModel().processMessage(req); } int currentAttempt = count.getAndIncrement(); if (currentAttempt == 0) { - return Observable.error(new CosmosClientException(HttpConstants.StatusCodes.TOO_MANY_REQUESTS)); + return Flux.error(new CosmosClientException(HttpConstants.StatusCodes.TOO_MANY_REQUESTS)); } else { return client.getOrigGatewayStoreModel().processMessage(req); } - } }).when(client.getSpyGatewayStoreModel()).processMessage(anyObject()); // validate @@ -169,4 +162,4 @@ private Document getDocumentDefinition() { @AfterClass(groups = { "long" }, timeOut = SHUTDOWN_TIMEOUT, enabled = false) public void afterClass() { } -} \ No newline at end of file +} diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java index bbad58300e595..ed4149961ab94 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java @@ -26,21 +26,18 @@ import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.ISessionContainer; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; -import io.reactivex.netty.protocol.http.client.HttpClientResponse; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpRequest; +import com.azure.data.cosmos.internal.http.HttpResponse; import org.mockito.Mockito; import org.mockito.stubbing.Answer; -import rx.Observable; +import reactor.core.publisher.Mono; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.doAnswer; /** @@ -49,11 +46,10 @@ */ public class RxDocumentClientUnderTest extends RxDocumentClientImpl { - public CompositeHttpClient spyHttpClient; - public CompositeHttpClient origHttpClient; + public HttpClient spyHttpClient; + public HttpClient origHttpClient; - public List> httpRequests = Collections.synchronizedList( - new ArrayList>()); + public List httpRequests = Collections.synchronizedList(new ArrayList<>()); public RxDocumentClientUnderTest(URI serviceEndpoint, String masterKey, @@ -70,27 +66,16 @@ RxGatewayStoreModel createRxGatewayProxy( QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, - CompositeHttpClient rxOrigClient) { + HttpClient rxOrigClient) { origHttpClient = rxOrigClient; spyHttpClient = Mockito.spy(rxOrigClient); - doAnswer((Answer>>) invocationOnMock -> { - - RxClient.ServerInfo serverInfo = - invocationOnMock.getArgumentAt(0, RxClient.ServerInfo.class); - - HttpClientRequest request - = invocationOnMock.getArgumentAt(1, HttpClientRequest.class); - - httpRequests.add(request); - - Observable> httpRespObs = - origHttpClient.submit(serverInfo, request); - - return httpRespObs; - }).when(spyHttpClient).submit( anyObject(), - (HttpClientRequest) anyObject()); + doAnswer((Answer>) invocationOnMock -> { + HttpRequest httpRequest = invocationOnMock.getArgumentAt(0, HttpRequest.class); + httpRequests.add(httpRequest); + return origHttpClient.send(httpRequest); + }).when(spyHttpClient).send(Mockito.any(HttpRequest.class)); return super.createRxGatewayProxy(sessionContainer, consistencyLevel, diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java index 782c5f4b6fb2f..cc0efac77bc01 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java @@ -30,9 +30,8 @@ import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RequestOptions; -import io.netty.buffer.ByteBuf; +import com.azure.data.cosmos.internal.http.HttpRequest; import io.netty.handler.codec.http.HttpMethod; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; import org.apache.commons.lang3.StringUtils; import org.testng.SkipException; import org.testng.annotations.AfterClass; @@ -58,7 +57,7 @@ public class SessionTest extends TestSuiteBase { private Database createdDatabase; private DocumentCollection createdCollection; private String collectionId = "+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~"; - private SpyClientUnderTestFactory.SpyBaseClass> spyClient; + private SpyClientUnderTestFactory.SpyBaseClass spyClient; private AsyncDocumentClient houseKeepingClient; private ConnectionMode connectionMode; private RequestOptions options; @@ -110,7 +109,6 @@ public void afterClass() { safeDeleteCollection(houseKeepingClient, createdCollection); safeClose(houseKeepingClient); safeClose(spyClient); - } @BeforeMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) @@ -120,19 +118,19 @@ public void beforeTest(Method method) { private List getSessionTokensInRequests() { return spyClient.getCapturedRequests().stream() - .map(r -> r.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN)).collect(Collectors.toList()); + .map(r -> r.headers().value(HttpConstants.HttpHeaders.SESSION_TOKEN)).collect(Collectors.toList()); } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "sessionTestArgProvider") public void sessionConsistency_ReadYourWrites(boolean isNameBased) { - spyClient.readCollection(getCollectionLink(isNameBased), null).toBlocking().single(); - spyClient.createDocument(getCollectionLink(isNameBased), new Document(), null, false).toBlocking().single(); + spyClient.readCollection(getCollectionLink(isNameBased), null).blockFirst(); + spyClient.createDocument(getCollectionLink(isNameBased), new Document(), null, false).blockFirst(); spyClient.clearCapturedRequests(); for (int i = 0; i < 10; i++) { Document documentCreated = spyClient.createDocument(getCollectionLink(isNameBased), new Document(), null, false) - .toBlocking().single().getResource(); + .blockFirst().getResource(); // We send session tokens on Writes in GATEWAY mode if (connectionMode == ConnectionMode.GATEWAY) { @@ -140,12 +138,12 @@ public void sessionConsistency_ReadYourWrites(boolean isNameBased) { assertThat(getSessionTokensInRequests().get(3 * i + 0)).isNotEmpty(); } - spyClient.readDocument(getDocumentLink(documentCreated, isNameBased), options).toBlocking().single(); + spyClient.readDocument(getDocumentLink(documentCreated, isNameBased), options).blockFirst(); assertThat(getSessionTokensInRequests()).hasSize(3 * i + 2); assertThat(getSessionTokensInRequests().get(3 * i + 1)).isNotEmpty(); - spyClient.readDocument(getDocumentLink(documentCreated, isNameBased), options).toBlocking().single(); + spyClient.readDocument(getDocumentLink(documentCreated, isNameBased), options).blockFirst(); assertThat(getSessionTokensInRequests()).hasSize(3 * i + 3); assertThat(getSessionTokensInRequests().get(3 * i + 2)).isNotEmpty(); @@ -157,18 +155,19 @@ public void sessionTokenInDocumentRead(boolean isNameBased) throws UnsupportedEn Document document = new Document(); document.id(UUID.randomUUID().toString()); document.set("pk", "pk"); - document = spyClient.createDocument(getCollectionLink(isNameBased), document, null, false).toBlocking().single() + document = spyClient.createDocument(getCollectionLink(isNameBased), document, null, false) + .blockFirst() .getResource(); final String documentLink = getDocumentLink(document, isNameBased); - spyClient.readDocument(documentLink, options).toBlocking().single() + spyClient.readDocument(documentLink, options).blockFirst() .getResource(); - List> documentReadHttpRequests = spyClient.getCapturedRequests().stream() - .filter(r -> r.getMethod() == HttpMethod.GET) + List documentReadHttpRequests = spyClient.getCapturedRequests().stream() + .filter(r -> r.httpMethod() == HttpMethod.GET) .filter(r -> { try { - return URLDecoder.decode(r.getUri().replaceAll("\\+", "%2b"), "UTF-8").contains( + return URLDecoder.decode(r.uri().toString().replaceAll("\\+", "%2b"), "UTF-8").contains( StringUtils.removeEnd(documentLink, "/")); } catch (UnsupportedEncodingException e) { return false; @@ -177,7 +176,7 @@ public void sessionTokenInDocumentRead(boolean isNameBased) throws UnsupportedEn // DIRECT mode may make more than one call (multiple replicas) assertThat(documentReadHttpRequests.size() >= 1).isTrue(); - assertThat(documentReadHttpRequests.get(0).getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN)).isNotEmpty(); + assertThat(documentReadHttpRequests.get(0).headers().value(HttpConstants.HttpHeaders.SESSION_TOKEN)).isNotEmpty(); } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "sessionTestArgProvider") @@ -186,13 +185,13 @@ public void sessionTokenRemovedForMasterResource(boolean isNameBased) throws Uns throw new SkipException("Master resource access is only through gateway"); } String collectionLink = getCollectionLink(isNameBased); - spyClient.readCollection(collectionLink, null).toBlocking().single(); + spyClient.readCollection(collectionLink, null).blockFirst(); - List> collectionReadHttpRequests = spyClient.getCapturedRequests().stream() - .filter(r -> r.getMethod() == HttpMethod.GET) + List collectionReadHttpRequests = spyClient.getCapturedRequests().stream() + .filter(r -> r.httpMethod() == HttpMethod.GET) .filter(r -> { try { - return URLDecoder.decode(r.getUri().replaceAll("\\+", "%2b"), "UTF-8").contains( + return URLDecoder.decode(r.uri().toString().replaceAll("\\+", "%2b"), "UTF-8").contains( StringUtils.removeEnd(collectionLink, "/")); } catch (UnsupportedEncodingException e) { return false; @@ -201,7 +200,7 @@ public void sessionTokenRemovedForMasterResource(boolean isNameBased) throws Uns .collect(Collectors.toList()); assertThat(collectionReadHttpRequests).hasSize(1); - assertThat(collectionReadHttpRequests.get(0).getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN)).isNull(); + assertThat(collectionReadHttpRequests.get(0).headers().value(HttpConstants.HttpHeaders.SESSION_TOKEN)).isNull(); } private String getCollectionLink(boolean isNameBased) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java index 49bc7dbc3b4e7..0ebd0656078dc 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java @@ -30,11 +30,9 @@ import com.azure.data.cosmos.SpyClientBuilder; import com.azure.data.cosmos.directconnectivity.Protocol; import com.azure.data.cosmos.internal.directconnectivity.ReflectionUtils; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.client.RxClient; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; -import io.reactivex.netty.protocol.http.client.HttpClientRequest; -import io.reactivex.netty.protocol.http.client.HttpResponseHeaders; +import com.azure.data.cosmos.internal.http.HttpClient; +import com.azure.data.cosmos.internal.http.HttpHeaders; +import com.azure.data.cosmos.internal.http.HttpRequest; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.commons.lang3.tuple.Pair; import org.mockito.Mockito; @@ -64,9 +62,9 @@ public SpyBaseClass(URI serviceEndpoint, String masterKeyOrResourceToken, Connec public abstract void clearCapturedRequests(); - static Configs createConfigsSpy(final Protocol protocol) { + protected static Configs createConfigsSpy(final Protocol protocol) { final Configs configs = spy(new Configs()); - doAnswer((Answer)invocation -> protocol).when(configs).getProtocol(); + doAnswer((Answer) invocation -> protocol).when(configs).getProtocol(); return configs; } } @@ -95,7 +93,7 @@ RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, - CompositeHttpClient rxClient) { + HttpClient rxClient) { this.origRxGatewayStoreModel = super.createRxGatewayProxy( sessionContainer, consistencyLevel, @@ -134,47 +132,38 @@ public RxGatewayStoreModel getOrigGatewayStoreModel() { } } - public static class ClientUnderTest extends SpyBaseClass> { + public static class ClientUnderTest extends SpyBaseClass { - CompositeHttpClient origHttpClient; - CompositeHttpClient spyHttpClient; - List, Future>> requestsResponsePairs = - Collections.synchronizedList(new ArrayList, Future>>()); + HttpClient origHttpClient; + HttpClient spyHttpClient; + List>> requestsResponsePairs = + Collections.synchronizedList(new ArrayList<>()); ClientUnderTest(URI serviceEndpoint, String masterKey, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel, Configs configs) { super(serviceEndpoint, masterKey, connectionPolicy, consistencyLevel, configs); init(); } - public List, Future>> capturedRequestResponseHeaderPairs() { + public List>> capturedRequestResponseHeaderPairs() { return requestsResponsePairs; } @Override - public List> getCapturedRequests() { - return requestsResponsePairs.stream().map(pair -> pair.getLeft()).collect(Collectors.toList()); + public List getCapturedRequests() { + return requestsResponsePairs.stream().map(Pair::getLeft).collect(Collectors.toList()); } - void initRequestCapture(CompositeHttpClient spyClient) { - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { - RxClient.ServerInfo serverInfo = invocationOnMock.getArgumentAt(0, RxClient.ServerInfo.class); - HttpClientRequest httpReq = invocationOnMock.getArgumentAt(1, HttpClientRequest.class); - - CompletableFuture f = new CompletableFuture<>(); - requestsResponsePairs.add(Pair.of(httpReq, f)); - - return origHttpClient.submit(serverInfo, httpReq) - .doOnNext( - res -> f.complete(res.getHeaders()) - ).doOnError( - e -> f.completeExceptionally(e) - ); - - } - }).when(spyClient).submit(Mockito.any(RxClient.ServerInfo.class), Mockito.any(HttpClientRequest.class)); + void initRequestCapture(HttpClient spyClient) { + doAnswer(invocationOnMock -> { + HttpRequest httpRequest = invocationOnMock.getArgumentAt(0, HttpRequest.class); + CompletableFuture f = new CompletableFuture<>(); + requestsResponsePairs.add(Pair.of(httpRequest, f)); + + return origHttpClient + .send(httpRequest) + .doOnNext(httpResponse -> f.complete(httpResponse.headers())) + .doOnError(f::completeExceptionally); + }).when(spyClient).send(Mockito.any(HttpRequest.class)); } @Override @@ -190,60 +179,50 @@ public ISessionContainer getSessionContainer() { } } - public CompositeHttpClient getSpyHttpClient() { + public HttpClient getSpyHttpClient() { return spyHttpClient; } } - public static class DirectHttpsClientUnderTest extends SpyBaseClass> { + public static class DirectHttpsClientUnderTest extends SpyBaseClass { - CompositeHttpClient origHttpClient; - CompositeHttpClient spyHttpClient; - List, Future>> requestsResponsePairs = - Collections.synchronizedList(new ArrayList, Future>>()); + HttpClient origHttpClient; + HttpClient spyHttpClient; + List>> requestsResponsePairs = + Collections.synchronizedList(new ArrayList<>()); DirectHttpsClientUnderTest(URI serviceEndpoint, String masterKey, ConnectionPolicy connectionPolicy, ConsistencyLevel consistencyLevel) { - super(serviceEndpoint, masterKey, connectionPolicy, consistencyLevel, createConfigsSpy(Protocol.HTTPS)); assert connectionPolicy.connectionMode() == ConnectionMode.DIRECT; init(); this.origHttpClient = ReflectionUtils.getDirectHttpsHttpClient(this); this.spyHttpClient = spy(this.origHttpClient); - ReflectionUtils.setDirectHttpsHttpClient(this, this.spyHttpClient); this.initRequestCapture(this.spyHttpClient); } - public List, Future>> capturedRequestResponseHeaderPairs() { + public List>> capturedRequestResponseHeaderPairs() { return requestsResponsePairs; } @Override - public List> getCapturedRequests() { - return requestsResponsePairs.stream().map(pair -> pair.getLeft()).collect(Collectors.toList()); + public List getCapturedRequests() { + return requestsResponsePairs.stream().map(Pair::getLeft).collect(Collectors.toList()); } - void initRequestCapture(CompositeHttpClient spyClient) { + void initRequestCapture(HttpClient spyClient) { + doAnswer(invocationOnMock -> { + HttpRequest httpRequest = invocationOnMock.getArgumentAt(0, HttpRequest.class); + CompletableFuture f = new CompletableFuture<>(); + requestsResponsePairs.add(Pair.of(httpRequest, f)); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { - RxClient.ServerInfo serverInfo = invocationOnMock.getArgumentAt(0, RxClient.ServerInfo.class); - HttpClientRequest httpReq = invocationOnMock.getArgumentAt(1, HttpClientRequest.class); + return origHttpClient + .send(httpRequest) + .doOnNext(httpResponse -> f.complete(httpResponse.headers())) + .doOnError(f::completeExceptionally); - CompletableFuture f = new CompletableFuture<>(); - requestsResponsePairs.add(Pair.of(httpReq, f)); - - return origHttpClient.submit(serverInfo, httpReq) - .doOnNext( - res -> f.complete(res.getHeaders()) - ).doOnError( - e -> f.completeExceptionally(e) - ); - - } - }).when(spyClient).submit(Mockito.any(RxClient.ServerInfo.class), Mockito.any(HttpClientRequest.class)); + }).when(spyClient).send(Mockito.any(HttpRequest.class)); } @Override @@ -259,7 +238,7 @@ public ISessionContainer getSessionContainer() { } } - public CompositeHttpClient getSpyHttpClient() { + public HttpClient getSpyHttpClient() { return spyHttpClient; } } @@ -297,12 +276,12 @@ RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, QueryCompatibilityMode queryCompatibilityMode, UserAgentContainer userAgentContainer, GlobalEndpointManager globalEndpointManager, - CompositeHttpClient rxClient) { + HttpClient rxClient) { - CompositeHttpClient spyClient = spy(rxClient); + HttpClient spy = spy(rxClient); this.origHttpClient = rxClient; - this.spyHttpClient = spyClient; + this.spyHttpClient = spy; this.initRequestCapture(spyHttpClient); @@ -312,7 +291,7 @@ RxGatewayStoreModel createRxGatewayProxy(ISessionContainer sessionContainer, queryCompatibilityMode, userAgentContainer, globalEndpointManager, - spyClient); + spy); } }; } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index 073763d0764bf..3cf4df21c8c0f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -62,6 +62,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.CaseFormat; import com.google.common.collect.ImmutableList; +import io.reactivex.subscribers.TestSubscriber; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.mockito.stubbing.Answer; @@ -70,11 +71,9 @@ import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.DataProvider; -import rx.Observable; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.scheduler.Schedulers; -import java.io.PrintWriter; -import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -131,8 +130,6 @@ private static ImmutableList immutableListOrNull(List list) { objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true); } - private String testName; - protected TestSuiteBase() { this(new AsyncDocumentClient.Builder()); } @@ -154,17 +151,17 @@ private DatabaseManagerImpl(AsyncDocumentClient client) { } @Override - public Observable> queryDatabases(SqlQuerySpec query) { + public Flux> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override - public Observable> createDatabase(Database databaseDefinition) { + public Flux> createDatabase(Database databaseDefinition) { return client.createDatabase(databaseDefinition, null); } @Override - public Observable> deleteDatabase(String id) { + public Flux> deleteDatabase(String id) { return client.deleteDatabase("dbs/" + id, null); } @@ -213,7 +210,8 @@ protected static void truncateCollection(DocumentCollection collection) { logger.info("Truncating collection {} documents ...", collection.id()); houseKeepingClient.queryDocuments(collection.selfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.results())) + .publishOn(Schedulers.parallel()) + .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(doc -> { RequestOptions requestOptions = new RequestOptions(); @@ -228,12 +226,13 @@ protected static void truncateCollection(DocumentCollection collection) { } return houseKeepingClient.deleteDocument(doc.selfLink(), requestOptions); - }).toCompletable().await(); + }).then().block(); logger.info("Truncating collection {} triggers ...", collection.id()); houseKeepingClient.queryTriggers(collection.selfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.results())) + .publishOn(Schedulers.parallel()) + .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(trigger -> { RequestOptions requestOptions = new RequestOptions(); @@ -243,12 +242,13 @@ protected static void truncateCollection(DocumentCollection collection) { // } return houseKeepingClient.deleteTrigger(trigger.selfLink(), requestOptions); - }).toCompletable().await(); + }).then().block(); logger.info("Truncating collection {} storedProcedures ...", collection.id()); houseKeepingClient.queryStoredProcedures(collection.selfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.results())) + .publishOn(Schedulers.parallel()) + .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(storedProcedure -> { RequestOptions requestOptions = new RequestOptions(); @@ -258,12 +258,13 @@ protected static void truncateCollection(DocumentCollection collection) { // } return houseKeepingClient.deleteStoredProcedure(storedProcedure.selfLink(), requestOptions); - }).toCompletable().await(); + }).then().block(); logger.info("Truncating collection {} udfs ...", collection.id()); houseKeepingClient.queryUserDefinedFunctions(collection.selfLink(), "SELECT * FROM root", options) - .flatMap(page -> Observable.from(page.results())) + .publishOn(Schedulers.parallel()) + .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(udf -> { RequestOptions requestOptions = new RequestOptions(); @@ -273,7 +274,7 @@ protected static void truncateCollection(DocumentCollection collection) { // } return houseKeepingClient.deleteUserDefinedFunction(udf.selfLink(), requestOptions); - }).toCompletable().await(); + }).then().block(); } finally { houseKeepingClient.close(); @@ -307,7 +308,7 @@ public static DocumentCollection createCollection(String databaseId, RequestOptions options) { AsyncDocumentClient client = createGatewayHouseKeepingDocumentClient().build(); try { - return client.createCollection("dbs/" + databaseId, collection, options).toBlocking().single().getResource(); + return client.createCollection("dbs/" + databaseId, collection, options).single().block().getResource(); } finally { client.close(); } @@ -315,12 +316,12 @@ public static DocumentCollection createCollection(String databaseId, public static DocumentCollection createCollection(AsyncDocumentClient client, String databaseId, DocumentCollection collection, RequestOptions options) { - return client.createCollection("dbs/" + databaseId, collection, options).toBlocking().single().getResource(); + return client.createCollection("dbs/" + databaseId, collection, options).single().block().getResource(); } public static DocumentCollection createCollection(AsyncDocumentClient client, String databaseId, DocumentCollection collection) { - return client.createCollection("dbs/" + databaseId, collection, null).toBlocking().single().getResource(); + return client.createCollection("dbs/" + databaseId, collection, null).single().block().getResource(); } private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { @@ -444,43 +445,33 @@ public static Document createDocument(AsyncDocumentClient client, String databas } public static Document createDocument(AsyncDocumentClient client, String databaseId, String collectionId, Document document, RequestOptions options) { - return client.createDocument(Utils.getCollectionNameLink(databaseId, collectionId), document, options, false).toBlocking().single().getResource(); + return client.createDocument(Utils.getCollectionNameLink(databaseId, collectionId), document, options, false).single().block().getResource(); } - public Observable> bulkInsert(AsyncDocumentClient client, + public Flux> bulkInsert(AsyncDocumentClient client, String collectionLink, List documentDefinitionList, int concurrencyLevel) { - ArrayList>> result = new ArrayList>>(documentDefinitionList.size()); + ArrayList>> result = new ArrayList<>(documentDefinitionList.size()); for (Document docDef : documentDefinitionList) { result.add(client.createDocument(collectionLink, docDef, null, false)); } - return Observable.merge(result, concurrencyLevel); + return Flux.merge(Flux.fromIterable(result), concurrencyLevel).publishOn(Schedulers.parallel()); } - public Observable> bulkInsert(AsyncDocumentClient client, + public Flux> bulkInsert(AsyncDocumentClient client, String collectionLink, List documentDefinitionList) { return bulkInsert(client, collectionLink, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL); } - public List bulkInsertBlocking(AsyncDocumentClient client, - String collectionLink, - List documentDefinitionList) { - return bulkInsert(client, collectionLink, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) - .map(ResourceResponse::getResource) - .toList() - .toBlocking() - .single(); - } - public static ConsistencyLevel getAccountDefaultConsistencyLevel(AsyncDocumentClient client) { - return client.getDatabaseAccount().toBlocking().single().getConsistencyPolicy().getDefaultConsistencyLevel(); + return client.getDatabaseAccount().single().block().getConsistencyPolicy().getDefaultConsistencyLevel(); } public static User createUser(AsyncDocumentClient client, String databaseId, User user) { - return client.createUser("dbs/" + databaseId, user, null).toBlocking().single().getResource(); + return client.createUser("dbs/" + databaseId, user, null).single().block().getResource(); } public static User safeCreateUser(AsyncDocumentClient client, String databaseId, User user) { @@ -541,7 +532,7 @@ static protected DocumentCollection getCollectionDefinitionWithRangeRangeIndex() public static void deleteCollectionIfExists(AsyncDocumentClient client, String databaseId, String collectionId) { List res = client.queryCollections("dbs/" + databaseId, - String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null).toBlocking().single() + String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null).single().block() .results(); if (!res.isEmpty()) { deleteCollection(client, Utils.getCollectionNameLink(databaseId, collectionId)); @@ -549,7 +540,7 @@ public static void deleteCollectionIfExists(AsyncDocumentClient client, String d } public static void deleteCollection(AsyncDocumentClient client, String collectionLink) { - client.deleteCollection(collectionLink, null).toBlocking().single(); + client.deleteCollection(collectionLink, null).single().block(); } public static void deleteDocumentIfExists(AsyncDocumentClient client, String databaseId, String collectionId, String docId) { @@ -557,7 +548,7 @@ public static void deleteDocumentIfExists(AsyncDocumentClient client, String dat options.partitionKey(new PartitionKey(docId)); List res = client .queryDocuments(Utils.getCollectionNameLink(databaseId, collectionId), String.format("SELECT * FROM root r where r.id = '%s'", docId), options) - .toBlocking().single().results(); + .single().block().results(); if (!res.isEmpty()) { deleteDocument(client, Utils.getDocumentNameLink(databaseId, collectionId, docId)); } @@ -566,7 +557,7 @@ public static void deleteDocumentIfExists(AsyncDocumentClient client, String dat public static void safeDeleteDocument(AsyncDocumentClient client, String documentLink, RequestOptions options) { if (client != null && documentLink != null) { try { - client.deleteDocument(documentLink, options).toBlocking().single(); + client.deleteDocument(documentLink, options).single().block(); } catch (Exception e) { CosmosClientException dce = com.azure.data.cosmos.internal.Utils.as(e, CosmosClientException.class); if (dce == null || dce.statusCode() != 404) { @@ -577,20 +568,20 @@ public static void safeDeleteDocument(AsyncDocumentClient client, String documen } public static void deleteDocument(AsyncDocumentClient client, String documentLink) { - client.deleteDocument(documentLink, null).toBlocking().single(); + client.deleteDocument(documentLink, null).single().block(); } public static void deleteUserIfExists(AsyncDocumentClient client, String databaseId, String userId) { List res = client .queryUsers("dbs/" + databaseId, String.format("SELECT * FROM root r where r.id = '%s'", userId), null) - .toBlocking().single().results(); + .single().block().results(); if (!res.isEmpty()) { deleteUser(client, Utils.getUserNameLink(databaseId, userId)); } } public static void deleteUser(AsyncDocumentClient client, String userLink) { - client.deleteUser(userLink, null).toBlocking().single(); + client.deleteUser(userLink, null).single().block(); } public static String getDatabaseLink(Database database) { @@ -603,8 +594,8 @@ static private Database safeCreateDatabase(AsyncDocumentClient client, Database } static protected Database createDatabase(AsyncDocumentClient client, Database database) { - Observable> databaseObservable = client.createDatabase(database, null); - return databaseObservable.toBlocking().single().getResource(); + Flux> databaseObservable = client.createDatabase(database, null); + return databaseObservable.single().block().getResource(); } static protected Database createDatabase(AsyncDocumentClient client, String databaseId) { @@ -614,15 +605,15 @@ static protected Database createDatabase(AsyncDocumentClient client, String data } static protected Database createDatabaseIfNotExists(AsyncDocumentClient client, String databaseId) { - return client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null).flatMap(p -> Observable.from(p.results())).switchIfEmpty( - Observable.defer(() -> { + return client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null).flatMap(p -> Flux.fromIterable(p.results())).switchIfEmpty( + Flux.defer(() -> { Database databaseDefinition = new Database(); databaseDefinition.id(databaseId); return client.createDatabase(databaseDefinition, null).map(ResourceResponse::getResource); }) - ).toBlocking().single(); + ).single().block(); } static protected void safeDeleteDatabase(AsyncDocumentClient client, Database database) { @@ -634,7 +625,7 @@ static protected void safeDeleteDatabase(AsyncDocumentClient client, Database da static protected void safeDeleteDatabase(AsyncDocumentClient client, String databaseId) { if (client != null) { try { - client.deleteDatabase(Utils.getDatabaseNameLink(databaseId), null).toBlocking().single(); + client.deleteDatabase(Utils.getDatabaseNameLink(databaseId), null).single().block(); } catch (Exception e) { } } @@ -643,13 +634,13 @@ static protected void safeDeleteDatabase(AsyncDocumentClient client, String data static protected void safeDeleteAllCollections(AsyncDocumentClient client, Database database) { if (database != null) { List collections = client.readCollections(database.selfLink(), null) - .flatMap(p -> Observable.from(p.results())) - .toList() - .toBlocking() - .single(); + .flatMap(p -> Flux.fromIterable(p.results())) + .collectList() + .single() + .block(); for (DocumentCollection collection : collections) { - client.deleteCollection(collection.selfLink(), null).toBlocking().single().getResource(); + client.deleteCollection(collection.selfLink(), null).single().block().getResource(); } } } @@ -657,7 +648,7 @@ static protected void safeDeleteAllCollections(AsyncDocumentClient client, Datab static protected void safeDeleteCollection(AsyncDocumentClient client, DocumentCollection collection) { if (client != null && collection != null) { try { - client.deleteCollection(collection.selfLink(), null).toBlocking().single(); + client.deleteCollection(collection.selfLink(), null).single().block(); } catch (Exception e) { } } @@ -666,7 +657,7 @@ static protected void safeDeleteCollection(AsyncDocumentClient client, DocumentC static protected void safeDeleteCollection(AsyncDocumentClient client, String databaseId, String collectionId) { if (client != null && databaseId != null && collectionId != null) { try { - client.deleteCollection("/dbs/" + databaseId + "/colls/" + collectionId, null).toBlocking().single(); + client.deleteCollection("/dbs/" + databaseId + "/colls/" + collectionId, null).single().block(); } catch (Exception e) { } } @@ -694,75 +685,75 @@ static protected void safeClose(AsyncDocumentClient client) { } } - public void validateSuccess(Observable> observable, + public void validateSuccess(Flux> observable, ResourceResponseValidator validator) { validateSuccess(observable, validator, subscriberValidationTimeout); } - public static void validateSuccess(Observable> observable, + public static void validateSuccess(Flux> observable, ResourceResponseValidator validator, long timeout) { - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); + testSubscriber.assertComplete(); testSubscriber.assertValueCount(1); - validator.validate(testSubscriber.getOnNextEvents().get(0)); + validator.validate(testSubscriber.values().get(0)); } - public void validateFailure(Observable> observable, + public void validateFailure(Flux> observable, FailureValidator validator) { validateFailure(observable, validator, subscriberValidationTimeout); } - public static void validateFailure(Observable> observable, + public static void validateFailure(Flux> observable, FailureValidator validator, long timeout) { - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + assertThat(testSubscriber.errorCount()).isEqualTo(1); + validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } - public void validateQuerySuccess(Observable> observable, + public void validateQuerySuccess(Flux> observable, FeedResponseListValidator validator) { validateQuerySuccess(observable, validator, subscriberValidationTimeout); } - public static void validateQuerySuccess(Observable> observable, + public static void validateQuerySuccess(Flux> observable, FeedResponseListValidator validator, long timeout) { - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); - validator.validate(testSubscriber.getOnNextEvents()); + testSubscriber.assertComplete(); + validator.validate(testSubscriber.values()); } - public void validateQueryFailure(Observable> observable, + public void validateQueryFailure(Flux> observable, FailureValidator validator) { validateQueryFailure(observable, validator, subscriberValidationTimeout); } - public static void validateQueryFailure(Observable> observable, + public static void validateQueryFailure(Flux> observable, FailureValidator validator, long timeout) { - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); + TestSubscriber> testSubscriber = new TestSubscriber<>(); observable.subscribe(testSubscriber); testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNotCompleted(); - testSubscriber.assertTerminalEvent(); - assertThat(testSubscriber.getOnErrorEvents()).hasSize(1); - validator.validate(testSubscriber.getOnErrorEvents().get(0)); + testSubscriber.assertNotComplete(); + testSubscriber.assertTerminated(); + assertThat(testSubscriber.errorCount()).isEqualTo(1); + validator.validate((Throwable) testSubscriber.getEvents().get(1).get(0)); } @DataProvider @@ -1008,24 +999,4 @@ public Object[][] queryMetricsArgProvider() { {false}, }; } - - public static class VerboseTestSubscriber extends TestSubscriber { - @Override - public void assertNoErrors() { - List onErrorEvents = getOnErrorEvents(); - StringBuilder errorMessageBuilder = new StringBuilder(); - if (!onErrorEvents.isEmpty()) { - for(Throwable throwable : onErrorEvents) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - throwable.printStackTrace(pw); - String sStackTrace = sw.toString(); // stack trace as a string - errorMessageBuilder.append(sStackTrace); - } - - AssertionError ae = new AssertionError(errorMessageBuilder.toString()); - throw ae; - } - } - } } \ No newline at end of file diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java index 4ceb3c95315c6..85b6cf49a62f9 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java @@ -38,19 +38,16 @@ import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; import org.apache.commons.collections4.list.UnmodifiableList; import org.mockito.Matchers; import org.mockito.Mockito; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import rx.Completable; -import rx.Single; -import rx.functions.Action0; +import reactor.core.publisher.Mono; import java.net.URL; import java.util.ArrayList; @@ -58,13 +55,16 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import static org.assertj.core.api.Assertions.assertThat; +; + public class GlobalAddressResolverTest { - private CompositeHttpClient httpClient; + private HttpClient httpClient; private GlobalEndpointManager endpointManager; private IAuthorizationTokenProvider authorizationTokenProvider; private UserAgentContainer userAgentContainer; @@ -91,7 +91,7 @@ public void setup() throws Exception { connectionPolicy = new ConnectionPolicy(); connectionPolicy.enableReadRequestsFallback(true); - httpClient = Mockito.mock(CompositeHttpClient.class); + httpClient = Mockito.mock(HttpClient.class); endpointManager = Mockito.mock(GlobalEndpointManager.class); List readEndPointList = new ArrayList<>(); @@ -114,7 +114,7 @@ public void setup() throws Exception { DocumentCollection collectionDefinition = new DocumentCollection(); collectionDefinition.id(UUID.randomUUID().toString()); collectionCache = Mockito.mock(RxCollectionCache.class); - Mockito.when(collectionCache.resolveCollectionAsync(Matchers.any(RxDocumentServiceRequest.class))).thenReturn(Single.just(collectionDefinition)); + Mockito.when(collectionCache.resolveCollectionAsync(Matchers.any(RxDocumentServiceRequest.class))).thenReturn(Mono.just(collectionDefinition)); routingMapProvider = Mockito.mock(RxPartitionKeyRangeCache.class); userAgentContainer = Mockito.mock(UserAgentContainer.class); serviceConfigReader = Mockito.mock(GatewayServiceConfigurationReader.class); @@ -171,7 +171,7 @@ public void openAsync() throws Exception { List partitionKeyRanges = new ArrayList<>(); partitionKeyRanges.add(range); Mockito.when(collectionRoutingMap.getOrderedPartitionKeyRanges()).thenReturn(partitionKeyRanges); - Single collectionRoutingMapSingle = Single.just(collectionRoutingMap); + Mono collectionRoutingMapSingle = Mono.just(collectionRoutingMap); Mockito.when(routingMapProvider.tryLookupAsync(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(collectionRoutingMapSingle); List ranges = new ArrayList<>(); @@ -179,15 +179,17 @@ public void openAsync() throws Exception { PartitionKeyRangeIdentity partitionKeyRangeIdentity = new PartitionKeyRangeIdentity(documentCollection.resourceId(), partitionKeyRange.id()); ranges.add(partitionKeyRangeIdentity); } - Completable completable = Completable.fromAction(new Action0() { + + Mono completable = Mono.fromCallable(new Callable() { @Override - public void call() { + public Void call() throws Exception { numberOfTaskCompleted.getAndIncrement(); + return null; } }); Mockito.when(gatewayAddressCache.openAsync(documentCollection, ranges)).thenReturn(completable); - globalAddressResolver.openAsync(documentCollection).await(); + globalAddressResolver.openAsync(documentCollection).block(); assertThat(numberOfTaskCompleted.get()).isEqualTo(2); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java index e46f5a3a6f8e3..e6efbb9bf03f3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java @@ -30,8 +30,7 @@ import com.azure.data.cosmos.directconnectivity.StoreClient; import com.azure.data.cosmos.directconnectivity.TransportClient; import com.azure.data.cosmos.internal.RxDocumentClientImpl; -import io.netty.buffer.ByteBuf; -import io.reactivex.netty.protocol.http.client.CompositeHttpClient; +import com.azure.data.cosmos.internal.http.HttpClient; import org.apache.commons.lang3.reflect.FieldUtils; /** @@ -75,18 +74,13 @@ public static TransportClient getTransportClient(RxDocumentClientImpl client) { return get(TransportClient.class, storeClient, "transportClient"); } - public static void setTransportClient(RxDocumentClientImpl client, TransportClient transportClient) { - StoreClient storeClient = getStoreClient(client); - set(storeClient, transportClient, "transportClient"); - } - - public static CompositeHttpClient getDirectHttpsHttpClient(RxDocumentClientImpl client) { + public static HttpClient getDirectHttpsHttpClient(RxDocumentClientImpl client) { TransportClient transportClient = getTransportClient(client); assert transportClient instanceof HttpTransportClient; - return get(CompositeHttpClient.class, transportClient, "httpClient"); + return get(HttpClient.class, transportClient, "httpClient"); } - public static void setDirectHttpsHttpClient(RxDocumentClientImpl client, CompositeHttpClient newHttpClient) { + public static void setDirectHttpsHttpClient(RxDocumentClientImpl client, HttpClient newHttpClient) { TransportClient transportClient = getTransportClient(client); assert transportClient instanceof HttpTransportClient; set(transportClient, newHttpClient, "httpClient"); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java index 692a9942c3688..ca84a0fb8f4aa 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java @@ -43,6 +43,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.LinkedListMultimap; +import io.reactivex.subscribers.TestSubscriber; import org.apache.commons.lang3.RandomUtils; import org.mockito.Matchers; import org.mockito.Mockito; @@ -50,11 +51,8 @@ import org.slf4j.LoggerFactory; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Observable; -import rx.Single; -import rx.functions.Func1; -import rx.functions.Func3; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import java.net.URL; import java.util.ArrayList; @@ -96,20 +94,13 @@ public class DocumentProducerTest { @DataProvider(name = "splitParamProvider") public Object[][] splitParamProvider() { - return new Object[][] { + return new Object[][]{ // initial continuation token, // # pages from parent before split, // # pages from left child after split, // # pages from right child after split - { "init-cp", 10, 5, 6 }, - { null, 10, 5, 6 }, - { null, 1000, 500, 600 }, - { "init-cp", 1000, 500, 600 }, - { "init-cp", 0, 10, 12 }, - { null, 0, 10, 12 }, - { null, 0, 1, 1 }, - { null, 10, 1, 1 }, - }; + {"init-cp", 10, 5, 6}, {null, 10, 5, 6}, {null, 1000, 500, 600}, {"init-cp", 1000, 500, 600}, {"init" + + "-cp", 0, 10, 12}, {null, 0, 10, 12}, {null, 0, 1, 1}, {null, 10, 1, 1},}; } private IRetryPolicyFactory mockDocumentClientIRetryPolicyFactory() { @@ -126,11 +117,9 @@ private IRetryPolicyFactory mockDocumentClientIRetryPolicyFactory() { return new RetryPolicy(globalEndpointManager, ConnectionPolicy.defaultPolicy()); } - @Test(groups = { "unit" }, dataProvider = "splitParamProvider", timeOut = TIMEOUT) - public void partitionSplit(String initialContinuationToken, - int numberOfResultPagesFromParentBeforeSplit, - int numberOfResultPagesFromLeftChildAfterSplit, - int numberOfResultPagesFromRightChildAfterSplit) { + @Test(groups = {"unit"}, dataProvider = "splitParamProvider", timeOut = TIMEOUT) + public void partitionSplit(String initialContinuationToken, int numberOfResultPagesFromParentBeforeSplit, + int numberOfResultPagesFromLeftChildAfterSplit, int numberOfResultPagesFromRightChildAfterSplit) { int initialPageSize = 7; int top = -1; @@ -138,37 +127,45 @@ public void partitionSplit(String initialContinuationToken, String leftChildPartitionId = "2"; String rightChildPartitionId = "3"; - List> resultFromParentPartition = mockFeedResponses(parentPartitionId, numberOfResultPagesFromParentBeforeSplit, 3, false); - List> resultFromLeftChildPartition = mockFeedResponses(leftChildPartitionId, numberOfResultPagesFromLeftChildAfterSplit, 3, true); - List> resultFromRightChildPartition = mockFeedResponses(rightChildPartitionId, numberOfResultPagesFromRightChildAfterSplit, 3, true); + List> resultFromParentPartition = mockFeedResponses(parentPartitionId, + numberOfResultPagesFromParentBeforeSplit, 3, false); + List> resultFromLeftChildPartition = mockFeedResponses(leftChildPartitionId, + numberOfResultPagesFromLeftChildAfterSplit, 3, true); + List> resultFromRightChildPartition = mockFeedResponses(rightChildPartitionId, + numberOfResultPagesFromRightChildAfterSplit, 3, true); // sanity check sanityCheckSplitValidation(parentPartitionId, leftChildPartitionId, rightChildPartitionId, - numberOfResultPagesFromParentBeforeSplit, - numberOfResultPagesFromLeftChildAfterSplit, - numberOfResultPagesFromRightChildAfterSplit, - resultFromParentPartition, resultFromLeftChildPartition, resultFromRightChildPartition); + numberOfResultPagesFromParentBeforeSplit, + numberOfResultPagesFromLeftChildAfterSplit, + numberOfResultPagesFromRightChildAfterSplit, resultFromParentPartition, + resultFromLeftChildPartition, resultFromRightChildPartition); // setting up behaviour - RequestExecutor.PartitionAnswer answerFromParentPartition = RequestExecutor.PartitionAnswer.just(parentPartitionId, resultFromParentPartition); - RequestExecutor.PartitionAnswer splitAnswerFromParentPartition = RequestExecutor.PartitionAnswer.alwaysPartitionSplit(parentPartitionId); + RequestExecutor.PartitionAnswer answerFromParentPartition = + RequestExecutor.PartitionAnswer.just(parentPartitionId, resultFromParentPartition); + RequestExecutor.PartitionAnswer splitAnswerFromParentPartition = + RequestExecutor.PartitionAnswer.alwaysPartitionSplit(parentPartitionId); - RequestExecutor.PartitionAnswer answerFromLeftChildPartition = RequestExecutor.PartitionAnswer.just(leftChildPartitionId, resultFromLeftChildPartition); - RequestExecutor.PartitionAnswer answerFromRightChildPartition = RequestExecutor.PartitionAnswer.just(rightChildPartitionId, resultFromRightChildPartition); + RequestExecutor.PartitionAnswer answerFromLeftChildPartition = + RequestExecutor.PartitionAnswer.just(leftChildPartitionId, resultFromLeftChildPartition); + RequestExecutor.PartitionAnswer answerFromRightChildPartition = + RequestExecutor.PartitionAnswer.just(rightChildPartitionId, resultFromRightChildPartition); RequestCreator requestCreator = RequestCreator.simpleMock(); RequestExecutor requestExecutor = RequestExecutor. fromPartitionAnswer(ImmutableList.of(answerFromParentPartition, splitAnswerFromParentPartition, - answerFromLeftChildPartition, answerFromRightChildPartition)); + answerFromLeftChildPartition, answerFromRightChildPartition)); PartitionKeyRange parentPartitionKeyRange = mockPartitionKeyRange(parentPartitionId); PartitionKeyRange leftChildPartitionKeyRange = mockPartitionKeyRange(leftChildPartitionId); PartitionKeyRange rightChildPartitionKeyRange = mockPartitionKeyRange(rightChildPartitionId); // this returns replacement ranges upon split detection - IDocumentQueryClient queryClient = mockQueryClient(ImmutableList.of(leftChildPartitionKeyRange, rightChildPartitionKeyRange)); + IDocumentQueryClient queryClient = mockQueryClient(ImmutableList.of(leftChildPartitionKeyRange, + rightChildPartitionKeyRange)); - DocumentProducer documentProducer = new DocumentProducer( + DocumentProducer documentProducer = new DocumentProducer<>( queryClient, collectionRid, null, @@ -189,7 +186,7 @@ public void partitionSplit(String initialContinuationToken, subscriber.awaitTerminalEvent(); subscriber.assertNoErrors(); - subscriber.assertCompleted(); + subscriber.assertComplete(); validateSplitCaptureRequests( requestCreator.invocations, @@ -206,17 +203,17 @@ public void partitionSplit(String initialContinuationToken, .distinct().collect(Collectors.toList())).containsExactlyElementsOf(Collections.singleton(initialPageSize)); // expected results - validateSplitResults(subscriber.getOnNextEvents(), parentPartitionId, leftChildPartitionId, rightChildPartitionId, resultFromParentPartition, - resultFromLeftChildPartition, resultFromRightChildPartition, false); + validateSplitResults(subscriber.values(), + parentPartitionId, leftChildPartitionId, + rightChildPartitionId, resultFromParentPartition, resultFromLeftChildPartition, + resultFromRightChildPartition, false); Mockito.verify(queryClient, times(1)).getPartitionKeyRangeCache(); } - @Test(groups = { "unit" }, dataProvider = "splitParamProvider", timeOut = TIMEOUT) - public void orderByPartitionSplit(String initialContinuationToken, - int numberOfResultPagesFromParentBeforeSplit, - int numberOfResultPagesFromLeftChildAfterSplit, - int numberOfResultPagesFromRightChildAfterSplit) { + @Test(groups = {"unit"}, dataProvider = "splitParamProvider", timeOut = TIMEOUT) + public void orderByPartitionSplit(String initialContinuationToken, int numberOfResultPagesFromParentBeforeSplit, + int numberOfResultPagesFromLeftChildAfterSplit, int numberOfResultPagesFromRightChildAfterSplit) { int initialPageSize = 7; int top = -1; @@ -225,60 +222,52 @@ public void orderByPartitionSplit(String initialContinuationToken, String rightChildPartitionId = "3"; Integer initialPropVal = 1; - List> resultFromParentPartition = mockFeedResponses( - parentPartitionId, numberOfResultPagesFromParentBeforeSplit, 3, initialPropVal, false); + List> resultFromParentPartition = mockFeedResponses(parentPartitionId, + numberOfResultPagesFromParentBeforeSplit, 3, initialPropVal, false); Integer highestValInParentPage = getLastValueInAsc(initialPropVal, resultFromParentPartition); List> resultFromLeftChildPartition = mockFeedResponses(leftChildPartitionId, - numberOfResultPagesFromLeftChildAfterSplit, 3, highestValInParentPage,true); + numberOfResultPagesFromLeftChildAfterSplit, 3, highestValInParentPage, true); List> resultFromRightChildPartition = mockFeedResponses(rightChildPartitionId, - numberOfResultPagesFromRightChildAfterSplit, 3, highestValInParentPage,true); + numberOfResultPagesFromRightChildAfterSplit, 3, highestValInParentPage, true); // sanity check sanityCheckSplitValidation(parentPartitionId, leftChildPartitionId, rightChildPartitionId, - numberOfResultPagesFromParentBeforeSplit, - numberOfResultPagesFromLeftChildAfterSplit, - numberOfResultPagesFromRightChildAfterSplit, - resultFromParentPartition, resultFromLeftChildPartition, resultFromRightChildPartition); + numberOfResultPagesFromParentBeforeSplit, + numberOfResultPagesFromLeftChildAfterSplit, + numberOfResultPagesFromRightChildAfterSplit, resultFromParentPartition, + resultFromLeftChildPartition, resultFromRightChildPartition); // setting up behaviour - RequestExecutor.PartitionAnswer answerFromParentPartition = RequestExecutor.PartitionAnswer.just( - parentPartitionId, resultFromParentPartition); - RequestExecutor.PartitionAnswer splitAnswerFromParentPartition = RequestExecutor - .PartitionAnswer.alwaysPartitionSplit(parentPartitionId); + RequestExecutor.PartitionAnswer answerFromParentPartition = + RequestExecutor.PartitionAnswer.just(parentPartitionId, resultFromParentPartition); + RequestExecutor.PartitionAnswer splitAnswerFromParentPartition = + RequestExecutor.PartitionAnswer.alwaysPartitionSplit(parentPartitionId); - RequestExecutor.PartitionAnswer answerFromLeftChildPartition = RequestExecutor.PartitionAnswer.just(leftChildPartitionId, resultFromLeftChildPartition); - RequestExecutor.PartitionAnswer answerFromRightChildPartition = RequestExecutor.PartitionAnswer.just(rightChildPartitionId, resultFromRightChildPartition); + RequestExecutor.PartitionAnswer answerFromLeftChildPartition = + RequestExecutor.PartitionAnswer.just(leftChildPartitionId, resultFromLeftChildPartition); + RequestExecutor.PartitionAnswer answerFromRightChildPartition = + RequestExecutor.PartitionAnswer.just(rightChildPartitionId, resultFromRightChildPartition); RequestCreator requestCreator = RequestCreator.simpleMock(); RequestExecutor requestExecutor = RequestExecutor. fromPartitionAnswer(ImmutableList.of(answerFromParentPartition, splitAnswerFromParentPartition, - answerFromLeftChildPartition, answerFromRightChildPartition)); + answerFromLeftChildPartition, answerFromRightChildPartition)); PartitionKeyRange parentPartitionKeyRange = mockPartitionKeyRange(parentPartitionId); PartitionKeyRange leftChildPartitionKeyRange = mockPartitionKeyRange(leftChildPartitionId); PartitionKeyRange rightChildPartitionKeyRange = mockPartitionKeyRange(rightChildPartitionId); // this returns replacement ranges upon split detection - IDocumentQueryClient queryCl = mockQueryClient( - ImmutableList.of(leftChildPartitionKeyRange, rightChildPartitionKeyRange)); - - OrderByDocumentProducer documentProducer = new OrderByDocumentProducer<>( - new OrderbyRowComparer<>(ImmutableList.of(SortOrder.Ascending)), - queryCl, - collectionRid, - null, - requestCreator, - requestExecutor, - parentPartitionKeyRange, - collectionLink, - null, - Document.class, - null, - initialPageSize, - initialContinuationToken, - top, + IDocumentQueryClient queryCl = mockQueryClient(ImmutableList.of(leftChildPartitionKeyRange, + rightChildPartitionKeyRange)); + + OrderByDocumentProducer documentProducer = + new OrderByDocumentProducer<>(new OrderbyRowComparer<>(ImmutableList.of(SortOrder.Ascending)), + queryCl, collectionRid, null, requestCreator, requestExecutor, + parentPartitionKeyRange, collectionLink, null, Document.class, null, + initialPageSize, initialContinuationToken, top, /*targetRangeToOrderByContinuationTokenMap*/new HashMap<>()); TestSubscriber.DocumentProducerFeedResponse> subscriber = new TestSubscriber<>(); @@ -287,34 +276,25 @@ public void orderByPartitionSplit(String initialContinuationToken, subscriber.awaitTerminalEvent(); subscriber.assertNoErrors(); - subscriber.assertCompleted(); + subscriber.assertComplete(); - validateSplitCaptureRequests( - requestCreator.invocations, - initialContinuationToken, - parentPartitionId, - leftChildPartitionId, - rightChildPartitionId, - resultFromParentPartition, - resultFromLeftChildPartition, - resultFromRightChildPartition); + validateSplitCaptureRequests(requestCreator.invocations, initialContinuationToken, parentPartitionId, + leftChildPartitionId, rightChildPartitionId, resultFromParentPartition, + resultFromLeftChildPartition, resultFromRightChildPartition); // page size match - assertThat(requestCreator.invocations.stream().map(i -> i.maxItemCount) - .distinct().collect(Collectors.toList())).containsExactlyElementsOf(Collections.singleton(initialPageSize)); + assertThat(requestCreator.invocations.stream().map(i -> i.maxItemCount).distinct().collect(Collectors.toList())).containsExactlyElementsOf(Collections.singleton(initialPageSize)); // expected results - validateSplitResults(subscriber.getOnNextEvents(), - parentPartitionId, - leftChildPartitionId, - rightChildPartitionId, - resultFromParentPartition, - resultFromLeftChildPartition, resultFromRightChildPartition, true); + validateSplitResults(subscriber.values(), + parentPartitionId, leftChildPartitionId, + rightChildPartitionId, resultFromParentPartition, resultFromLeftChildPartition, + resultFromRightChildPartition, true); Mockito.verify(queryCl, times(1)).getPartitionKeyRangeCache(); } - @Test(groups = { "unit" }, timeOut = TIMEOUT) + @Test(groups = {"unit"}, timeOut = TIMEOUT) public void simple() { int initialPageSize = 7; int top = -1; @@ -322,34 +302,24 @@ public void simple() { String partitionId = "1"; List requests = new ArrayList<>(); - for(int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) { requests.add(mockRequest(partitionId)); } List> responses = mockFeedResponses(partitionId, 10, 3, true); RequestCreator requestCreator = RequestCreator.give(requests); - RequestExecutor requestExecutor = RequestExecutor.fromPartitionAnswer( - RequestExecutor.PartitionAnswer.just("1", responses)); + RequestExecutor requestExecutor = RequestExecutor.fromPartitionAnswer(RequestExecutor.PartitionAnswer.just("1" + , responses)); PartitionKeyRange targetRange = mockPartitionKeyRange(partitionId); IDocumentQueryClient queryClient = Mockito.mock(IDocumentQueryClient.class); String initialContinuationToken = "initial-cp"; - DocumentProducer documentProducer = new DocumentProducer<>( - queryClient, - collectionRid, - null, - requestCreator, - requestExecutor, - targetRange, - collectionLink, - () -> mockDocumentClientIRetryPolicyFactory().getRequestPolicy(), - Document.class, - null, - initialPageSize, - initialContinuationToken, - top); + DocumentProducer documentProducer = new DocumentProducer<>(queryClient, collectionRid, null, + requestCreator, requestExecutor, + targetRange, collectionLink, + () -> mockDocumentClientIRetryPolicyFactory().getRequestPolicy(), Document.class, null, initialPageSize, initialContinuationToken, top); TestSubscriber subscriber = new TestSubscriber<>(); @@ -357,30 +327,25 @@ public void simple() { subscriber.awaitTerminalEvent(); subscriber.assertNoErrors(); - subscriber.assertCompleted(); + subscriber.assertComplete(); subscriber.assertValueCount(responses.size()); // requests match - assertThat(requestCreator.invocations.stream().map(i -> i.invocationResult) - .collect(Collectors.toList())).containsExactlyElementsOf(requests); + assertThat(requestCreator.invocations.stream().map(i -> i.invocationResult).collect(Collectors.toList())).containsExactlyElementsOf(requests); // requested max page size match - assertThat(requestCreator.invocations.stream().map(i -> i.maxItemCount) - .distinct().collect(Collectors.toList())).containsExactlyElementsOf(Collections.singleton(7)); + assertThat(requestCreator.invocations.stream().map(i -> i.maxItemCount).distinct().collect(Collectors.toList())).containsExactlyElementsOf(Collections.singleton(7)); // continuation tokens assertThat(requestCreator.invocations.get(0).continuationToken).isEqualTo(initialContinuationToken); - assertThat(requestCreator.invocations.stream().skip(1).map(i -> i.continuationToken) - .collect(Collectors.toList())).containsExactlyElementsOf( - responses.stream().limit(9).map(r -> r.continuationToken()).collect(Collectors.toList())); + assertThat(requestCreator.invocations.stream().skip(1).map(i -> i.continuationToken).collect(Collectors.toList())).containsExactlyElementsOf(responses.stream().limit(9).map(r -> r.continuationToken()).collect(Collectors.toList())); // source partition - assertThat(requestCreator.invocations.stream().map(i -> i.sourcePartition).distinct() - .collect(Collectors.toList())).containsExactlyElementsOf(Collections.singletonList(targetRange)); + assertThat(requestCreator.invocations.stream().map(i -> i.sourcePartition).distinct().collect(Collectors.toList())).containsExactlyElementsOf(Collections.singletonList(targetRange)); } - @Test(groups = { "unit" }, timeOut = TIMEOUT) + @Test(groups = {"unit"}, timeOut = TIMEOUT) public void retries() { int initialPageSize = 7; int top = -1; @@ -393,30 +358,26 @@ public void retries() { Exception throttlingException = mockThrottlingException(10); List> responsesAfterThrottle = mockFeedResponses(partitionKeyRangeId, 5, 1, true); - RequestExecutor.PartitionAnswer behaviourBeforeException = RequestExecutor.PartitionAnswer.just(partitionKeyRangeId, responsesBeforeThrottle); - RequestExecutor.PartitionAnswer exceptionBehaviour = RequestExecutor.PartitionAnswer.errors(partitionKeyRangeId, Collections.singletonList(throttlingException)); - RequestExecutor.PartitionAnswer behaviourAfterException = RequestExecutor.PartitionAnswer.just(partitionKeyRangeId, responsesAfterThrottle); + RequestExecutor.PartitionAnswer behaviourBeforeException = + RequestExecutor.PartitionAnswer.just(partitionKeyRangeId, responsesBeforeThrottle); + RequestExecutor.PartitionAnswer exceptionBehaviour = + RequestExecutor.PartitionAnswer.errors(partitionKeyRangeId, + Collections.singletonList(throttlingException)); + RequestExecutor.PartitionAnswer behaviourAfterException = + RequestExecutor.PartitionAnswer.just(partitionKeyRangeId, responsesAfterThrottle); - RequestExecutor requestExecutor = RequestExecutor.fromPartitionAnswer(behaviourBeforeException, exceptionBehaviour, behaviourAfterException); + RequestExecutor requestExecutor = RequestExecutor.fromPartitionAnswer(behaviourBeforeException, + exceptionBehaviour, + behaviourAfterException); PartitionKeyRange targetRange = mockPartitionKeyRange(partitionKeyRangeId); IDocumentQueryClient queryClient = Mockito.mock(IDocumentQueryClient.class); String initialContinuationToken = "initial-cp"; - DocumentProducer documentProducer = new DocumentProducer<>( - queryClient, - collectionRid, - null, - requestCreator, - requestExecutor, - targetRange, - collectionLink, - () -> mockDocumentClientIRetryPolicyFactory().getRequestPolicy(), - Document.class, - null, - initialPageSize, - initialContinuationToken, - top); + DocumentProducer documentProducer = new DocumentProducer<>(queryClient, collectionRid, null, + requestCreator, requestExecutor, + targetRange, collectionLink, + () -> mockDocumentClientIRetryPolicyFactory().getRequestPolicy(), Document.class, null, initialPageSize, initialContinuationToken, top); TestSubscriber subscriber = new TestSubscriber<>(); @@ -424,48 +385,36 @@ public void retries() { subscriber.awaitTerminalEvent(); subscriber.assertNoErrors(); - subscriber.assertCompleted(); + subscriber.assertComplete(); subscriber.assertValueCount(responsesBeforeThrottle.size() + responsesAfterThrottle.size()); // requested max page size match - assertThat(requestCreator.invocations.stream().map(i -> i.maxItemCount) - .distinct().collect(Collectors.toList())).containsExactlyElementsOf(Collections.singleton(7)); + assertThat(requestCreator.invocations.stream().map(i -> i.maxItemCount).distinct().collect(Collectors.toList())).containsExactlyElementsOf(Collections.singleton(7)); // continuation tokens assertThat(requestCreator.invocations.get(0).continuationToken).isEqualTo(initialContinuationToken); // source partition - assertThat(requestCreator.invocations.stream().map(i -> i.sourcePartition).distinct() - .collect(Collectors.toList())).containsExactlyElementsOf(Collections.singletonList(targetRange)); + assertThat(requestCreator.invocations.stream().map(i -> i.sourcePartition).distinct().collect(Collectors.toList())).containsExactlyElementsOf(Collections.singletonList(targetRange)); - List resultContinuationToken = subscriber.getOnNextEvents() - .stream().map(r -> r.pageResult.continuationToken()).collect(Collectors.toList()); - List beforeExceptionContinuationTokens = responsesBeforeThrottle.stream() - .map(r -> r.continuationToken()).collect(Collectors.toList()); - List afterExceptionContinuationTokens = responsesAfterThrottle.stream() - .map(r -> r.continuationToken()).collect(Collectors.toList()); + List resultContinuationToken = + subscriber.values().stream().map(r -> r.pageResult.continuationToken()).collect(Collectors.toList()); + List beforeExceptionContinuationTokens = + responsesBeforeThrottle.stream().map(FeedResponse::continuationToken).collect(Collectors.toList()); + List afterExceptionContinuationTokens = + responsesAfterThrottle.stream().map(FeedResponse::continuationToken).collect(Collectors.toList()); - assertThat(resultContinuationToken).containsExactlyElementsOf( - Iterables.concat(beforeExceptionContinuationTokens, afterExceptionContinuationTokens)); + assertThat(resultContinuationToken).containsExactlyElementsOf(Iterables.concat(beforeExceptionContinuationTokens, afterExceptionContinuationTokens)); String continuationTokenOnException = Iterables.getLast(beforeExceptionContinuationTokens); - assertThat(requestCreator.invocations.stream().map(cr -> cr.continuationToken)).containsExactlyElementsOf( - Iterables.concat( - ImmutableList.of(initialContinuationToken), - Iterables.limit(resultContinuationToken, resultContinuationToken.size()-1))); - - assertThat(requestExecutor.partitionKeyRangeIdToCapturedInvocation.get(partitionKeyRangeId) - .stream().map(cr -> cr.request.getContinuation())).containsExactlyElementsOf( - Iterables.concat( - ImmutableList.of(initialContinuationToken), - beforeExceptionContinuationTokens, - Collections.singletonList(continuationTokenOnException), - Iterables.limit(afterExceptionContinuationTokens, afterExceptionContinuationTokens.size()-1))); + assertThat(requestCreator.invocations.stream().map(cr -> cr.continuationToken)).containsExactlyElementsOf(Iterables.concat(ImmutableList.of(initialContinuationToken), Iterables.limit(resultContinuationToken, resultContinuationToken.size() - 1))); + + assertThat(requestExecutor.partitionKeyRangeIdToCapturedInvocation.get(partitionKeyRangeId).stream().map(cr -> cr.request.getContinuation())).containsExactlyElementsOf(Iterables.concat(ImmutableList.of(initialContinuationToken), beforeExceptionContinuationTokens, Collections.singletonList(continuationTokenOnException), Iterables.limit(afterExceptionContinuationTokens, afterExceptionContinuationTokens.size() - 1))); } - @Test(groups = { "unit" }, timeOut = TIMEOUT) + @Test(groups = {"unit"}, timeOut = TIMEOUT) public void retriesExhausted() { int initialPageSize = 7; int top = -1; @@ -477,29 +426,23 @@ public void retriesExhausted() { List> responsesBeforeThrottle = mockFeedResponses(partitionKeyRangeId, 1, 1, false); Exception throttlingException = mockThrottlingException(10); - RequestExecutor.PartitionAnswer behaviourBeforeException = RequestExecutor.PartitionAnswer.just(partitionKeyRangeId, responsesBeforeThrottle); - RequestExecutor.PartitionAnswer exceptionBehaviour = RequestExecutor.PartitionAnswer.errors(partitionKeyRangeId, Collections.nCopies(10, throttlingException)); + RequestExecutor.PartitionAnswer behaviourBeforeException = + RequestExecutor.PartitionAnswer.just(partitionKeyRangeId, responsesBeforeThrottle); + RequestExecutor.PartitionAnswer exceptionBehaviour = + RequestExecutor.PartitionAnswer.errors(partitionKeyRangeId, Collections.nCopies(10, + throttlingException)); - RequestExecutor requestExecutor = RequestExecutor.fromPartitionAnswer(behaviourBeforeException, exceptionBehaviour); + RequestExecutor requestExecutor = RequestExecutor.fromPartitionAnswer(behaviourBeforeException, + exceptionBehaviour); PartitionKeyRange targetRange = mockPartitionKeyRange(partitionKeyRangeId); IDocumentQueryClient queryClient = Mockito.mock(IDocumentQueryClient.class); String initialContinuationToken = "initial-cp"; - DocumentProducer documentProducer = new DocumentProducer<>( - queryClient, - collectionRid, - null, - requestCreator, - requestExecutor, - targetRange, - collectionRid, - () -> mockDocumentClientIRetryPolicyFactory().getRequestPolicy(), - Document.class, - null, - initialPageSize, - initialContinuationToken, - top); + DocumentProducer documentProducer = new DocumentProducer(queryClient, collectionRid, null, + requestCreator, requestExecutor, + targetRange, collectionRid, + () -> mockDocumentClientIRetryPolicyFactory().getRequestPolicy(), Document.class, null, initialPageSize, initialContinuationToken, top); TestSubscriber subscriber = new TestSubscriber<>(); @@ -517,44 +460,28 @@ private CosmosClientException mockThrottlingException(long retriesAfter) { return throttleException; } - private List> mockFeedResponses(String partitionKeyRangeId, - int numberOfPages, - int numberOfDocsPerPage, - boolean completed) { - return mockFeedResponsesPartiallySorted(partitionKeyRangeId, - numberOfPages, - numberOfDocsPerPage, - false, - -1, - completed); + private List> mockFeedResponses(String partitionKeyRangeId, int numberOfPages, + int numberOfDocsPerPage, boolean completed) { + return mockFeedResponsesPartiallySorted(partitionKeyRangeId, numberOfPages, numberOfDocsPerPage, false, -1, + completed); } - private List> mockFeedResponses(String partitionKeyRangeId, - int numberOfPages, - int numberOfDocsPerPage, - int orderByFieldInitialVal, - boolean completed) { - return mockFeedResponsesPartiallySorted(partitionKeyRangeId, - numberOfPages, - numberOfDocsPerPage, - true, - orderByFieldInitialVal, - completed); + private List> mockFeedResponses(String partitionKeyRangeId, int numberOfPages, + int numberOfDocsPerPage, int orderByFieldInitialVal, boolean completed) { + return mockFeedResponsesPartiallySorted(partitionKeyRangeId, numberOfPages, numberOfDocsPerPage, true, + orderByFieldInitialVal, completed); } private List> mockFeedResponsesPartiallySorted(String partitionKeyRangeId, - int numberOfPages, - int numberOfDocsPerPage, - boolean isOrderby, - int orderByFieldInitialVal, - boolean completed) { + int numberOfPages, int numberOfDocsPerPage, boolean isOrderby, int orderByFieldInitialVal, + boolean completed) { String uuid = UUID.randomUUID().toString(); List> responses = new ArrayList<>(); - for(int i = 0; i < numberOfPages; i++) { + for (int i = 0; i < numberOfPages; i++) { FeedResponseBuilder rfb = FeedResponseBuilder.queryFeedResponseBuilder(Document.class); List res = new ArrayList<>(); - for(int j = 0; j < numberOfDocsPerPage; j++) { + for (int j = 0; j < numberOfDocsPerPage; j++) { Document d = getDocumentDefinition(); if (isOrderby) { @@ -565,13 +492,13 @@ private List> mockFeedResponsesPartiallySorted(String par d.set(DocumentPartitionKeyRangeMinInclusiveFieldName, pkr.getMinInclusive()); d.set(DocumentPartitionKeyRangeMaxExclusiveFieldName, pkr.getMaxExclusive()); - QueryItem qi = new QueryItem( - "{ \"item\": " + Integer.toString(d.getInt(OrderByIntFieldName)) + " }"); - String json = "{\"" + OrderByPayloadFieldName + "\" : " + d.toJson() + ", \"" + OrderByItemsFieldName - + "\" : [ " + qi.toJson() + " ] }"; + QueryItem qi = new QueryItem("{ \"item\": " + Integer.toString(d.getInt(OrderByIntFieldName)) + + " }"); + String json = + "{\"" + OrderByPayloadFieldName + "\" : " + d.toJson() + ", \"" + OrderByItemsFieldName + "\" : [ " + qi.toJson() + " ] }"; - OrderByRowResult row = - new OrderByRowResult<>(Document.class, json, mockPartitionKeyRange(partitionKeyRangeId), "backend continuation token"); + OrderByRowResult row = new OrderByRowResult<>(Document.class, json, + mockPartitionKeyRange(partitionKeyRangeId), "backend continuation token"); res.add(row); } else { res.add(d); @@ -591,8 +518,8 @@ private List> mockFeedResponsesPartiallySorted(String par private int getLastValueInAsc(int initialValue, List> responsesList) { Integer value = null; - for(FeedResponse page: responsesList) { - for(Document d: page.results()) { + for (FeedResponse page : responsesList) { + for (Document d : page.results()) { Integer tmp = d.getInt(OrderByIntFieldName); if (tmp != null) { value = tmp; @@ -610,7 +537,7 @@ private IDocumentQueryClient mockQueryClient(List replacement IDocumentQueryClient client = Mockito.mock(IDocumentQueryClient.class); RxPartitionKeyRangeCache cache = Mockito.mock(RxPartitionKeyRangeCache.class); doReturn(cache).when(client).getPartitionKeyRangeCache(); - doReturn(Single.just(replacementRanges)).when(cache). + doReturn(Mono.just(replacementRanges)).when(cache). tryGetOverlappingRangesAsync(anyString(), any(Range.class), anyBoolean(), Matchers.anyMap()); return client; } @@ -630,11 +557,8 @@ private RxDocumentServiceRequest mockRequest(String partitionKeyRangeId) { return req; } - private static void validateSplitCaptureRequests( - List capturedInvocationList, - String initialContinuationToken, - String parentPartitionId, - String leftChildPartitionId, + private static void validateSplitCaptureRequests(List capturedInvocationList, + String initialContinuationToken, String parentPartitionId, String leftChildPartitionId, String rightChildPartitionId, List> expectedResultPagesFromParentPartitionBeforeSplit, List> expectedResultPagesFromLeftChildPartition, @@ -645,104 +569,58 @@ private static void validateSplitCaptureRequests( int numberOfResultPagesFromRightChildAfterSplit = expectedResultPagesFromRightChildPartition.size(); // numberOfResultPagesFromParentBeforeSplit + 1 requests to parent partition - assertThat(capturedInvocationList.stream().limit(numberOfResultPagesFromParentBeforeSplit + 1) - .filter(i -> i.sourcePartition.id().equals(parentPartitionId))) - .hasSize(numberOfResultPagesFromParentBeforeSplit + 1); + assertThat(capturedInvocationList.stream().limit(numberOfResultPagesFromParentBeforeSplit + 1).filter(i -> i.sourcePartition.id().equals(parentPartitionId))).hasSize(numberOfResultPagesFromParentBeforeSplit + 1); - assertThat(capturedInvocationList.stream().skip(numberOfResultPagesFromParentBeforeSplit + 1) - .filter(i -> i.sourcePartition.id().equals(leftChildPartitionId))) - .hasSize(numberOfResultPagesFromLeftChildAfterSplit); + assertThat(capturedInvocationList.stream().skip(numberOfResultPagesFromParentBeforeSplit + 1).filter(i -> i.sourcePartition.id().equals(leftChildPartitionId))).hasSize(numberOfResultPagesFromLeftChildAfterSplit); - assertThat(capturedInvocationList.stream().skip(numberOfResultPagesFromParentBeforeSplit + 1) - .filter(i -> i.sourcePartition.id().equals(rightChildPartitionId))) - .hasSize(numberOfResultPagesFromRightChildAfterSplit); + assertThat(capturedInvocationList.stream().skip(numberOfResultPagesFromParentBeforeSplit + 1).filter(i -> i.sourcePartition.id().equals(rightChildPartitionId))).hasSize(numberOfResultPagesFromRightChildAfterSplit); - - BiFunction, String, Stream> - filterByPartition = (stream, partitionId) - -> stream.filter(i -> i.sourcePartition.id().equals(partitionId)); + BiFunction, String, Stream> filterByPartition = (stream, partitionId) -> stream.filter(i -> i.sourcePartition.id().equals(partitionId)); Function>, Stream> extractContinuationToken = (list) -> list.stream().map(p -> p.continuationToken()); - assertThat(filterByPartition.apply(capturedInvocationList.stream(), parentPartitionId) - .map(r -> r.continuationToken)).containsExactlyElementsOf( - toList(Stream.concat( - Stream.of(initialContinuationToken), - extractContinuationToken.apply(expectedResultPagesFromParentPartitionBeforeSplit)))); + assertThat(filterByPartition.apply(capturedInvocationList.stream(), parentPartitionId).map(r -> r.continuationToken)).containsExactlyElementsOf(toList(Stream.concat(Stream.of(initialContinuationToken), extractContinuationToken.apply(expectedResultPagesFromParentPartitionBeforeSplit)))); String expectedInitialChildContinuationTokenInheritedFromParent = expectedResultPagesFromParentPartitionBeforeSplit.size() > 0 ? - expectedResultPagesFromParentPartitionBeforeSplit.get( - expectedResultPagesFromParentPartitionBeforeSplit.size() - 1) - .continuationToken() :initialContinuationToken; - - assertThat( - filterByPartition.andThen(s -> s.map(r -> r.continuationToken)) - .apply(capturedInvocationList.stream(), leftChildPartitionId) - ).containsExactlyElementsOf( - toList( - Stream.concat( - Stream.of(expectedInitialChildContinuationTokenInheritedFromParent), - extractContinuationToken.apply(expectedResultPagesFromLeftChildPartition) - //drop last page with null cp which doesn't trigger any request - .limit(expectedResultPagesFromLeftChildPartition.size() - 1) - ) - )); - - assertThat( - filterByPartition.andThen(s -> s.map(r -> r.continuationToken)) - .apply(capturedInvocationList.stream(), rightChildPartitionId) - ).containsExactlyElementsOf( - toList( - Stream.concat( - Stream.of(expectedInitialChildContinuationTokenInheritedFromParent), - extractContinuationToken.apply(expectedResultPagesFromRightChildPartition) - //drop last page with null cp which doesn't trigger any request - .limit(expectedResultPagesFromRightChildPartition.size() - 1) - ) - )); + expectedResultPagesFromParentPartitionBeforeSplit.get(expectedResultPagesFromParentPartitionBeforeSplit.size() - 1).continuationToken() : initialContinuationToken; + + assertThat(filterByPartition.andThen(s -> s.map(r -> r.continuationToken)).apply(capturedInvocationList.stream(), leftChildPartitionId)).containsExactlyElementsOf(toList(Stream.concat(Stream.of(expectedInitialChildContinuationTokenInheritedFromParent), extractContinuationToken.apply(expectedResultPagesFromLeftChildPartition) + //drop last page with null cp which doesn't trigger any request + .limit(expectedResultPagesFromLeftChildPartition.size() - 1)))); + + assertThat(filterByPartition.andThen(s -> s.map(r -> r.continuationToken)).apply(capturedInvocationList.stream(), rightChildPartitionId)).containsExactlyElementsOf(toList(Stream.concat(Stream.of(expectedInitialChildContinuationTokenInheritedFromParent), extractContinuationToken.apply(expectedResultPagesFromRightChildPartition) + //drop last page with null cp which doesn't trigger any request + .limit(expectedResultPagesFromRightChildPartition.size() - 1)))); } - private static void sanityCheckSplitValidation(String parentPartitionId, - String leftChildPartitionId, - String rightChildPartitionId, - int numberOfResultPagesFromParentBeforeSplit, - int numberOfResultPagesFromLeftChildAfterSplit, - int numberOfResultPagesFromRightChildAfterSplit, - List> resultFromParent, - List> resultFromLeftChild, - List> resultFromRightChild) { + private static void sanityCheckSplitValidation(String parentPartitionId, String leftChildPartitionId, + String rightChildPartitionId, int numberOfResultPagesFromParentBeforeSplit, + int numberOfResultPagesFromLeftChildAfterSplit, int numberOfResultPagesFromRightChildAfterSplit, + List> resultFromParent, List> resultFromLeftChild, + List> resultFromRightChild) { // test sanity check assertThat(resultFromParent).hasSize(numberOfResultPagesFromParentBeforeSplit); assertThat(resultFromLeftChild).hasSize(numberOfResultPagesFromLeftChildAfterSplit); assertThat(resultFromRightChild).hasSize(numberOfResultPagesFromRightChildAfterSplit); //validate expected result continuation token - assertThat(toList(resultFromParent.stream().map(p -> p.continuationToken()) - .filter(cp -> Strings.isNullOrEmpty(cp)))).isEmpty(); + assertThat(toList(resultFromParent.stream().map(p -> p.continuationToken()).filter(cp -> Strings.isNullOrEmpty(cp)))).isEmpty(); - assertThat(toList(resultFromLeftChild.stream().map(p -> p.continuationToken()) - .limit(resultFromLeftChild.size() - 1) - .filter(cp -> Strings.isNullOrEmpty(cp)))).isEmpty(); + assertThat(toList(resultFromLeftChild.stream().map(p -> p.continuationToken()).limit(resultFromLeftChild.size() - 1).filter(cp -> Strings.isNullOrEmpty(cp)))).isEmpty(); assertThat(resultFromLeftChild.get(resultFromLeftChild.size() - 1).continuationToken()).isNullOrEmpty(); - assertThat(toList(resultFromRightChild.stream().map(p -> p.continuationToken()) - .limit(resultFromRightChild.size() - 1) - .filter(cp -> Strings.isNullOrEmpty(cp)))).isEmpty(); + assertThat(toList(resultFromRightChild.stream().map(p -> p.continuationToken()).limit(resultFromRightChild.size() - 1).filter(cp -> Strings.isNullOrEmpty(cp)))).isEmpty(); assertThat(resultFromRightChild.get(resultFromRightChild.size() - 1).continuationToken()).isNullOrEmpty(); } private void validateSplitResults(List.DocumentProducerFeedResponse> actualPages, - String parentPartitionId, - String leftChildPartitionId, - String rightChildPartitionId, - List> resultFromParent, - List> resultFromLeftChild, - List> resultFromRightChild, - boolean isOrderby) { + String parentPartitionId, String leftChildPartitionId, String rightChildPartitionId, + List> resultFromParent, List> resultFromLeftChild, + List> resultFromRightChild, boolean isOrderby) { if (isOrderby) { Supplier> getStreamOfActualDocuments = @@ -754,46 +632,40 @@ public int compare(Document o1, Document o2) { ObjectNode obj1 = (ObjectNode) o1.get(OrderByPayloadFieldName); ObjectNode obj2 = (ObjectNode) o1.get(OrderByPayloadFieldName); - int cmp = (obj1).get(OrderByIntFieldName).asInt() - - (obj2).get(OrderByIntFieldName).asInt(); + int cmp = (obj1).get(OrderByIntFieldName).asInt() - (obj2).get(OrderByIntFieldName).asInt(); if (cmp != 0) { return cmp; } - return obj1.get(DocumentPartitionKeyRangeMinInclusiveFieldName).asText() - .compareTo(obj2.get(DocumentPartitionKeyRangeMinInclusiveFieldName).asText()); + return obj1.get(DocumentPartitionKeyRangeMinInclusiveFieldName).asText().compareTo(obj2.get(DocumentPartitionKeyRangeMinInclusiveFieldName).asText()); } }; List expectedDocuments = Stream.concat(Stream.concat(resultFromParent.stream(), - resultFromLeftChild.stream()), resultFromRightChild.stream()) - .flatMap(p -> p.results().stream()) - .sorted(comparator) - .collect(Collectors.toList()); + resultFromLeftChild.stream()), + resultFromRightChild.stream()).flatMap(p -> p.results().stream()).sorted(comparator).collect(Collectors.toList()); - List actualDocuments = getStreamOfActualDocuments.get().map(d -> d.id()).collect(Collectors.toList()); - assertThat(actualDocuments) - .containsExactlyElementsOf(expectedDocuments.stream().map(d -> d.id()).collect(Collectors.toList())); + List actualDocuments = + getStreamOfActualDocuments.get().map(d -> d.id()).collect(Collectors.toList()); + assertThat(actualDocuments).containsExactlyElementsOf(expectedDocuments.stream().map(d -> d.id()).collect(Collectors.toList())); } else { - assertThat(actualPages).hasSize(resultFromParent.size() - + resultFromLeftChild.size() - + resultFromRightChild.size()); + assertThat(actualPages).hasSize(resultFromParent.size() + resultFromLeftChild.size() + resultFromRightChild.size()); BiFunction> repeater = (v, cnt) -> { return IntStream.range(0, cnt).mapToObj(i -> v); }; - List expectedCapturedPartitionIds = toList(Stream.concat(Stream.concat(repeater.apply(parentPartitionId, resultFromParent.size()), - repeater.apply(leftChildPartitionId, resultFromLeftChild.size())), - repeater.apply(rightChildPartitionId, resultFromRightChild.size()))); - + List expectedCapturedPartitionIds = + toList(Stream.concat(Stream.concat(repeater.apply(parentPartitionId, resultFromParent.size()), + repeater.apply(leftChildPartitionId, + resultFromLeftChild.size())), + repeater.apply(rightChildPartitionId, resultFromRightChild.size()))); + assertThat(toList(partitionKeyRangeIds(actualPages).stream())).containsExactlyInAnyOrderElementsOf(expectedCapturedPartitionIds); - assertThat(toList(partitionKeyRangeIds(actualPages).stream())).containsExactlyInAnyOrderElementsOf( - expectedCapturedPartitionIds); - - validateResults(feedResponses(actualPages), ImmutableList.of(resultFromParent, resultFromLeftChild, resultFromRightChild)); + validateResults(feedResponses(actualPages), ImmutableList.of(resultFromParent, resultFromLeftChild, + resultFromRightChild)); } } @@ -805,7 +677,7 @@ private static List> feedResponses(List dpFR.pageResult).collect(Collectors.toList()); } - private static List toList(Stream stream) { + private static List toList(Stream stream) { return stream.collect(Collectors.toList()); } @@ -813,11 +685,12 @@ private static List partitionKeyRangeIds(List return responses.stream().map(dpFR -> dpFR.sourcePartitionKeyRange.id()).collect(Collectors.toList()); } - private static void validateResults(List> captured, List>> expectedResponsesFromPartitions) { - List> expected = expectedResponsesFromPartitions - .stream().flatMap(l -> l.stream()).collect(Collectors.toList()); + private static void validateResults(List> captured, + List>> expectedResponsesFromPartitions) { + List> expected = + expectedResponsesFromPartitions.stream().flatMap(l -> l.stream()).collect(Collectors.toList()); assertThat(captured).hasSameSizeAs(expected); - for(int i = 0; i < expected.size(); i++) { + for (int i = 0; i < expected.size(); i++) { FeedResponse actualPage = captured.get(i); FeedResponse expectedPage = expected.get(i); assertEqual(actualPage, expectedPage); @@ -828,7 +701,7 @@ private static void assertEqual(FeedResponse actualPage, FeedResponse< assertThat(actualPage.results()).hasSameSizeAs(actualPage.results()); assertThat(actualPage.continuationToken()).isEqualTo(expectedPage.continuationToken()); - for(int i = 0; i < actualPage.results().size(); i++) { + for (int i = 0; i < actualPage.results().size(); i++) { Document actualDoc = actualPage.results().get(i); Document expectedDoc = expectedPage.results().get(i); assertThat(actualDoc.id()).isEqualTo(expectedDoc.id()); @@ -836,10 +709,11 @@ private static void assertEqual(FeedResponse actualPage, FeedResponse< } } - static abstract class RequestExecutor implements Func1>> { + static abstract class RequestExecutor implements Function>> { LinkedListMultimap partitionKeyRangeIdToCapturedInvocation = LinkedListMultimap.create(); + class CapturedInvocation { long time = System.nanoTime(); RxDocumentServiceRequest request; @@ -853,7 +727,7 @@ public CapturedInvocation(RxDocumentServiceRequest request, Exception ex) { public CapturedInvocation(RxDocumentServiceRequest request, PartitionAnswer.Response resp) { this.request = request; - this.invocationResult = resp.invocationResult; + this.invocationResult = resp.invocationResult; this.failureResult = resp.failureResult; } } @@ -861,7 +735,7 @@ public CapturedInvocation(RxDocumentServiceRequest request, PartitionAnswer.Resp private static CosmosClientException partitionKeyRangeGoneException() { Map headers = new HashMap<>(); headers.put(HttpConstants.HttpHeaders.SUB_STATUS, - Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)); + Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)); return new CosmosClientException(HttpConstants.StatusCodes.GONE, new Error(), headers); } @@ -872,23 +746,22 @@ protected void capture(String partitionId, CapturedInvocation captureInvocation) public static RequestExecutor fromPartitionAnswer(List answers) { return new RequestExecutor() { @Override - public Observable> call(RxDocumentServiceRequest request) { + public Flux> apply(RxDocumentServiceRequest request) { synchronized (this) { logger.debug("executing request: " + request + " cp is: " + request.getContinuation()); for (PartitionAnswer a : answers) { - if (a.getPartitionKeyRangeId().equals( - request.getPartitionKeyRangeIdentity().getPartitionKeyRangeId())) { + if (a.getPartitionKeyRangeId().equals(request.getPartitionKeyRangeIdentity().getPartitionKeyRangeId())) { try { PartitionAnswer.Response resp = a.onRequest(request); if (resp != null) { CapturedInvocation ci = new CapturedInvocation(request, resp); capture(a.getPartitionKeyRangeId(), ci); - return resp.toSingle().toObservable(); + return resp.toSingle(); } } catch (Exception e) { capture(a.getPartitionKeyRangeId(), new CapturedInvocation(request, e)); - return Observable.error(e); + return Flux.error(e); } } } @@ -915,11 +788,11 @@ public Response(Exception ex) { this.failureResult = ex; } - public Single> toSingle() { + public Flux> toSingle() { if (invocationResult != null) { - return Single.just(invocationResult); + return Flux.just(invocationResult); } else { - return Single.error(failureResult); + return Flux.error(failureResult); } } } @@ -1003,15 +876,15 @@ public Response onRequest(RxDocumentServiceRequest request) { } } - static abstract class RequestCreator implements - Func3 { + static abstract class RequestCreator implements TriFunction { public static RequestCreator give(List requests) { AtomicInteger i = new AtomicInteger(0); return new RequestCreator() { @Override - public RxDocumentServiceRequest call(PartitionKeyRange pkr, String cp, Integer ps) { + public RxDocumentServiceRequest apply(PartitionKeyRange pkr, String cp, Integer ps) { synchronized (this) { RxDocumentServiceRequest req = requests.get(i.getAndIncrement()); invocations.add(new CapturedInvocation(pkr, cp, ps, req)); @@ -1024,7 +897,7 @@ public RxDocumentServiceRequest call(PartitionKeyRange pkr, String cp, Integer p public static RequestCreator simpleMock() { return new RequestCreator() { @Override - public RxDocumentServiceRequest call(PartitionKeyRange pkr, String cp, Integer ps) { + public RxDocumentServiceRequest apply(PartitionKeyRange pkr, String cp, Integer ps) { synchronized (this) { RxDocumentServiceRequest req = Mockito.mock(RxDocumentServiceRequest.class); PartitionKeyRangeIdentity pkri = new PartitionKeyRangeIdentity(pkr.id()); @@ -1044,10 +917,8 @@ class CapturedInvocation { Integer maxItemCount; RxDocumentServiceRequest invocationResult; - public CapturedInvocation(PartitionKeyRange sourcePartition, - String continuationToken, - Integer maxItemCount, - RxDocumentServiceRequest invocationResult) { + public CapturedInvocation(PartitionKeyRange sourcePartition, String continuationToken, + Integer maxItemCount, RxDocumentServiceRequest invocationResult) { this.sourcePartition = sourcePartition; this.continuationToken = continuationToken; this.maxItemCount = maxItemCount; @@ -1057,18 +928,14 @@ public CapturedInvocation(PartitionKeyRange sourcePartition, List invocations = Collections.synchronizedList(new ArrayList<>()); - abstract public RxDocumentServiceRequest call(PartitionKeyRange pkr, String cp, Integer ps); +// abstract public RxDocumentServiceRequest call(PartitionKeyRange pkr, String cp, Integer ps); } private Document getDocumentDefinition() { String uuid = UUID.randomUUID().toString(); - Document doc = new Document(String.format("{ " - + "\"id\": \"%s\", " - + "\"mypk\": \"%s\", " - + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]], " - + "\"prop\": \"%s\"" - + "}" - , uuid, uuid, uuid)); + Document doc = new Document(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": " + + "[[6519456, 1471916863], [2498434, 1455671440]], " + + "\"prop\": \"%s\"" + "}", uuid, uuid, uuid)); return doc; } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java index e074fb4cc55d1..26e2899ca24f6 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java @@ -29,16 +29,16 @@ import com.azure.data.cosmos.FeedOptionsBase; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import io.reactivex.subscribers.TestSubscriber; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import rx.Observable; -import rx.functions.Func1; -import rx.functions.Func2; -import rx.observers.TestSubscriber; +import reactor.core.publisher.Flux; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiFunction; +import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -94,7 +94,7 @@ public void query(FeedOptions options, int top) { AtomicInteger requestIndex = new AtomicInteger(0); - Func2 createRequestFunc = (token, maxItemCount) -> { + BiFunction createRequestFunc = (token, maxItemCount) -> { assertThat(maxItemCount).describedAs("max item count").isEqualTo( getExpectedMaxItemCountInRequest(options, top, feedResponseList, requestIndex.get())); assertThat(token).describedAs("continuation token").isEqualTo( @@ -106,10 +106,10 @@ public void query(FeedOptions options, int top) { AtomicInteger executeIndex = new AtomicInteger(0); - Func1>> executeFunc = request -> { + Function>> executeFunc = request -> { FeedResponse rsp = feedResponseList.get(executeIndex.getAndIncrement()); totalResultsReceived.addAndGet(rsp.results().size()); - return Observable.just(rsp); + return Flux.just(rsp); }; Fetcher fetcher = @@ -162,7 +162,7 @@ public void changeFeed() { AtomicInteger requestIndex = new AtomicInteger(0); - Func2 createRequestFunc = (token, maxItemCount) -> { + BiFunction createRequestFunc = (token, maxItemCount) -> { assertThat(maxItemCount).describedAs("max item count").isEqualTo(options.maxItemCount()); assertThat(token).describedAs("continuation token").isEqualTo( getExpectedContinuationTokenInRequest(options, feedResponseList, requestIndex.getAndIncrement())); @@ -172,8 +172,8 @@ public void changeFeed() { AtomicInteger executeIndex = new AtomicInteger(0); - Func1>> executeFunc = request -> { - return Observable.just(feedResponseList.get(executeIndex.getAndIncrement())); + Function>> executeFunc = request -> { + return Flux.just(feedResponseList.get(executeIndex.getAndIncrement())); }; Fetcher fetcher = @@ -196,14 +196,14 @@ private void validateFetcher(Fetcher fetcher, assertThat(fetcher.shouldFetchMore()).describedAs("should not fetch more pages").isFalse(); } - private FeedResponse validate(Observable> page) { - TestSubscriber> subscriber = new TestSubscriber(); + private FeedResponse validate(Flux> page) { + TestSubscriber> subscriber = new TestSubscriber<>(); page.subscribe(subscriber); subscriber.awaitTerminalEvent(); - subscriber.assertCompleted(); + subscriber.assertComplete(); subscriber.assertNoErrors(); subscriber.assertValueCount(1); - return subscriber.getOnNextEvents().get(0); + return subscriber.values().get(0); } private String getExpectedContinuationTokenInRequest(FeedOptionsBase options, diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java index c28ab466d11ed..21d529771076f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java @@ -83,14 +83,6 @@ public AggregateQueryTests(CosmosClientBuilder clientBuilder) { super(clientBuilder); } - - // TODO: DANOBLE: Investigate DIRECT TCP performance issue - // Links: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 - // Notes: - // I've seen this test time out in my development environment. I test against a debug instance of the public - // emulator and so what I'm seeing could be the result of a public emulator performance issue. Of course, it - // might also be the result of a TCP protocol performance problem. - @Test(groups = { "simple" }, timeOut = 2 * TIMEOUT, dataProvider = "queryMetricsArgProvider") public void queryDocumentsWithAggregates(boolean qmEnabled) throws Exception { @@ -99,7 +91,7 @@ public void queryDocumentsWithAggregates(boolean qmEnabled) throws Exception { options.populateQueryMetrics(qmEnabled); options.maxDegreeOfParallelism(2); - for (QueryConfig queryConfig : queryConfigs) { + for (QueryConfig queryConfig : queryConfigs) { Flux> queryObservable = createdCollection.queryItems(queryConfig.query, options); @@ -115,7 +107,7 @@ public void queryDocumentsWithAggregates(boolean qmEnabled) throws Exception { public void bulkInsert() { generateTestData(); - bulkInsertBlocking(createdCollection, docs); + voidBulkInsertBlocking(createdCollection, docs); } public void generateTestData() { @@ -206,7 +198,7 @@ public void afterClass() { safeClose(client); } - @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT * 100) + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT * 2) public void beforeClass() throws Exception { client = this.clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java index f0b01803cd9e0..8ae7dfb3d54d3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java @@ -50,7 +50,6 @@ import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; import reactor.util.concurrent.Queues; -import rx.Observable; import java.util.ArrayList; import java.util.Collection; @@ -149,7 +148,7 @@ public void query(String query, int maxItemCount, int maxExpectedBufferedCountFo log.info("instantiating subscriber ..."); TestSubscriber> subscriber = new TestSubscriber<>(1); - queryObservable.publishOn(Schedulers.elastic()).subscribe(subscriber); + queryObservable.publishOn(Schedulers.elastic(), 1).subscribe(subscriber); int sleepTimeInMillis = 40000; int i = 0; @@ -200,7 +199,7 @@ public void beforeClass() { docDefList); numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client).readPartitionKeyRanges(getCollectionLink(), null) - .flatMap(p -> Observable.from(p.results())).toList().toBlocking().single().size(); + .flatMap(p -> Flux.fromIterable(p.results())).collectList().single().block().size(); waitIfNeededForReplicasToCatchUp(clientBuilder()); warmUp(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java index 3c80a8d39a8de..2af6909ed5ede 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java @@ -82,7 +82,7 @@ public BackPressureTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } - @Test(groups = { "long" }, timeOut = TIMEOUT) + @Test(groups = { "long" }, timeOut = 3 * TIMEOUT) public void readFeed() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(1); @@ -93,7 +93,7 @@ public void readFeed() throws Exception { rxClient.httpRequests.clear(); TestSubscriber> subscriber = new TestSubscriber>(1); - queryObservable.publishOn(Schedulers.elastic()).subscribe(subscriber); + queryObservable.publishOn(Schedulers.elastic(), 1).subscribe(subscriber); int sleepTimeInMillis = 10000; // 10 seconds int i = 0; @@ -109,7 +109,7 @@ public void readFeed() throws Exception { // validate that only one item is returned to subscriber in each iteration // validate that the difference between the number of requests to backend // and the number of returned results is always less than a fixed threshold - assertThat(rxClient.httpRequests.size() - subscriber.getEvents().get(0).size()) + assertThat(rxClient.httpRequests.size() - subscriber.valueCount()) .isLessThanOrEqualTo(Queues.SMALL_BUFFER_SIZE); subscriber.requestMore(1); @@ -118,10 +118,10 @@ public void readFeed() throws Exception { subscriber.assertNoErrors(); subscriber.assertComplete(); - assertThat(subscriber.getEvents().get(0)).hasSize(createdDocuments.size()); + assertThat(subscriber.valueCount()).isEqualTo(createdDocuments.size()); } - @Test(groups = { "long" }, timeOut = TIMEOUT) + @Test(groups = { "long" }, timeOut = 3 * TIMEOUT) public void query() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(1); @@ -132,7 +132,7 @@ public void query() throws Exception { rxClient.httpRequests.clear(); TestSubscriber> subscriber = new TestSubscriber>(1); - queryObservable.publishOn(Schedulers.elastic()).subscribe(subscriber); + queryObservable.publishOn(Schedulers.elastic(), 1).subscribe(subscriber); int sleepTimeInMillis = 10000; int i = 0; @@ -157,13 +157,9 @@ public void query() throws Exception { subscriber.assertNoErrors(); subscriber.assertComplete(); - assertThat(subscriber.getEvents().get(0)).hasSize(createdDocuments.size()); + assertThat(subscriber.valueCount()).isEqualTo(createdDocuments.size()); } - // TODO: DANOBLE: Investigate DIRECT TCP performance issue - // NOTE: This method requires multiple SHUTDOWN_TIMEOUT intervals - // SEE: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 - @BeforeClass(groups = { "long" }, timeOut = 2 * SETUP_TIMEOUT) public void beforeClass() throws Exception { @@ -181,9 +177,9 @@ public void beforeClass() throws Exception { Offer offer = rxClient.queryOffers( String.format("SELECT * FROM r WHERE r.offerResourceId = '%s'", createdCollection.read().block().settings().resourceId()) - , null).first().map(FeedResponse::results).toBlocking().single().get(0); + , null).take(1).map(FeedResponse::results).single().block().get(0); offer.setThroughput(6000); - offer = rxClient.replaceOffer(offer).toBlocking().single().getResource(); + offer = rxClient.replaceOffer(offer).single().block().getResource(); assertThat(offer.getThroughput()).isEqualTo(6000); ArrayList docDefList = new ArrayList<>(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java index a8ed82c9b2d58..4921e5fca1260 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java @@ -32,6 +32,7 @@ import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.internal.TestSuiteBase; import com.google.common.collect.ArrayListMultimap; @@ -42,7 +43,7 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.lang.reflect.Method; import java.time.OffsetDateTime; @@ -53,7 +54,7 @@ import static org.assertj.core.api.Assertions.assertThat; -//TODO: change to use external TestSuiteBase +//TODO: change to use external TestSuiteBase public class ChangeFeedTest extends TestSuiteBase { private static final int SETUP_TIMEOUT = 40000; @@ -98,7 +99,7 @@ public void changeFeed_fromBeginning() throws Exception { changeFeedOption.startFromBeginning(true); List> changeFeedResultList = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) - .toList().toBlocking().single(); + .collectList().block(); int count = 0; for (int i = 0; i < changeFeedResultList.size(); i++) { @@ -113,14 +114,13 @@ public void changeFeed_fromBeginning() throws Exception { assertThat(count).as("the number of changes").isEqualTo(expectedDocuments.size()); } - @Test(groups = { "simple" }, timeOut = TIMEOUT) + @Test(groups = { "simple" }, timeOut = 5 * TIMEOUT) public void changesFromPartitionKeyRangeId_FromBeginning() throws Exception { List partitionKeyRangeIds = client.readPartitionKeyRanges(getCollectionLink(), null) - .flatMap(p -> Observable.from(p.results()), 1) - .map(pkr -> pkr.id()) - .toList() - .toBlocking() - .single(); + .flatMap(p -> Flux.fromIterable(p.results()), 1) + .map(Resource::id) + .collectList() + .block(); assertThat(partitionKeyRangeIds.size()).isGreaterThan(1); @@ -131,7 +131,7 @@ public void changesFromPartitionKeyRangeId_FromBeginning() throws Exception { changeFeedOption.partitionKeyRangeId(pkRangeId); changeFeedOption.startFromBeginning(true); List> changeFeedResultList = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) - .toList().toBlocking().single(); + .collectList().block(); int count = 0; for(int i = 0; i < changeFeedResultList.size(); i++) { @@ -159,10 +159,10 @@ public void changeFeed_fromNow() throws Exception { changeFeedOption.partitionKey(new PartitionKey(partitionKey)); List> changeFeedResultsList = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) - .toList() - .toBlocking().single(); + .collectList() + .block(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder().totalSize(0).build(); + FeedResponseListValidator validator = new FeedResponseListValidator.Builder().totalSize(0).build(); validator.validate(changeFeedResultsList); assertThat(changeFeedResultsList.get(changeFeedResultsList.size() -1 ). continuationToken()).as("Response continuation should not be null").isNotNull(); @@ -172,7 +172,7 @@ public void changeFeed_fromNow() throws Exception { public void changeFeed_fromStartDate() throws Exception { //setStartDateTime is not currently supported in multimaster mode. So skipping the test - if(BridgeInternal.isEnableMultipleWriteLocations(client.getDatabaseAccount().toBlocking().single())){ + if(BridgeInternal.isEnableMultipleWriteLocations(client.getDatabaseAccount().single().block())){ throw new SkipException("StartTime/IfModifiedSince is not currently supported when EnableMultipleWriteLocations is set"); } @@ -190,11 +190,10 @@ public void changeFeed_fromStartDate() throws Exception { // Waiting for at-least a second to ensure that new document is created after we took the time stamp waitAtleastASecond(dateTimeBeforeCreatingDoc); - client.createDocument(getCollectionLink(), getDocumentDefinition(partitionKey), null, true).toBlocking().single().getResource(); + client.createDocument(getCollectionLink(), getDocumentDefinition(partitionKey), null, true).single().block(); List> changeFeedResultList = client.queryDocumentChangeFeed(getCollectionLink(), - changeFeedOption).toList() - .toBlocking().single(); + changeFeedOption).collectList().block(); int count = 0; for(int i = 0; i < changeFeedResultList.size(); i++) { @@ -213,7 +212,7 @@ public void changesFromPartitionKey_AfterInsertingNewDocuments() throws Exceptio changeFeedOption.partitionKey(new PartitionKey(partitionKey)); List> changeFeedResultsList = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) - .toList().toBlocking().single(); + .collectList().block(); assertThat(changeFeedResultsList).as("only one page").hasSize(1); assertThat(changeFeedResultsList.get(0).results()).as("no recent changes").isEmpty(); @@ -223,15 +222,15 @@ public void changesFromPartitionKey_AfterInsertingNewDocuments() throws Exceptio assertThat(changeFeedContinuation).as("continuation token is not empty").isNotEmpty(); // create some documents - client.createDocument(getCollectionLink(), getDocumentDefinition(partitionKey), null, true).toBlocking().single(); - client.createDocument(getCollectionLink(), getDocumentDefinition(partitionKey), null, true).toBlocking().single(); + client.createDocument(getCollectionLink(), getDocumentDefinition(partitionKey), null, true).single().block(); + client.createDocument(getCollectionLink(), getDocumentDefinition(partitionKey), null, true).single().block(); // READ change feed from continuation changeFeedOption.requestContinuation(changeFeedContinuation); FeedResponse changeFeedResults2 = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) - .toBlocking().first(); + .blockFirst(); assertThat(changeFeedResults2.results()).as("change feed should contain newly inserted docs.").hasSize(2); assertThat(changeFeedResults2.continuationToken()).as("Response continuation should not be null").isNotNull(); @@ -241,17 +240,17 @@ public void createDocument(AsyncDocumentClient client, String partitionKey) { Document docDefinition = getDocumentDefinition(partitionKey); Document createdDocument = client - .createDocument(getCollectionLink(), docDefinition, null, false).toBlocking().single().getResource(); + .createDocument(getCollectionLink(), docDefinition, null, false).single().block().getResource(); partitionKeyToDocuments.put(partitionKey, createdDocument); } public List bulkInsert(AsyncDocumentClient client, List docs) { - ArrayList>> result = new ArrayList>>(); + ArrayList>> result = new ArrayList>>(); for (int i = 0; i < docs.size(); i++) { result.add(client.createDocument("dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(), docs.get(i), null, false)); } - return Observable.merge(result, 100).map(r -> r.getResource()).toList().toBlocking().single(); + return Flux.merge(Flux.fromIterable(result), 100).map(ResourceResponse::getResource).collectList().block(); } @AfterMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java index 2f42a575e7038..4c4e502b7bc2c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java @@ -29,7 +29,6 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.rx.TestSuiteBase; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; @@ -78,8 +77,8 @@ public void readConflicts_toBlocking_toIterator() { } assertThat(numberOfResults).isEqualTo(expectedNumberOfConflicts); } - - + + @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder().build(); @@ -96,4 +95,4 @@ public void beforeMethod() { safeClose(client); client = clientBuilder().build(); } -} +} \ No newline at end of file diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java index 957413c4c660e..5ff9d51ee28cc 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java @@ -51,7 +51,7 @@ public DocumentClientResourceLeakTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } - @Test(groups = {"emulator"}, timeOut = TIMEOUT) + @Test(enabled = false, groups = {"emulator"}, timeOut = TIMEOUT) public void resourceLeak() throws Exception { System.gc(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java index e007f30f66da5..11c3a09b738e0 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java @@ -35,7 +35,6 @@ import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; @@ -51,10 +50,9 @@ public class DocumentCrudTest extends TestSuiteBase { - private CosmosContainer createdCollection; - private CosmosClient client; - + private CosmosContainer container; + @Factory(dataProvider = "clientBuildersWithDirect") public DocumentCrudTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); @@ -63,23 +61,22 @@ public DocumentCrudTest(CosmosClientBuilder clientBuilder) { @DataProvider(name = "documentCrudArgProvider") public Object[][] documentCrudArgProvider() { return new Object[][] { - // collection name, is name base - {UUID.randomUUID().toString()} , - - // with special characters in the name. - {"+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~"} , + // collection name, is name base + { UUID.randomUUID().toString() }, + // with special characters in the name. + { "+ -_,:.|~" + UUID.randomUUID().toString() + " +-_,:.|~" }, }; } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") public void createDocument(String documentId) throws InterruptedException { - CosmosItemProperties docDefinition = getDocumentDefinition(documentId); - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + CosmosItemProperties properties = getDocumentDefinition(documentId); + Mono createObservable = container.createItem(properties, new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.id()) - .build(); + .withId(properties.id()) + .build(); validateSuccess(createObservable, validator); } @@ -92,7 +89,7 @@ public void createLargeDocument(String documentId) throws InterruptedException { int size = (int) (ONE_MB * 1.5); docDefinition.set("largeString", StringUtils.repeat("x", size)); - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + Mono createObservable = container.createItem(docDefinition, new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.id()) @@ -110,7 +107,7 @@ public void createDocumentWithVeryLargePartitionKey(String documentId) throws In } docDefinition.set("mypk", sb.toString()); - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); + Mono createObservable = container.createItem(docDefinition, new CosmosItemRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(docDefinition.id()) @@ -128,7 +125,7 @@ public void readDocumentWithVeryLargePartitionKey(String documentId) throws Inte } docDefinition.set("mypk", sb.toString()); - CosmosItem createdDocument = TestSuiteBase.createDocument(createdCollection, docDefinition); + CosmosItem createdDocument = TestSuiteBase.createDocument(container, docDefinition); waitIfNeededForReplicasToCatchUp(clientBuilder()); @@ -146,11 +143,8 @@ public void readDocumentWithVeryLargePartitionKey(String documentId) throws Inte @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") public void createDocument_AlreadyExists(String documentId) throws InterruptedException { CosmosItemProperties docDefinition = getDocumentDefinition(documentId); - - createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block(); - - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); - + container.createItem(docDefinition, new CosmosItemRequestOptions()).block(); + Mono createObservable = container.createItem(docDefinition, new CosmosItemRequestOptions()); FailureValidator validator = new FailureValidator.Builder().resourceAlreadyExists().build(); validateFailure(createObservable, validator); } @@ -158,20 +152,17 @@ public void createDocument_AlreadyExists(String documentId) throws InterruptedEx @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") public void createDocumentTimeout(String documentId) throws InterruptedException { CosmosItemProperties docDefinition = getDocumentDefinition(documentId); - - Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()) - .timeout(Duration.ofMillis(1)); - + Mono createObservable = container.createItem(docDefinition, new CosmosItemRequestOptions()).timeout(Duration.ofMillis(1)); FailureValidator validator = new FailureValidator.Builder().instanceOf(TimeoutException.class).build(); - validateFailure(createObservable, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") public void readDocument(String documentId) throws InterruptedException { + CosmosItemProperties docDefinition = getDocumentDefinition(documentId); + CosmosItem document = container.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); waitIfNeededForReplicasToCatchUp(clientBuilder()); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); @@ -181,6 +172,7 @@ public void readDocument(String documentId) throws InterruptedException { CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(document.id()) .build(); + validateSuccess(readObservable, validator); } @@ -189,7 +181,7 @@ public void timestamp(String documentId) throws Exception { OffsetDateTime before = OffsetDateTime.now(); CosmosItemProperties docDefinition = getDocumentDefinition(documentId); Thread.sleep(1000); - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + CosmosItem document = container.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); waitIfNeededForReplicasToCatchUp(clientBuilder()); @@ -207,7 +199,7 @@ public void timestamp(String documentId) throws Exception { public void readDocument_DoesntExist(String documentId) throws InterruptedException { CosmosItemProperties docDefinition = getDocumentDefinition(documentId); - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + CosmosItem document = container.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); @@ -227,7 +219,7 @@ public void readDocument_DoesntExist(String documentId) throws InterruptedExcept public void deleteDocument(String documentId) throws InterruptedException { CosmosItemProperties docDefinition = getDocumentDefinition(documentId); - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + CosmosItem document = container.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); @@ -251,7 +243,7 @@ public void deleteDocument_undefinedPK(String documentId) throws InterruptedExce CosmosItemProperties docDefinition = new CosmosItemProperties(); docDefinition.id(documentId); - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + CosmosItem document = container.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.partitionKey(PartitionKey.None); @@ -273,7 +265,7 @@ public void deleteDocument_undefinedPK(String documentId) throws InterruptedExce public void deleteDocument_DoesntExist(String documentId) throws InterruptedException { CosmosItemProperties docDefinition = getDocumentDefinition(documentId); - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + CosmosItem document = container.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); @@ -291,7 +283,7 @@ public void replaceDocument(String documentId) throws InterruptedException { // create a document CosmosItemProperties docDefinition = getDocumentDefinition(documentId); - CosmosItem document = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); + CosmosItem document = container.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); String newPropValue = UUID.randomUUID().toString(); docDefinition.set("newProp", newPropValue); @@ -314,7 +306,7 @@ public void upsertDocument_CreateDocument(String documentId) throws Throwable { // replace document - Mono upsertObservable = createdCollection.upsertItem(docDefinition, new CosmosItemRequestOptions()); + Mono upsertObservable = container.upsertItem(docDefinition, new CosmosItemRequestOptions()); // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -323,51 +315,49 @@ public void upsertDocument_CreateDocument(String documentId) throws Throwable { validateSuccess(upsertObservable, validator); } - @Test(groups = { "simple" }, timeOut = TIMEOUT * 100, dataProvider = "documentCrudArgProvider") + @Test(groups = { "simple" }, timeOut = TIMEOUT, dataProvider = "documentCrudArgProvider") public void upsertDocument_ReplaceDocument(String documentId) throws Throwable { - // create a document - CosmosItemProperties docDefinition = getDocumentDefinition(documentId); - docDefinition = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()).block().properties(); + CosmosItemProperties properties = getDocumentDefinition(documentId); + properties = container.createItem(properties, new CosmosItemRequestOptions()).block().properties(); String newPropValue = UUID.randomUUID().toString(); - docDefinition.set("newProp", newPropValue); + properties.set("newProp", newPropValue); - // replace document - Mono readObservable = createdCollection.upsertItem(docDefinition, new CosmosItemRequestOptions()); - System.out.println(docDefinition); + // Replace document + + Mono readObservable = container.upsertItem(properties, new CosmosItemRequestOptions()); + System.out.println(properties); + + // Validate result - // validate CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withProperty("newProp", newPropValue).build(); + .withProperty("newProp", newPropValue).build(); + validateSuccess(readObservable, validator); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder().build(); - createdCollection = getSharedMultiPartitionCosmosContainer(client); + assertThat(this.client).isNull(); + this.client = this.clientBuilder().build(); + this.container = getSharedMultiPartitionCosmosContainer(this.client); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeClose(client); + assertThat(this.client).isNotNull(); + this.client.close(); } - @BeforeMethod(groups = { "simple" }, timeOut = SETUP_TIMEOUT) - public void beforeMethod() { - safeClose(client); - client = clientBuilder().build(); - } - private CosmosItemProperties getDocumentDefinition(String documentId) { - String uuid = UUID.randomUUID().toString(); - CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + final String uuid = UUID.randomUUID().toString(); + final CosmosItemProperties properties = new CosmosItemProperties(String.format("{ " + "\"id\": \"%s\", " + "\"mypk\": \"%s\", " + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + "}" , documentId, uuid)); - return doc; + return properties; } -} \ No newline at end of file +} diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java index 0828566f4841e..744e3c5d9b718 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java @@ -68,7 +68,6 @@ public class MultiOrderByQueryTests extends TestSuiteBase { private static final String PARTITION_KEY = "pk"; private ArrayList documents = new ArrayList(); private CosmosContainer documentCollection; - private CosmosClientBuilder clientBuilder; private CosmosClient client; class CustomComparator implements Comparator { @@ -180,9 +179,9 @@ public void beforeClass() throws Exception { } } - bulkInsertBlocking(documentCollection, documents); + voidBulkInsertBlocking(documentCollection, documents); - waitIfNeededForReplicasToCatchUp(clientBuilder); + waitIfNeededForReplicasToCatchUp(clientBuilder()); } private CosmosItemProperties generateMultiOrderByDocument() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java index f728a30a75ab4..280716fa34fae 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java @@ -37,7 +37,7 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; -//TODO: change to use external TestSuiteBase +//TODO: change to use external TestSuiteBase public class OfferQueryTest extends TestSuiteBase { public final static int SETUP_TIMEOUT = 40000; @@ -72,9 +72,9 @@ public void queryOffersWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Observable> queryObservable = client.queryOffers(query, null); + Flux> queryObservable = client.queryOffers(query, null); - List allOffers = client.readOffers(null).flatMap(f -> Observable.from(f.results())).toList().toBlocking().single(); + List allOffers = client.readOffers(null).flatMap(f -> Flux.fromIterable(f.results())).collectList().single().block(); List expectedOffers = allOffers.stream().filter(o -> collectionResourceId.equals(o.getString("offerResourceId"))).collect(Collectors.toList()); assertThat(expectedOffers).isNotEmpty(); @@ -101,9 +101,11 @@ public void queryOffersFilterMorePages() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(1); - Observable> queryObservable = client.queryOffers(query, options); + Flux> queryObservable = client.queryOffers(query, options); - List expectedOffers = client.readOffers(null).flatMap(f -> Observable.from(f.results())).toList().toBlocking().single() + List expectedOffers = client.readOffers(null).flatMap(f -> Flux.fromIterable(f.results())) + .collectList() + .single().block() .stream().filter(o -> collectionResourceIds.contains(o.getOfferResourceId())) .collect(Collectors.toList()); @@ -127,7 +129,7 @@ public void queryCollections_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - Observable> queryObservable = client.queryCollections(getDatabaseLink(), query, options); + Flux> queryObservable = client.queryCollections(getDatabaseLink(), query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java index 050bd7af6723e..22166d05c11bc 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java @@ -33,11 +33,11 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.List; -//TODO: change to use external TestSuiteBase +//TODO: change to use external TestSuiteBase public class OfferReadReplaceTest extends TestSuiteBase { public final String databaseId = DatabaseForTest.generateId(); @@ -55,7 +55,7 @@ public OfferReadReplaceTest(AsyncDocumentClient.Builder clientBuilder) { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void readAndReplaceOffer() { - client.readOffers(null).toBlocking().subscribe((offersFeed) -> { + client.readOffers(null).subscribe((offersFeed) -> { try { int i; List offers = offersFeed.results(); @@ -65,10 +65,10 @@ public void readAndReplaceOffer() { } } - Offer rOffer = client.readOffer(offers.get(i).selfLink()).toBlocking().single().getResource(); + Offer rOffer = client.readOffer(offers.get(i).selfLink()).single().block().getResource(); int oldThroughput = rOffer.getThroughput(); - Observable> readObservable = client.readOffer(offers.get(i).selfLink()); + Flux> readObservable = client.readOffer(offers.get(i).selfLink()); // validate offer read ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() @@ -81,7 +81,7 @@ public void readAndReplaceOffer() { // update offer int newThroughput = oldThroughput + 100; offers.get(i).setThroughput(newThroughput); - Observable> replaceObservable = client.replaceOffer(offers.get(i)); + Flux> replaceObservable = client.replaceOffer(offers.get(i)); // validate offer replace ResourceResponseValidator validatorForReplace = new ResourceResponseValidator.Builder() diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java index 2ba3c95a5459c..7b72e8ff0ed32 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java @@ -33,6 +33,7 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.RetryAnalyzer; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.CompositeContinuationToken; @@ -49,7 +50,6 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; import reactor.core.publisher.Flux; -import rx.Observable; import java.util.ArrayList; import java.util.Collections; @@ -248,9 +248,9 @@ public void queryOrderWithTop(int topValue) throws Exception { private List sortDocumentsAndCollectResourceIds(String propName, Function extractProp, Comparator comparer) { return createdDocuments.stream() - .filter(d -> d.getMap().containsKey(propName)) // removes undefined - .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) - .map(d -> d.resourceId()).collect(Collectors.toList()); + .filter(d -> d.getMap().containsKey(propName)) // removes undefined + .sorted((d1, d2) -> comparer.compare(extractProp.apply(d1), extractProp.apply(d2))) + .map(Resource::resourceId).collect(Collectors.toList()); } @Test(groups = { "simple" }, timeOut = TIMEOUT) @@ -456,7 +456,7 @@ public void beforeClass() throws Exception { numberOfPartitions = CosmosBridgeInternal.getAsyncDocumentClient(client) .readPartitionKeyRanges("dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id(), null) - .flatMap(p -> Observable.from(p.results())).toList().toBlocking().single().size(); + .flatMap(p -> Flux.fromIterable(p.results())).collectList().single().block().size(); waitIfNeededForReplicasToCatchUp(clientBuilder()); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java index ecc2da547cb94..782e22da2c7df 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java @@ -33,6 +33,7 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.CompositeContinuationToken; import com.azure.data.cosmos.internal.routing.Range; @@ -43,7 +44,6 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; import reactor.core.publisher.Flux; -import rx.Observable; import java.util.ArrayList; import java.util.List; @@ -154,9 +154,6 @@ public void queryDocuments_NoResults() { validateQuerySuccess(queryObservable, validator); } - // TODO: DANOBLE: Investigate DIRECT TCP performance issue - // See: https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 - @Test(groups = { "simple" }, timeOut = 2 * TIMEOUT) public void queryDocumentsWithPageSize() { String query = "SELECT * from root"; @@ -213,18 +210,14 @@ public void crossPartitionQueryNotEnabled() { validateQueryFailure(queryObservable, validator); } - // TODO: DANOBLE: Investigate DIRECT TCP performance issue - // Links: - // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 - @Test(groups = { "simple" }, timeOut = 2 * TIMEOUT) public void partitionKeyRangeId() { int sum = 0; for (String partitionKeyRangeId : CosmosBridgeInternal.getAsyncDocumentClient(client).readPartitionKeyRanges(getCollectionLink(), null) - .flatMap(p -> Observable.from(p.results())) - .map(pkr -> pkr.id()).toList().toBlocking().single()) { + .flatMap(p -> Flux.fromIterable(p.results())) + .map(Resource::id).collectList().single().block()) { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); options.partitionKeyRangeIdInternal(partitionKeyRangeId); @@ -279,22 +272,11 @@ public void queryDocumentsWithCompositeContinuationTokens() throws Exception { String query = "SELECT * FROM c"; // Get Expected - List expectedDocs = createdDocuments - .stream() - .collect(Collectors.toList()); + List expectedDocs = new ArrayList<>(createdDocuments); assertThat(expectedDocs).isNotEmpty(); this.queryWithContinuationTokensAndPageSizes(query, new int[] {1, 10, 100}, expectedDocs); } - - // TODO: DANOBLE: Investigate DIRECT TCP performance issue - // Links: - // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028https://msdata.visualstudio.com/CosmosDB/_workitems/edit/367028 - // Notes: - // When I've watch this method execute in the debugger and seen that the code sometimes pauses for quite a while in - // the middle of the second group of 21 documents. I test against a debug instance of the public emulator and so - // what I'm seeing could be the result of a public emulator performance issue. Of course, it might also be the - // result of a TCP protocol performance problem. @BeforeClass(groups = { "simple", "non-emulator" }, timeOut = 2 * SETUP_TIMEOUT) public void beforeClass() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java index 5b9509c79d1d9..661a35e9bc0ed 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java @@ -22,31 +22,36 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosPermission; +import com.azure.data.cosmos.CosmosPermissionResponse; +import com.azure.data.cosmos.CosmosPermissionSettings; +import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosUser; +import com.azure.data.cosmos.CosmosUserSettings; import com.azure.data.cosmos.PermissionMode; -import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.User; -import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Mono; import java.util.UUID; -//TODO: change to use external TestSuiteBase +//TODO: change to use external TestSuiteBase public class PermissionCrudTest extends TestSuiteBase { - private Database createdDatabase; - private User createdUser; + private CosmosDatabase createdDatabase; + private CosmosUser createdUser; + private final String databaseId = CosmosDatabaseForTest.generateId(); - private AsyncDocumentClient client; + private CosmosClient client; @Factory(dataProvider = "clientBuilders") - public PermissionCrudTest(AsyncDocumentClient.Builder clientBuilder) { + public PermissionCrudTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @@ -55,17 +60,16 @@ public void createPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); //create permission - Permission permission = new Permission(); - permission.id(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.READ); - permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); - + CosmosPermissionSettings permissionSettings = new CosmosPermissionSettings() + .id(UUID.randomUUID().toString()) + .permissionMode(PermissionMode.READ) + .resourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); - Observable> createObservable = client.createPermission(getUserLink(), permission, null); + Mono createObservable = createdUser.createPermission(permissionSettings, null); // validate permission creation - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(permission.id()) + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(permissionSettings.id()) .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() @@ -78,18 +82,19 @@ public void readPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); // create permission - Permission permission = new Permission(); - permission.id(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.READ); - permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); - Permission readBackPermission = client.createPermission(getUserLink(), permission, null).toBlocking().single().getResource(); + CosmosPermissionSettings permissionSettings = new CosmosPermissionSettings() + .id(UUID.randomUUID().toString()) + .permissionMode(PermissionMode.READ) + .resourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); + CosmosPermissionResponse readBackPermission = createdUser.createPermission(permissionSettings, null) + .block(); // read Permission - Observable> readObservable = client.readPermission(readBackPermission.selfLink(), null); + Mono readObservable = readBackPermission.getPermission().read(null); // validate permission read - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() - .withId(permission.id()) + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(permissionSettings.id()) .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() @@ -103,17 +108,18 @@ public void deletePermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); // create permission - Permission permission = new Permission(); - permission.id(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.READ); - permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); - Permission readBackPermission = client.createPermission(getUserLink(), permission, null).toBlocking().single().getResource(); - + CosmosPermissionSettings permissionSettings = new CosmosPermissionSettings() + .id(UUID.randomUUID().toString()) + .permissionMode(PermissionMode.READ) + .resourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); + CosmosPermissionResponse readBackPermission = createdUser.createPermission(permissionSettings, null) + .block(); // delete - Observable> deleteObservable = client.deletePermission(readBackPermission.selfLink(), null); + Mono deleteObservable = readBackPermission.getPermission() + .delete(null); // validate delete permission - ResourceResponseValidator validator = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .nullResource() .build(); validateSuccess(deleteObservable, validator); @@ -121,7 +127,8 @@ public void deletePermission() throws Exception { waitIfNeededForReplicasToCatchUp(clientBuilder()); // attempt to read the permission which was deleted - Observable> readObservable = client.readPermission(readBackPermission.selfLink(), null); + Mono readObservable = readBackPermission.getPermission() + .read( null); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); validateFailure(readObservable, notFoundValidator); } @@ -132,31 +139,33 @@ public void upsertPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); // create permission - Permission permission = new Permission(); - permission.id(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.READ); - permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); - Permission readBackPermission = client.upsertPermission(getUserLink(), permission, null).toBlocking().single().getResource(); - + CosmosPermissionSettings permissionSettings = new CosmosPermissionSettings() + .id(UUID.randomUUID().toString()) + .permissionMode(PermissionMode.READ) + .resourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); + CosmosPermissionResponse readBackPermissionResponse = createdUser.createPermission(permissionSettings, null) + .block(); + CosmosPermissionSettings readBackPermission = readBackPermissionResponse.settings(); // read Permission - Observable> readObservable = client.readPermission(readBackPermission.selfLink(), null); - + Mono readObservable = readBackPermissionResponse.getPermission() + .read( null); + // validate permission creation - ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(readBackPermission.id()) .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); - validateSuccess(readObservable, validatorForRead); + validateSuccess(readObservable, validator); //update permission - readBackPermission.setPermissionMode(PermissionMode.ALL); + readBackPermission = readBackPermission.permissionMode(PermissionMode.ALL); - Observable> updateObservable = client.upsertPermission(getUserLink(), readBackPermission, null); + Mono updateObservable = createdUser.upsertPermission(readBackPermission, null); // validate permission update - ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() + CosmosResponseValidator validatorForUpdate = new CosmosResponseValidator.Builder() .withId(readBackPermission.id()) .withPermissionMode(PermissionMode.ALL) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") @@ -170,32 +179,37 @@ public void replacePermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); + String id = UUID.randomUUID().toString(); // create permission - Permission permission = new Permission(); - permission.id(UUID.randomUUID().toString()); - permission.setPermissionMode(PermissionMode.READ); - permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); - Permission readBackPermission = client.createPermission(getUserLink(), permission, null).toBlocking().single().getResource(); - + CosmosPermissionSettings permissionSettings = new CosmosPermissionSettings() + .id(id) + .permissionMode(PermissionMode.READ) + .resourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); + CosmosPermissionResponse readBackPermissionResponse = createdUser.createPermission(permissionSettings, null) + .block(); // read Permission - Observable> readObservable = client.readPermission(readBackPermission.selfLink(), null); + Mono readObservable = readBackPermissionResponse.getPermission() + .read(null); // validate permission creation - ResourceResponseValidator validatorForRead = new ResourceResponseValidator.Builder() - .withId(readBackPermission.id()) + CosmosResponseValidator validator = new CosmosResponseValidator.Builder() + .withId(readBackPermissionResponse.getPermission().id()) .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); - validateSuccess(readObservable, validatorForRead); + validateSuccess(readObservable, validator); //update permission - readBackPermission.setPermissionMode(PermissionMode.ALL); - - Observable> updateObservable = client.replacePermission(readBackPermission, null); + CosmosPermissionSettings readBackPermission = readBackPermissionResponse.settings(); + readBackPermission = readBackPermission.permissionMode(PermissionMode.ALL); + + CosmosPermission cosmosPermission = createdUser.getPermission(id); + Mono updateObservable = readBackPermissionResponse.getPermission() + .replace(readBackPermission, null); // validate permission replace - ResourceResponseValidator validatorForUpdate = new ResourceResponseValidator.Builder() + CosmosResponseValidator validatorForUpdate = new CosmosResponseValidator.Builder() .withId(readBackPermission.id()) .withPermissionMode(PermissionMode.ALL) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") @@ -207,7 +221,7 @@ public void replacePermission() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { client = clientBuilder().build(); - createdDatabase = SHARED_DATABASE; + createdDatabase = createDatabase(client, databaseId); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) @@ -215,13 +229,9 @@ public void afterClass() { safeClose(client); } - private static User getUserDefinition() { - User user = new User(); - user.id(UUID.randomUUID().toString()); - return user; + private static CosmosUserSettings getUserDefinition() { + return new CosmosUserSettings() + .id(UUID.randomUUID().toString()); } - private String getUserLink() { - return createdUser.selfLink(); - } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java index 75abe8275169f..500dea2a01e7b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java @@ -37,7 +37,7 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; @@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat; -//TODO: change to use external TestSuiteBase +//TODO: change to use external TestSuiteBase public class PermissionQueryTest extends TestSuiteBase { public final String databaseId = DatabaseForTest.generateId(); @@ -70,7 +70,7 @@ public void queryWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(5); - Observable> queryObservable = client + Flux> queryObservable = client .queryPermissions(getUserLink(), query, options); List expectedDocs = createdPermissions.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList()); @@ -94,7 +94,7 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Observable> queryObservable = client + Flux> queryObservable = client .queryPermissions(getUserLink(), query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() @@ -113,7 +113,7 @@ public void queryAll() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(3); options.enableCrossPartitionQuery(true); - Observable> queryObservable = client + Flux> queryObservable = client .queryPermissions(getUserLink(), query, options); int expectedPageSize = (createdPermissions.size() + options.maxItemCount() - 1) / options.maxItemCount(); @@ -136,7 +136,7 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Observable> queryObservable = client + Flux> queryObservable = client .queryPermissions(getUserLink(), query, options); FailureValidator validator = new FailureValidator.Builder() @@ -183,7 +183,7 @@ public Permission createPermissions(AsyncDocumentClient client, int index) { permission.setPermissionMode(PermissionMode.READ); permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgT" + Integer.toString(index) + "="); - return client.createPermission(getUserLink(), permission, null).toBlocking().single().getResource(); + return client.createPermission(getUserLink(), permission, null).single().block().getResource(); } private String getUserLink() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java index 7fa24e154a6de..e027d9c4a3eeb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java @@ -35,14 +35,15 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; -//TODO: change to use external TestSuiteBase +//TODO: change to use external TestSuiteBase public class ReadFeedOffersTest extends TestSuiteBase { protected static final int FEED_TIMEOUT = 60000; @@ -67,7 +68,7 @@ public void readOffers() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Observable> feedObservable = client.readOffers(options); + Flux> feedObservable = client.readOffers(options); int expectedPageSize = (allOffers.size() + options.maxItemCount() - 1) / options.maxItemCount(); @@ -91,11 +92,11 @@ public void beforeClass() { } allOffers = client.readOffers(null) - .map(frp -> frp.results()) - .toList() - .map(list -> list.stream().flatMap(x -> x.stream()).collect(Collectors.toList())) - .toBlocking() - .single(); + .map(FeedResponse::results) + .collectList() + .map(list -> list.stream().flatMap(Collection::stream).collect(Collectors.toList())) + .single() + .block(); } @AfterClass(groups = { "emulator" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) @@ -114,7 +115,7 @@ public DocumentCollection createCollections(AsyncDocumentClient client) { partitionKeyDef.paths(paths); collection.setPartitionKey(partitionKeyDef); - return client.createCollection(getDatabaseLink(), collection, null).toBlocking().single().getResource(); + return client.createCollection(getDatabaseLink(), collection, null).single().block().getResource(); } private String getDatabaseLink() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java index b9db20bbd03c8..db4966d0dc7b5 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java @@ -29,20 +29,21 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Permission; import com.azure.data.cosmos.PermissionMode; +import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.User; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; -//TODO: change to use external TestSuiteBase +//TODO: change to use external TestSuiteBase public class ReadFeedPermissionsTest extends TestSuiteBase { public final String databaseId = DatabaseForTest.generateId(); @@ -64,14 +65,14 @@ public void readPermissions() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Observable> feedObservable = client.readPermissions(getUserLink(), options); + Flux> feedObservable = client.readPermissions(getUserLink(), options); int expectedPageSize = (createdPermissions.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdPermissions.size()) .numberOfPages(expectedPageSize) - .exactlyContainsInAnyOrder(createdPermissions.stream().map(d -> d.resourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(createdPermissions.stream().map(Resource::resourceId).collect(Collectors.toList())) .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -110,7 +111,7 @@ public Permission createPermissions(AsyncDocumentClient client, int index) { permission.id(UUID.randomUUID().toString()); permission.setPermissionMode(PermissionMode.READ); permission.setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgT" + Integer.toString(index) + "="); - return client.createPermission(getUserLink(), permission, null).toBlocking().single().getResource(); + return client.createPermission(getUserLink(), permission, null).single().block().getResource(); } private String getUserLink() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java index ee92587679c76..4c405c6614841 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java @@ -35,7 +35,8 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; + public class ReadFeedPkrTests extends TestSuiteBase { @@ -55,7 +56,7 @@ public void readPartitionKeyRanges() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Observable> feedObservable = client.readPartitionKeyRanges(getCollectionLink(), options); + Flux> feedObservable = client.readPartitionKeyRanges(getCollectionLink(), options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(1) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java index af43751145d93..ae14803ebad44 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java @@ -43,7 +43,7 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.List; @@ -126,42 +126,42 @@ public void beforeClass() throws Exception { // CREATE user createdUser = createUser(client, createdDatabase.id(), getUserDefinition()); // CREATE permission for collection - createdCollPermission = client.createPermission(getUserLink(), getCollPermission(), null).toBlocking().single() + createdCollPermission = client.createPermission(getUserLink(), getCollPermission(), null).single().block() .getResource(); - createdCollPermissionWithName = client.createPermission(getUserLink(), getCollPermissionWithName(), null).toBlocking().single() + createdCollPermissionWithName = client.createPermission(getUserLink(), getCollPermissionWithName(), null).single().block() .getResource(); // CREATE permission for document - createdDocPermission = client.createPermission(getUserLink(), getDocPermission(), null).toBlocking().single() + createdDocPermission = client.createPermission(getUserLink(), getDocPermission(), null).single().block() .getResource(); - createdDocPermissionWithName = client.createPermission(getUserLink(), getDocPermissionWithName(), null).toBlocking().single() + createdDocPermissionWithName = client.createPermission(getUserLink(), getDocPermissionWithName(), null).single().block() .getResource(); // CREATE permission for document with partition key createdDocPermissionWithPartitionKey = client - .createPermission(getUserLink(), getDocPermissionWithPartitionKey(), null).toBlocking().single() + .createPermission(getUserLink(), getDocPermissionWithPartitionKey(), null).single().block() .getResource(); createdDocPermissionWithPartitionKeyWithName = client - .createPermission(getUserLink(), getDocPermissionWithPartitionKeyWithName(), null).toBlocking().single() + .createPermission(getUserLink(), getDocPermissionWithPartitionKeyWithName(), null).single().block() .getResource(); // CREATE permission for document with partition key 2 createdDocPermissionWithPartitionKey2 = client - .createPermission(getUserLink(), getDocPermissionWithPartitionKey2(), null).toBlocking().single() + .createPermission(getUserLink(), getDocPermissionWithPartitionKey2(), null).single().block() .getResource(); createdDocPermissionWithPartitionKey2WithName = client - .createPermission(getUserLink(), getDocPermissionWithPartitionKey2WithName(), null).toBlocking().single() + .createPermission(getUserLink(), getDocPermissionWithPartitionKey2WithName(), null).single().block() .getResource(); // CREATE permission for collection with partition key createdColPermissionWithPartitionKey = client - .createPermission(getUserLink(), getColPermissionWithPartitionKey(), null).toBlocking().single() + .createPermission(getUserLink(), getColPermissionWithPartitionKey(), null).single().block() .getResource(); createdColPermissionWithPartitionKeyWithName = client - .createPermission(getUserLink(), getColPermissionWithPartitionKeyWithName(), null).toBlocking().single() + .createPermission(getUserLink(), getColPermissionWithPartitionKeyWithName(), null).single().block() .getResource(); // CREATE permission for collection with partition key createdColPermissionWithPartitionKey2 = client - .createPermission(getUserLink(), getColPermissionWithPartitionKey2(), null).toBlocking().single() + .createPermission(getUserLink(), getColPermissionWithPartitionKey2(), null).single().block() .getResource(); createdColPermissionWithPartitionKey2WithName = client - .createPermission(getUserLink(), getColPermissionWithPartitionKey2WithName(), null).toBlocking().single() + .createPermission(getUserLink(), getColPermissionWithPartitionKey2WithName(), null).single().block() .getResource(); } @@ -258,7 +258,7 @@ public void readCollectionFromPermissionFeed(String collectionUrl, Permission pe asyncClientResourceToken = new AsyncDocumentClient.Builder().withServiceEndpoint(TestConfigurations.HOST) .withPermissionFeed(permissionFeed).withConnectionPolicy(ConnectionPolicy.defaultPolicy()) .withConsistencyLevel(ConsistencyLevel.SESSION).build(); - Observable> readObservable = asyncClientResourceToken + Flux> readObservable = asyncClientResourceToken .readCollection(collectionUrl, null); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() @@ -289,7 +289,7 @@ public void readDocumentFromPermissionFeed(String documentUrl, Permission permis } else { options.setPartitionKey(PartitionKey.None); } - Observable> readObservable = asyncClientResourceToken + Flux> readObservable = asyncClientResourceToken .readDocument(documentUrl, options); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .withId(documentId).build(); @@ -314,7 +314,7 @@ public void readDocumentFromResouceToken(String resourceToken) throws Exception .build(); RequestOptions options = new RequestOptions(); options.setPartitionKey(PartitionKey.None); - Observable> readObservable = asyncClientResourceToken + Flux> readObservable = asyncClientResourceToken .readDocument(createdDocument.selfLink(), options); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .withId(createdDocument.id()).build(); @@ -341,7 +341,7 @@ public void readDocumentOfParKeyFromTwoCollPermissionWithDiffPartitionKeys(Strin .withConsistencyLevel(ConsistencyLevel.SESSION).build(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(partitionKey)); - Observable> readObservable = asyncClientResourceToken + Flux> readObservable = asyncClientResourceToken .readDocument(documentUrl, options); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .withId(documentId).build(); @@ -368,7 +368,7 @@ public void readDocumentFromCollPermissionWithDiffPartitionKey_ResourceNotFound( .withConsistencyLevel(ConsistencyLevel.SESSION).build(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(partitionKey)); - Observable> readObservable = asyncClientResourceToken + Flux> readObservable = asyncClientResourceToken .readDocument(documentUrl, options); FailureValidator validator = new FailureValidator.Builder().resourceNotFound().build(); validateFailure(readObservable, validator); @@ -397,7 +397,7 @@ public void readDocumentFromCollPermissionWithDiffPartitionKey_WithException() t .build(); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(PARTITION_KEY_VALUE_2)); - Observable> readObservable = asyncClientResourceToken + Flux> readObservable = asyncClientResourceToken .readDocument(createdDocumentWithPartitionKey.selfLink(), options); FailureValidator validator = new FailureValidator.Builder().resourceTokenNotFound().build(); validateFailure(readObservable, validator); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java index 91d98c5ea4a02..4aa54eb8291d6 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java @@ -39,11 +39,12 @@ import java.util.UUID; -public class StoredProcedureCrudTest extends TestSuiteBase { +import static org.assertj.core.api.Assertions.assertThat; - private CosmosContainer createdCollection; +public class StoredProcedureCrudTest extends TestSuiteBase { private CosmosClient client; + private CosmosContainer container; @Factory(dataProvider = "clientBuildersWithDirect") public StoredProcedureCrudTest(CosmosClientBuilder clientBuilder) { @@ -53,77 +54,74 @@ public StoredProcedureCrudTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createStoredProcedure() throws Exception { - // create a stored procedure CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); - Mono createObservable = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()); + Mono createObservable = container.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()); - // validate stored procedure creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(storedProcedureDef.id()) - .withStoredProcedureBody("function() {var x = 10;}") - .notNullEtag() - .build(); + .withId(storedProcedureDef.id()) + .withStoredProcedureBody("function() {var x = 10;}") + .notNullEtag() + .build(); + validateSuccess(createObservable, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readStoredProcedure() throws Exception { - // create a stored procedure + CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); - CosmosStoredProcedure storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()) - .block().storedProcedure(); + CosmosStoredProcedure storedProcedure = container.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); - // read stored procedure waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = storedProcedure.read(null); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(storedProcedureDef.id()) - .withStoredProcedureBody("function() {var x = 10;}") - .notNullEtag() - .build(); + .withId(storedProcedureDef.id()) + .withStoredProcedureBody("function() {var x = 10;}") + .notNullEtag() + .build(); + validateSuccess(readObservable, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteStoredProcedure() throws Exception { - // create a stored procedure + CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); - CosmosStoredProcedure storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()) - .block().storedProcedure(); - // delete + CosmosStoredProcedure storedProcedure = this.container.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); Mono deleteObservable = storedProcedure.delete(new CosmosStoredProcedureRequestOptions()); - // validate - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .nullResource() - .build(); + CosmosResponseValidator validator = new CosmosResponseValidator.Builder<>() + .nullResource() + .build(); + validateSuccess(deleteObservable, validator); - // attempt to read stored procedure which was deleted - waitIfNeededForReplicasToCatchUp(clientBuilder()); + waitIfNeededForReplicasToCatchUp(this.clientBuilder()); Mono readObservable = storedProcedure.read(null); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); validateFailure(readObservable, notFoundValidator); } - @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) + @BeforeClass(groups = { "simple" }, timeOut = 10_000 * SETUP_TIMEOUT) public void beforeClass() { - client = clientBuilder().build(); - createdCollection = getSharedMultiPartitionCosmosContainer(client); + assertThat(this.client).isNull(); + this.client = clientBuilder().build(); + this.container = getSharedMultiPartitionCosmosContainer(this.client); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { - safeClose(client); + assertThat(this.client).isNotNull(); + this.client.close(); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index bda9d574de7fd..1a9e52beb4e33 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -41,6 +41,7 @@ import com.azure.data.cosmos.CosmosDatabaseSettings; import com.azure.data.cosmos.CosmosItem; import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponse; import com.azure.data.cosmos.CosmosResponseValidator; @@ -78,10 +79,8 @@ import org.testng.annotations.DataProvider; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import rx.Observable; +import reactor.core.scheduler.Schedulers; -import java.io.PrintWriter; -import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -194,27 +193,29 @@ public CosmosDatabase getDatabase(String id) { @BeforeSuite(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}, timeOut = SUITE_SETUP_TIMEOUT) public static void beforeSuite() { + logger.info("beforeSuite Started"); - CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); - CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.create(DatabaseManagerImpl.getInstance(houseKeepingClient)); - SHARED_DATABASE = dbForTest.createdDatabase; - CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); - options.offerThroughput(10100); - SHARED_MULTI_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options); - SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES = createCollection(SHARED_DATABASE, getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes(), options); - options.offerThroughput(6000); - SHARED_SINGLE_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options); + + try (CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build()) { + CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.create(DatabaseManagerImpl.getInstance(houseKeepingClient)); + SHARED_DATABASE = dbForTest.createdDatabase; + CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); + options.offerThroughput(10100); + SHARED_MULTI_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options); + SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES = createCollection(SHARED_DATABASE, getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes(), options); + options.offerThroughput(6000); + SHARED_SINGLE_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options); + } } @AfterSuite(groups = {"simple", "long", "direct", "multi-master", "emulator", "non-emulator"}, timeOut = SUITE_SHUTDOWN_TIMEOUT) public static void afterSuite() { + logger.info("afterSuite Started"); - CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); - try { + + try (CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build()) { safeDeleteDatabase(SHARED_DATABASE); CosmosDatabaseForTest.cleanupStaleTestDatabases(DatabaseManagerImpl.getInstance(houseKeepingClient)); - } finally { - safeClose(houseKeepingClient); } } @@ -222,37 +223,37 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { CosmosContainerSettings cosmosContainerSettings = cosmosContainer.read().block().settings(); String cosmosContainerId = cosmosContainerSettings.id(); logger.info("Truncating collection {} ...", cosmosContainerId); - CosmosClient houseKeepingClient = createGatewayHouseKeepingDocumentClient().build(); - try { - List paths = cosmosContainerSettings.partitionKey().paths(); - FeedOptions options = new FeedOptions(); - options.maxDegreeOfParallelism(-1); - options.enableCrossPartitionQuery(true); - options.maxItemCount(100); + List paths = cosmosContainerSettings.partitionKey().paths(); + FeedOptions options = new FeedOptions(); + options.maxDegreeOfParallelism(-1); + options.enableCrossPartitionQuery(true); + options.maxItemCount(100); - logger.info("Truncating collection {} documents ...", cosmosContainer.id()); + logger.info("Truncating collection {} documents ...", cosmosContainer.id()); - cosmosContainer.queryItems("SELECT * FROM root", options) + cosmosContainer.queryItems("SELECT * FROM root", options) + .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.results())) - .flatMap(doc -> { - - Object propertyValue = null; - if (paths != null && !paths.isEmpty()) { - List pkPath = PathParser.getPathParts(paths.get(0)); - propertyValue = doc.getObjectByPath(pkPath); - if (propertyValue == null) { - propertyValue = PartitionKey.None; - } + .flatMap(doc -> { - } - return cosmosContainer.getItem(doc.id(), propertyValue).delete(); - }).collectList().block(); - logger.info("Truncating collection {} triggers ...", cosmosContainerId); + Object propertyValue = null; + if (paths != null && !paths.isEmpty()) { + List pkPath = PathParser.getPathParts(paths.get(0)); + propertyValue = doc.getObjectByPath(pkPath); + if (propertyValue == null) { + propertyValue = PartitionKey.None; + } - cosmosContainer.queryTriggers("SELECT * FROM root", options) - .flatMap(page -> Flux.fromIterable(page.results())) - .flatMap(trigger -> { - CosmosRequestOptions requestOptions = new CosmosRequestOptions(); + } + return cosmosContainer.getItem(doc.id(), propertyValue).delete(); + }).then().block(); + logger.info("Truncating collection {} triggers ...", cosmosContainerId); + + cosmosContainer.queryTriggers("SELECT * FROM root", options) + .publishOn(Schedulers.parallel()) + .flatMap(page -> Flux.fromIterable(page.results())) + .flatMap(trigger -> { + CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = trigger.getObjectByPath(PathParser.getPathParts(paths.get(0))); @@ -260,41 +261,39 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { // } return cosmosContainer.getTrigger(trigger.id()).delete(requestOptions); - }).collectList().block(); + }).then().block(); - logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); + logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); - cosmosContainer.queryStoredProcedures("SELECT * FROM root", options) - .flatMap(page -> Flux.fromIterable(page.results())) - .flatMap(storedProcedure -> { - CosmosRequestOptions requestOptions = new CosmosRequestOptions(); + cosmosContainer.queryStoredProcedures("SELECT * FROM root", options) + .publishOn(Schedulers.parallel()) + .flatMap(page -> Flux.fromIterable(page.results())) + .flatMap(storedProcedure -> { + CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = storedProcedure.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getStoredProcedure(storedProcedure.id()).delete(requestOptions); - }).collectList().block(); + return cosmosContainer.getStoredProcedure(storedProcedure.id()).delete(requestOptions); + }).then().block(); - logger.info("Truncating collection {} udfs ...", cosmosContainerId); + logger.info("Truncating collection {} udfs ...", cosmosContainerId); - cosmosContainer.queryUserDefinedFunctions("SELECT * FROM root", options) - .flatMap(page -> Flux.fromIterable(page.results())) - .flatMap(udf -> { - CosmosRequestOptions requestOptions = new CosmosRequestOptions(); + cosmosContainer.queryUserDefinedFunctions("SELECT * FROM root", options) + .publishOn(Schedulers.parallel()) + .flatMap(page -> Flux.fromIterable(page.results())) + .flatMap(udf -> { + CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = udf.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getUserDefinedFunction(udf.id()).delete(requestOptions); - }).collectList().block(); - - } finally { - houseKeepingClient.close(); - } + return cosmosContainer.getUserDefinedFunction(udf.id()).delete(requestOptions); + }).then().block(); logger.info("Finished truncating collection {}.", cosmosContainerId); } @@ -449,38 +448,32 @@ public static CosmosItem createDocument(CosmosContainer cosmosContainer, CosmosI return cosmosContainer.createItem(item).block().item(); } - /* - // TODO: respect concurrencyLevel; - public Flux bulkInsert(CosmosContainer cosmosContainer, - List documentDefinitionList, - int concurrencyLevel) { - CosmosItemProperties first = documentDefinitionList.remove(0); - Flux result = Flux.from(cosmosContainer.createItem(first)); + private Flux bulkInsert(CosmosContainer cosmosContainer, + List documentDefinitionList, + int concurrencyLevel) { + List> result = new ArrayList<>(documentDefinitionList.size()); for (CosmosItemProperties docDef : documentDefinitionList) { - result.concatWith(cosmosContainer.createItem(docDef)); + result.add(cosmosContainer.createItem(docDef)); } - return result; + return Flux.merge(Flux.fromIterable(result), concurrencyLevel); } -*/ public List bulkInsertBlocking(CosmosContainer cosmosContainer, List documentDefinitionList) { - /* return bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) - .parallel() - .runOn(Schedulers.parallel()) + .publishOn(Schedulers.parallel()) .map(CosmosItemResponse::properties) - .sequential() .collectList() .block(); - */ - return Flux.merge(documentDefinitionList.stream() - .map(d -> cosmosContainer.createItem(d).map(response -> response.properties())) - .collect(Collectors.toList())).collectList().block(); } - public static ConsistencyLevel getAccountDefaultConsistencyLevel(CosmosClient client) { - return CosmosBridgeInternal.getDatabaseAccount(client).block().getConsistencyPolicy().getDefaultConsistencyLevel(); + public void voidBulkInsertBlocking(CosmosContainer cosmosContainer, + List documentDefinitionList) { + bulkInsert(cosmosContainer, documentDefinitionList, DEFAULT_BULK_INSERT_CONCURRENCY_LEVEL) + .publishOn(Schedulers.parallel()) + .map(CosmosItemResponse::properties) + .then() + .block(); } public static CosmosUser createUser(CosmosClient client, String databaseId, CosmosUserSettings userSettings) { @@ -658,7 +651,7 @@ static protected void safeDeleteCollection(CosmosContainer collection) { static protected void safeDeleteCollection(CosmosDatabase database, String collectionId) { if (database != null && collectionId != null) { try { - database.getContainer(collectionId).read().block().container().delete().block(); + database.getContainer(collectionId).delete().block(); } catch (Exception e) { } } @@ -686,30 +679,13 @@ static protected void safeClose(CosmosClient client) { } } - public void validateQuerySuccess(Observable> observable, - FeedResponseListValidator validator) { - validateQuerySuccess(observable, validator, subscriberValidationTimeout); - } - - public static void validateQuerySuccess(Observable> observable, - FeedResponseListValidator validator, long timeout) { - - VerboseTestSubscriber> testSubscriber = new VerboseTestSubscriber<>(); - - observable.subscribe(testSubscriber); - testSubscriber.awaitTerminalEvent(timeout, TimeUnit.MILLISECONDS); - testSubscriber.assertNoErrors(); - testSubscriber.assertCompleted(); - validator.validate(testSubscriber.getOnNextEvents()); - } - public void validateSuccess(Mono single, CosmosResponseValidator validator) throws InterruptedException { validateSuccess(single.flux(), validator, subscriberValidationTimeout); } public static void validateSuccess(Flux flowable, - CosmosResponseValidator validator, long timeout) throws InterruptedException { + CosmosResponseValidator validator, long timeout) { TestSubscriber testSubscriber = new TestSubscriber<>(); @@ -753,8 +729,7 @@ public static void validateQuerySuccess(Flux (FeedResponse) object) - .collect(Collectors.toList())); + validator.validate(testSubscriber.values()); } public void validateQueryFailure(Flux> flowable, FailureValidator validator) { @@ -782,9 +757,9 @@ public static Object[][] clientBuilders() { @DataProvider public static Object[][] clientBuildersWithSessionConsistency() { return new Object[][]{ - {createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null)}, - {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.HTTPS, false, null)}, - {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.TCP, false, null)} + {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.HTTPS, false, null)}, + {createDirectRxDocumentClient(ConsistencyLevel.SESSION, Protocol.TCP, false, null)}, + {createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null)} }; } @@ -847,7 +822,6 @@ private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List cosmosConfigurations = new ArrayList<>(); - cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null)); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, @@ -862,6 +836,8 @@ private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) c.getConfigs().getProtocol() )); + cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null)); + return cosmosConfigurations.stream().map(b -> new Object[]{b}).collect(Collectors.toList()).toArray(new Object[0][]); } @@ -937,7 +913,6 @@ private static Object[][] clientBuildersWithDirect(List testCo boolean isMultiMasterEnabled = preferredLocations != null && accountConsistency == ConsistencyLevel.SESSION; List cosmosConfigurations = new ArrayList<>(); - cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations)); for (Protocol protocol : protocols) { testConsistencies.forEach(consistencyLevel -> cosmosConfigurations.add(createDirectRxDocumentClient(consistencyLevel, @@ -952,6 +927,8 @@ private static Object[][] clientBuildersWithDirect(List testCo c.getConfigs().getProtocol() )); + cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations)); + return cosmosConfigurations.stream().map(c -> new Object[]{c}).collect(Collectors.toList()).toArray(new Object[0][]); } @@ -1018,24 +995,4 @@ public Object[][] queryMetricsArgProvider() { {false}, }; } - - public static class VerboseTestSubscriber extends rx.observers.TestSubscriber { - @Override - public void assertNoErrors() { - List onErrorEvents = getOnErrorEvents(); - StringBuilder errorMessageBuilder = new StringBuilder(); - if (!onErrorEvents.isEmpty()) { - for(Throwable throwable : onErrorEvents) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - throwable.printStackTrace(pw); - String sStackTrace = sw.toString(); // stack trace as a string - errorMessageBuilder.append(sStackTrace); - } - - AssertionError ae = new AssertionError(errorMessageBuilder.toString()); - throw ae; - } - } - } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java index fdab59e72fc63..fca092e56c44c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java @@ -53,7 +53,7 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import rx.Observable; +import reactor.core.publisher.Flux; import java.time.OffsetDateTime; import java.util.ArrayList; @@ -64,7 +64,6 @@ import static org.assertj.core.api.Assertions.assertThat; -//TODO: change to use external TestSuiteBase public class TokenResolverTest extends TestSuiteBase { private class UserClass { @@ -104,16 +103,16 @@ public Object[][] connectionMode() { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { createdDatabase = SHARED_DATABASE; - createdCollection = SHARED_SINGLE_PARTITION_COLLECTION; + createdCollection = SHARED_MULTI_PARTITION_COLLECTION; client = clientBuilder().build(); userWithReadPermission = createUser(client, createdDatabase.id(), getUserDefinition()); - readPermission = client.createPermission(userWithReadPermission.selfLink(), getPermission(createdCollection, "ReadPermissionOnColl", PermissionMode.READ), null).toBlocking().single() + readPermission = client.createPermission(userWithReadPermission.selfLink(), getPermission(createdCollection, "ReadPermissionOnColl", PermissionMode.READ), null).single().block() .getResource(); userWithAllPermission = createUser(client, createdDatabase.id(), getUserDefinition()); - allPermission = client.createPermission(userWithAllPermission.selfLink(), getPermission(createdCollection, "AllPermissionOnColl", PermissionMode.ALL), null).toBlocking().single() + allPermission = client.createPermission(userWithAllPermission.selfLink(), getPermission(createdCollection, "AllPermissionOnColl", PermissionMode.ALL), null).single().block() .getResource(); } @@ -121,7 +120,7 @@ public void beforeClass() { public void readDocumentWithReadPermission(ConnectionMode connectionMode) { Document docDefinition = getDocumentDefinition(); ResourceResponse resourceResponse = client - .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).toBlocking().first(); + .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).blockFirst(); AsyncDocumentClient asyncClientWithTokenResolver = null; try { asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.READ); @@ -130,7 +129,7 @@ public void readDocumentWithReadPermission(ConnectionMode connectionMode) { HashMap properties = new HashMap(); properties.put("UserId", "readUser"); requestOptions.setProperties(properties); - Observable> readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().selfLink(), requestOptions); + Flux> readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().selfLink(), requestOptions); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .withId(resourceResponse.getResource().id()).build(); validateSuccess(readObservable, validator); @@ -143,13 +142,13 @@ public void readDocumentWithReadPermission(ConnectionMode connectionMode) { public void deleteDocumentWithReadPermission(ConnectionMode connectionMode) { Document docDefinition = getDocumentDefinition(); ResourceResponse resourceResponse = client - .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).toBlocking().first(); + .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).blockFirst(); AsyncDocumentClient asyncClientWithTokenResolver = null; try { asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.READ); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceResponse.getResource().get("mypk"))); - Observable> readObservable = asyncClientWithTokenResolver.deleteDocument(resourceResponse.getResource().selfLink(), requestOptions); + Flux> readObservable = asyncClientWithTokenResolver.deleteDocument(resourceResponse.getResource().selfLink(), requestOptions); FailureValidator validator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.FORBIDDEN).build(); validateFailure(readObservable, validator); } finally { @@ -162,7 +161,7 @@ public void writeDocumentWithReadPermission(ConnectionMode connectionMode) { AsyncDocumentClient asyncClientWithTokenResolver = null; try { asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.READ); - Observable> readObservable = asyncClientWithTokenResolver.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, true); + Flux> readObservable = asyncClientWithTokenResolver.createDocument(createdCollection.selfLink(), getDocumentDefinition(), null, true); FailureValidator validator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.FORBIDDEN).build(); validateFailure(readObservable, validator); } finally { @@ -176,7 +175,7 @@ public void writeDocumentWithAllPermission(ConnectionMode connectionMode) { try { asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.ALL); Document documentDefinition = getDocumentDefinition(); - Observable> readObservable = asyncClientWithTokenResolver.createDocument(createdCollection.selfLink(), documentDefinition, null, true); + Flux> readObservable = asyncClientWithTokenResolver.createDocument(createdCollection.selfLink(), documentDefinition, null, true); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .withId(documentDefinition.id()).build(); validateSuccess(readObservable, validator); @@ -189,13 +188,13 @@ public void writeDocumentWithAllPermission(ConnectionMode connectionMode) { public void deleteDocumentWithAllPermission(ConnectionMode connectionMode) { Document docDefinition = getDocumentDefinition(); ResourceResponse resourceResponse = client - .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).toBlocking().first(); + .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).blockFirst(); AsyncDocumentClient asyncClientWithTokenResolver = null; try { asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.ALL); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceResponse.getResource().get("mypk"))); - Observable> readObservable = asyncClientWithTokenResolver.deleteDocument(resourceResponse.getResource().selfLink(), requestOptions); + Flux> readObservable = asyncClientWithTokenResolver.deleteDocument(resourceResponse.getResource().selfLink(), requestOptions); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .nullResource().build(); validateSuccess(readObservable, validator); @@ -209,7 +208,7 @@ public void readCollectionWithReadPermission(ConnectionMode connectionMode) { AsyncDocumentClient asyncClientWithTokenResolver = null; try { asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.READ); - Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), null); + Flux> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), null); ResourceResponseValidator validator = new ResourceResponseValidator.Builder() .withId(createdCollection.id()).build(); validateSuccess(readObservable, validator); @@ -223,7 +222,7 @@ public void deleteCollectionWithReadPermission(ConnectionMode connectionMode) { AsyncDocumentClient asyncClientWithTokenResolver = null; try { asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.READ); - Observable> readObservable = asyncClientWithTokenResolver.deleteCollection(createdCollection.selfLink(), null); + Flux> readObservable = asyncClientWithTokenResolver.deleteCollection(createdCollection.selfLink(), null); FailureValidator validator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.FORBIDDEN).build(); validateFailure(readObservable, validator); } finally { @@ -235,7 +234,7 @@ public void deleteCollectionWithReadPermission(ConnectionMode connectionMode) { public void verifyingAuthTokenAPISequence(ConnectionMode connectionMode) { Document docDefinition = getDocumentDefinition(); ResourceResponse resourceResponse = client - .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).toBlocking().first(); + .createDocument(BridgeInternal.getAltLink(createdCollection), docDefinition, null, false).blockFirst(); AsyncDocumentClient asyncClientWithTokenResolver = null; try { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); @@ -254,7 +253,7 @@ public void verifyingAuthTokenAPISequence(ConnectionMode connectionMode) { .build(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setPartitionKey(new PartitionKey(resourceResponse.getResource().get("mypk"))); - Observable> readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().selfLink(), requestOptions); + Flux> readObservable = asyncClientWithTokenResolver.readDocument(resourceResponse.getResource().selfLink(), requestOptions); FailureValidator failureValidator = new FailureValidator.Builder().statusCode(HttpConstants.StatusCodes.UNAUTHORIZED).build(); validateFailure(readObservable, failureValidator); @@ -321,7 +320,7 @@ public void createAndExecuteSprocWithWritePermission(ConnectionMode connectionMo " }'" + "}"); - Observable> createObservable = asyncClientWithTokenResolver.createStoredProcedure(createdCollection.selfLink(), sproc, null); + Flux> createObservable = asyncClientWithTokenResolver.createStoredProcedure(createdCollection.selfLink(), sproc, null); ResourceResponseValidator createSucessValidator = new ResourceResponseValidator.Builder() .withId(sprocId).build(); validateSuccess(createObservable, createSucessValidator); @@ -329,7 +328,7 @@ public void createAndExecuteSprocWithWritePermission(ConnectionMode connectionMo RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey("")); String sprocLink = "dbs/" + createdDatabase.id() + "/colls/" + createdCollection.id() + "/sprocs/" + sprocId; - StoredProcedureResponse result = asyncClientWithTokenResolver.executeStoredProcedure(sprocLink, options, null).toBlocking().single(); + StoredProcedureResponse result = asyncClientWithTokenResolver.executeStoredProcedure(sprocLink, options, null).single().block(); assertThat(result.getResponseAsString()).isEqualTo("\"Success!\""); } finally { safeClose(asyncClientWithTokenResolver); @@ -345,9 +344,9 @@ public void readDocumentsWithAllPermission(ConnectionMode connectionMode) { try { asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.ALL); Document document1 = asyncClientWithTokenResolver.createDocument(createdCollection.selfLink(), new Document("{'id': '" + id1 + "'}"), null, false) - .toBlocking().single().getResource(); + .single().block().getResource(); Document document2 = asyncClientWithTokenResolver.createDocument(createdCollection.selfLink(), new Document("{'id': '" + id2 + "'}"), null, false) - .toBlocking().single().getResource(); + .single().block().getResource(); List expectedIds = new ArrayList(); String rid1 = document1.resourceId(); String rid2 = document2.resourceId(); @@ -357,10 +356,10 @@ public void readDocumentsWithAllPermission(ConnectionMode connectionMode) { FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Observable> queryObservable = asyncClientWithTokenResolver.queryDocuments(createdCollection.selfLink(), query, options); + Flux> queryObservable = asyncClientWithTokenResolver.queryDocuments(createdCollection.selfLink(), query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() - .numberOfPages(1) - .exactlyContainsInAnyOrder(expectedIds).build(); + .totalSize(2) + .exactlyContainsInAnyOrder(expectedIds).build(); validateQuerySuccess(queryObservable, validator, 10000); } finally { safeClose(asyncClientWithTokenResolver); @@ -369,9 +368,9 @@ public void readDocumentsWithAllPermission(ConnectionMode connectionMode) { @Test(groups = {"simple"}, dataProvider = "connectionMode", timeOut = TIMEOUT) public void readChangeFeedWithAllPermission(ConnectionMode connectionMode) throws InterruptedException { - + //setStartDateTime is not currently supported in multimaster mode. So skipping the test - if(BridgeInternal.isEnableMultipleWriteLocations(client.getDatabaseAccount().toBlocking().single())){ + if(BridgeInternal.isEnableMultipleWriteLocations(client.getDatabaseAccount().single().block())){ throw new SkipException("StartTime/IfModifiedSince is not currently supported when EnableMultipleWriteLocations is set"); } @@ -392,10 +391,10 @@ public void readChangeFeedWithAllPermission(ConnectionMode connectionMode) throw Thread.sleep(1000); document1 = asyncClientWithTokenResolver - .createDocument(createdCollection.selfLink(), document1, null, false).toBlocking().single() + .createDocument(createdCollection.selfLink(), document1, null, false).single().block() .getResource(); document2 = asyncClientWithTokenResolver - .createDocument(createdCollection.selfLink(), document2, null, false).toBlocking().single() + .createDocument(createdCollection.selfLink(), document2, null, false).single().block() .getResource(); List expectedIds = new ArrayList(); String rid1 = document1.resourceId(); @@ -408,7 +407,7 @@ public void readChangeFeedWithAllPermission(ConnectionMode connectionMode) throw options.startDateTime(befTime); Thread.sleep(1000); - Observable> queryObservable = asyncClientWithTokenResolver + Flux> queryObservable = asyncClientWithTokenResolver .queryDocumentChangeFeed(createdCollection.selfLink(), options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .exactlyContainsInAnyOrder(expectedIds).build(); @@ -434,7 +433,7 @@ public void verifyRuntimeExceptionWhenUserModifiesProperties(ConnectionMode conn RequestOptions options = new RequestOptions(); options.setProperties(new HashMap()); - Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); + Flux> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); FailureValidator validator = new FailureValidator.Builder().withRuntimeExceptionClass(UnsupportedOperationException.class).build(); validateFailure(readObservable, validator); } finally { @@ -463,7 +462,7 @@ public void verifyBlockListedUserThrows(ConnectionMode connectionMode) { HashMap properties = new HashMap(); properties.put(field, blockListedUser); options.setProperties(properties); - Observable> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); + Flux> readObservable = asyncClientWithTokenResolver.readCollection(createdCollection.selfLink(), options); FailureValidator validator = new FailureValidator.Builder().withRuntimeExceptionMessage(errorMessage).build(); validateFailure(readObservable, validator); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java index 23d1e60a60686..f4b7e3b7eb50f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java @@ -30,6 +30,7 @@ import com.azure.data.cosmos.CosmosTriggerSettings; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; import org.testng.annotations.AfterClass; @@ -48,7 +49,7 @@ public class TriggerQueryTest extends TestSuiteBase { private CosmosContainer createdCollection; - private List createdTriggers = new ArrayList<>(); + private static final List createdTriggers = new ArrayList<>(); private CosmosClient client; @@ -77,7 +78,7 @@ public void queryWithFilter() throws Exception { FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) - .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedDocs.stream().map(Resource::resourceId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -112,7 +113,9 @@ public void queryAll() throws Exception { options.enableCrossPartitionQuery(true); Flux> queryObservable = createdCollection.queryTriggers(query, options); - List expectedDocs = createdTriggers; + createdTriggers.forEach(cosmosTriggerSettings -> logger.info("Created trigger in method: {}", cosmosTriggerSettings.resourceId())); + + List expectedDocs = createdTriggers; int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); @@ -120,7 +123,7 @@ public void queryAll() throws Exception { .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() - .map(d -> d.resourceId()) + .map(Resource::resourceId) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() @@ -154,6 +157,7 @@ public void beforeClass() throws Exception { client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); + createdTriggers.clear(); for(int i = 0; i < 5; i++) { createdTriggers.add(createTrigger(createdCollection)); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java index 769731568cf86..d83db3e2d1421 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java @@ -28,18 +28,21 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.CosmosItemResponse; -import com.azure.data.cosmos.CosmosResponseValidator; -import com.azure.data.cosmos.Database; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.RetryAnalyzer; +import com.azure.data.cosmos.FeedResponse; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; +import reactor.test.StepVerifier; +import java.time.Duration; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import static org.apache.commons.io.FileUtils.ONE_MB; @@ -47,7 +50,6 @@ public class VeryLargeDocumentQueryTest extends TestSuiteBase { private final static int TIMEOUT = 60000; private final static int SETUP_TIMEOUT = 60000; - private Database createdDatabase; private CosmosContainer createdCollection; private CosmosClient client; @@ -57,8 +59,8 @@ public VeryLargeDocumentQueryTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } - @Test(groups = { "emulator" }, timeOut = TIMEOUT, retryAnalyzer = RetryAnalyzer.class) - public void queryLargeDocuments() throws InterruptedException { + @Test(groups = { "emulator" }, timeOut = TIMEOUT) + public void queryLargeDocuments() { int cnt = 5; @@ -69,11 +71,21 @@ public void queryLargeDocuments() throws InterruptedException { FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - validateQuerySuccess(createdCollection.queryItems("SELECT * FROM r", options), - new FeedResponseListValidator.Builder().totalSize(cnt).build()); + Flux> feedResponseFlux = createdCollection.queryItems("SELECT * FROM r", + options); + + AtomicInteger totalCount = new AtomicInteger(); + StepVerifier.create(feedResponseFlux.subscribeOn(Schedulers.single())) + .thenConsumeWhile(feedResponse -> { + int size = feedResponse.results().size(); + totalCount.addAndGet(size); + return true; + }) + .expectComplete() + .verify(Duration.ofMillis(subscriberValidationTimeout)); } - private void createLargeDocument() throws InterruptedException { + private void createLargeDocument() { CosmosItemProperties docDefinition = getDocumentDefinition(); //Keep size as ~ 1.999MB to account for size of other props @@ -82,15 +94,14 @@ private void createLargeDocument() throws InterruptedException { Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); - CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(docDefinition.id()) - .build(); - - validateSuccess(createObservable, validator); + StepVerifier.create(createObservable.subscribeOn(Schedulers.single())) + .expectNextMatches(cosmosItemResponse -> cosmosItemResponse.properties().id().equals(docDefinition.id())) + .expectComplete() + .verify(Duration.ofMillis(subscriberValidationTimeout)); } @BeforeClass(groups = { "emulator" }, timeOut = 2 * SETUP_TIMEOUT) - public void beforeClass() throws Exception { + public void beforeClass() { client = clientBuilder().build(); createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); @@ -110,8 +121,4 @@ private static CosmosItemProperties getDocumentDefinition() { , uuid, uuid)); return doc; } - - public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); - } } From 87aafe79579413a5d34cc12ef1378b0f0895dce3 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Tue, 25 Jun 2019 16:06:02 -0700 Subject: [PATCH 46/85] Hiding Json Serializable set and remove methods and object mapper and object node return types (#204) --- .../data/cosmos/benchmark/AsyncBenchmark.java | 13 +++---- .../cosmos/benchmark/AsyncMixedBenchmark.java | 13 +++---- .../cosmos/benchmark/AsyncWriteBenchmark.java | 13 +++---- .../cosmos/benchmark/ReadMyWriteWorkflow.java | 13 +++---- .../ReadMyWritesConsistencyTest.java | 5 +-- .../data/cosmos/benchmark/WorkflowTest.java | 5 +-- .../com/azure/data/cosmos/BridgeInternal.java | 8 +++++ .../azure/data/cosmos/JsonSerializable.java | 12 +++---- .../cosmos/directconnectivity/Address.java | 13 +++---- .../data/cosmos/internal/routing/Range.java | 9 ++--- .../multimaster/samples/ConflictWorker.java | 13 +++---- .../examples/CollectionCRUDAsyncAPITest.java | 5 +-- .../rx/examples/DocumentCRUDAsyncAPITest.java | 3 +- .../rx/examples/OfferCRUDAsyncAPITest.java | 5 +-- .../examples/StoredProcedureAsyncAPITest.java | 5 +-- ...ggregateDocumentQueryExecutionContext.java | 2 +- .../query/CompositeContinuationToken.java | 5 +-- .../query/OrderByContinuationToken.java | 9 ++--- .../query/PartitionedQueryExecutionInfo.java | 3 +- ...PartitionedQueryExecutionInfoInternal.java | 3 +- .../internal/query/TakeContinuationToken.java | 5 +-- .../DCDocumentCrudTest.java | 7 ++-- .../cosmos/internal/ConsistencyTests2.java | 3 +- .../cosmos/internal/ConsistencyTestsBase.java | 8 ++--- .../data/cosmos/internal/SessionTest.java | 3 +- .../data/cosmos/internal/TestSuiteBase.java | 5 +-- .../internal/query/DocumentProducerTest.java | 9 ++--- .../data/cosmos/rx/AggregateQueryTests.java | 11 +++--- .../rx/BackPressureCrossPartitionTest.java | 5 +-- .../azure/data/cosmos/rx/ChangeFeedTest.java | 4 +-- .../data/cosmos/rx/CollectionCrudTest.java | 11 +++--- .../data/cosmos/rx/DocumentCrudTest.java | 12 ++++--- .../cosmos/rx/MultiOrderByQueryTests.java | 35 ++++++++++--------- .../azure/data/cosmos/rx/TestSuiteBase.java | 5 +-- .../data/cosmos/rx/TokenResolverTest.java | 4 +-- .../azure/data/cosmos/rx/TopQueryTests.java | 9 ++--- .../cosmos/rx/VeryLargeDocumentQueryTest.java | 3 +- 37 files changed, 168 insertions(+), 128 deletions(-) diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java index a8a22a5e548b6..25bead6c5a87f 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.benchmark; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; @@ -100,12 +101,12 @@ abstract class AsyncBenchmark { String uuid = UUID.randomUUID().toString(); Document newDoc = new Document(); newDoc.id(uuid); - newDoc.set(partitionKey, uuid); - newDoc.set("dataField1", dataFieldValue); - newDoc.set("dataField2", dataFieldValue); - newDoc.set("dataField3", dataFieldValue); - newDoc.set("dataField4", dataFieldValue); - newDoc.set("dataField5", dataFieldValue); + BridgeInternal.setProperty(newDoc, partitionKey, uuid); + BridgeInternal.setProperty(newDoc, "dataField1", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField2", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField3", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField4", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField5", dataFieldValue); Flux obs = client.createDocument(collection.selfLink(), newDoc, null, false) .map(ResourceResponse::getResource); createDocumentObservables.add(obs); diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java index 21c7809f2a859..a3512b879f9ee 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.benchmark; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKey; @@ -57,12 +58,12 @@ protected void performWorkload(BaseSubscriber documentBaseSubscriber, String idString = uuid + i; Document newDoc = new Document(); newDoc.id(idString); - newDoc.set(partitionKey, idString); - newDoc.set("dataField1", dataFieldValue); - newDoc.set("dataField2", dataFieldValue); - newDoc.set("dataField3", dataFieldValue); - newDoc.set("dataField4", dataFieldValue); - newDoc.set("dataField5", dataFieldValue); + BridgeInternal.setProperty(newDoc, partitionKey, idString); + BridgeInternal.setProperty(newDoc, "dataField1", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField2", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField3", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField4", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField5", dataFieldValue); obs = client.createDocument(getCollectionLink(), newDoc, null, false).map(ResourceResponse::getResource); } else if (i % 100 == 0) { diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java index a267c6f946566..9e08fe86fa10d 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.benchmark; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.ResourceResponse; import com.codahale.metrics.Timer; @@ -82,12 +83,12 @@ protected void performWorkload(BaseSubscriber> baseSu String idString = uuid + i; Document newDoc = new Document(); newDoc.id(idString); - newDoc.set(partitionKey, idString); - newDoc.set("dataField1", dataFieldValue); - newDoc.set("dataField2", dataFieldValue); - newDoc.set("dataField3", dataFieldValue); - newDoc.set("dataField4", dataFieldValue); - newDoc.set("dataField5", dataFieldValue); + BridgeInternal.setProperty(newDoc, partitionKey, idString); + BridgeInternal.setProperty(newDoc, "dataField1", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField2", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField3", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField4", dataFieldValue); + BridgeInternal.setProperty(newDoc, "dataField5", dataFieldValue); Flux> obs = client.createDocument(getCollectionLink(), newDoc, null, false); diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java index 97144ca747ffb..f24fe611c51ed 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.benchmark; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKey; @@ -178,12 +179,12 @@ private Flux writeDocument(Integer i) { String randomVal = Utils.randomUUID().toString(); Document document = new Document(); document.id(idString); - document.set(partitionKey, idString); - document.set(QUERY_FIELD_NAME, randomVal); - document.set("dataField1", randomVal); - document.set("dataField2", randomVal); - document.set("dataField3", randomVal); - document.set("dataField4", randomVal); + BridgeInternal.setProperty(document, partitionKey, idString); + BridgeInternal.setProperty(document, QUERY_FIELD_NAME, randomVal); + BridgeInternal.setProperty(document, "dataField1", randomVal); + BridgeInternal.setProperty(document, "dataField2", randomVal); + BridgeInternal.setProperty(document, "dataField3", randomVal); + BridgeInternal.setProperty(document, "dataField4", randomVal); Integer key = i == null ? cacheKey() : i; return client.createDocument(getCollectionLink(), document, null, false) diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java index ae2f758aeffcb..fb23deca93f1f 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.benchmark; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.DataType; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; @@ -176,11 +177,11 @@ DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { includedPath.path("/*"); Collection indexes = new ArrayList<>(); Index stringIndex = Index.Range(DataType.STRING); - stringIndex.set("precision", -1); + BridgeInternal.setProperty(stringIndex, "precision", -1); indexes.add(stringIndex); Index numberIndex = Index.Range(DataType.NUMBER); - numberIndex.set("precision", -1); + BridgeInternal.setProperty(numberIndex, "precision", -1); indexes.add(numberIndex); includedPath.indexes(indexes); includedPaths.add(includedPath); diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java index 8f57b84bea21f..b1dddd6165b77 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.benchmark; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.DataType; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; @@ -328,11 +329,11 @@ DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { includedPath.path("/*"); Collection indexes = new ArrayList<>(); Index stringIndex = Index.Range(DataType.STRING); - stringIndex.set("precision", -1); + BridgeInternal.setProperty(stringIndex, "precision", -1); indexes.add(stringIndex); Index numberIndex = Index.Range(DataType.NUMBER); - numberIndex.set("precision", -1); + BridgeInternal.setProperty(numberIndex, "precision", -1); indexes.add(numberIndex); includedPath.indexes(indexes); includedPaths.add(includedPath); diff --git a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java index 6650b5a9f7a00..b4a9076e72c33 100644 --- a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java @@ -295,4 +295,12 @@ public static PartitionKeyInternal getNonePartitionKey(PartitionKeyDefinition pa public static PartitionKey getPartitionKey(PartitionKeyInternal partitionKeyInternal) { return new PartitionKey(partitionKeyInternal); } + + public static void setProperty(JsonSerializable jsonSerializable, String propertyName, T value) { + jsonSerializable.set(propertyName, value); + } + + public static void remove(JsonSerializable jsonSerializable, String propertyName) { + jsonSerializable.remove(propertyName); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java b/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java index 8beb2518625d9..c33c169e5cd14 100644 --- a/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java +++ b/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java @@ -86,7 +86,7 @@ protected JsonSerializable(String jsonString) { this.propertyBag = objectNode; } - ObjectMapper getMapper() { + private ObjectMapper getMapper() { // TODO: Made package private due to #153. #171 adding custom serialization options back. if (this.om != null) { return this.om; } return OBJECT_MAPPER; @@ -103,7 +103,7 @@ private static void checkForValidPOJO(Class c) { } } - protected Logger getLogger() { + Logger getLogger() { return logger; } @@ -134,7 +134,7 @@ public boolean has(String propertyName) { * * @param propertyName the property to remove. */ - public void remove(String propertyName) { + void remove(String propertyName) { this.propertyBag.remove(propertyName); } @@ -146,7 +146,7 @@ public void remove(String propertyName) { * @param value the value of the property. */ @SuppressWarnings({"unchecked", "rawtypes"}) - public void set(String propertyName, T value) { + void set(String propertyName, T value) { if (value == null) { // Sets null. this.propertyBag.putNull(propertyName); @@ -416,7 +416,7 @@ public Collection getCollection(String propertyName, Class c, boolean * @param propertyName the property to get. * @return the JSONObject. */ - public ObjectNode getObject(String propertyName) { + ObjectNode getObject(String propertyName) { if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) { ObjectNode jsonObj = (ObjectNode) this.propertyBag.get(propertyName); return jsonObj; @@ -430,7 +430,7 @@ public ObjectNode getObject(String propertyName) { * @param propertyName the property to get. * @return the JSONObject collection. */ - public Collection getCollection(String propertyName) { + Collection getCollection(String propertyName) { Collection result = null; if (this.propertyBag.has(propertyName) && this.propertyBag.hasNonNull(propertyName)) { result = new ArrayList(); diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Address.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Address.java index 718685fec5241..18baa1c64c32c 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Address.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Address.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.Constants; @@ -51,7 +52,7 @@ public boolean IsPrimary() { } void setIsPrimary(boolean isPrimary) { - super.set(Constants.Properties.IS_PRIMARY, isPrimary); + BridgeInternal.setProperty(this, Constants.Properties.IS_PRIMARY, isPrimary); } public String getProtocolScheme() { @@ -59,7 +60,7 @@ public String getProtocolScheme() { } void setProtocol(String protocol) { - super.set(Constants.Properties.PROTOCOL, protocol); + BridgeInternal.setProperty(this, Constants.Properties.PROTOCOL, protocol); } public String getLogicalUri() { @@ -67,7 +68,7 @@ public String getLogicalUri() { } void setLogicalUri(String logicalUri) { - super.set(Constants.Properties.LOGICAL_URI, logicalUri); + BridgeInternal.setProperty(this, Constants.Properties.LOGICAL_URI, logicalUri); } public String getPhyicalUri() { @@ -75,7 +76,7 @@ public String getPhyicalUri() { } void setPhysicalUri(String phyicalUri) { - super.set(Constants.Properties.PHYISCAL_URI, phyicalUri); + BridgeInternal.setProperty(this, Constants.Properties.PHYISCAL_URI, phyicalUri); } public String getPartitionIndex() { @@ -83,7 +84,7 @@ public String getPartitionIndex() { } void setPartitionIndex(String partitionIndex) { - super.set(Constants.Properties.PARTITION_INDEX, partitionIndex); + BridgeInternal.setProperty(this, Constants.Properties.PARTITION_INDEX, partitionIndex); } public String getParitionKeyRangeId() { @@ -91,6 +92,6 @@ public String getParitionKeyRangeId() { } public void setPartitionKeyRangeId(String partitionKeyRangeId) { - super.set(Constants.Properties.PARTITION_KEY_RANGE_ID, partitionKeyRangeId); + BridgeInternal.setProperty(this, Constants.Properties.PARTITION_KEY_RANGE_ID, partitionKeyRangeId); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java b/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java index 2a80fe6ad3399..6e074fc337874 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.internal.routing; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.JsonSerializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -89,7 +90,7 @@ public T getMin() { public void setMin(T min) { this.minValue = min; - super.set(Range.MIN_PROPERTY, min); + BridgeInternal.setProperty(this, Range.MIN_PROPERTY, min); } @SuppressWarnings("unchecked") @@ -103,7 +104,7 @@ public T getMax() { public void setMax(T max) { this.maxValue = max; - super.set(Range.MAX_PROPERTY, max); + BridgeInternal.setProperty(this, Range.MAX_PROPERTY, max); } @JsonProperty("isMinInclusive") @@ -112,7 +113,7 @@ public boolean isMinInclusive() { } public void setMinInclusive(boolean isMinInclusive) { - super.set(Range.IS_MIN_INCLUSIVE_PROPERTY, isMinInclusive); + BridgeInternal.setProperty(this, Range.IS_MIN_INCLUSIVE_PROPERTY, isMinInclusive); } @JsonProperty("isMaxInclusive") @@ -121,7 +122,7 @@ public boolean isMaxInclusive() { } public void setMaxInclusive(boolean isMaxInclusive) { - super.set(Range.IS_MAX_INCLUSIVE_PROPERTY, isMaxInclusive); + BridgeInternal.setProperty(this, Range.IS_MAX_INCLUSIVE_PROPERTY, isMaxInclusive); } public boolean isSingleValue() { diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java index bb4df7cf23990..8e0c5d26bcff3 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java @@ -26,6 +26,7 @@ import com.azure.data.cosmos.AccessCondition; import com.azure.data.cosmos.AccessConditionType; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Conflict; import com.azure.data.cosmos.ConflictResolutionPolicy; import com.azure.data.cosmos.CosmosClientException; @@ -498,8 +499,8 @@ public void runDeleteConflictOnUdp() throws Exception { private Flux tryInsertDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { logger.debug("region: {}", client.getWriteEndpoint()); - document.set("regionId", index); - document.set("regionEndpoint", client.getReadEndpoint()); + BridgeInternal.setProperty(document, "regionId", index); + BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); return client.createDocument(collectionUri, document, null, false) .onErrorResume(e -> { if (hasDocumentClientException(e, 409)) { @@ -544,8 +545,8 @@ private boolean hasDocumentClientExceptionCause(Throwable e, int statusCode) { } private Flux tryUpdateDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { - document.set("regionId", index); - document.set("regionEndpoint", client.getReadEndpoint()); + BridgeInternal.setProperty(document, "regionId", index); + BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); RequestOptions options = new RequestOptions(); options.setAccessCondition(new AccessCondition()); @@ -566,8 +567,8 @@ private Flux tryUpdateDocument(AsyncDocumentClient client, String coll } private Flux tryDeleteDocument(AsyncDocumentClient client, String collectionUri, Document document, int index) { - document.set("regionId", index); - document.set("regionEndpoint", client.getReadEndpoint()); + BridgeInternal.setProperty(document, "regionId", index); + BridgeInternal.setProperty(document, "regionEndpoint", client.getReadEndpoint()); RequestOptions options = new RequestOptions(); options.setAccessCondition(new AccessCondition()); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java index 05ad28422139e..afbb7fc319ef0 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.rx.examples; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; @@ -398,11 +399,11 @@ private DocumentCollection getMultiPartitionCollectionDefinition() { includedPath.path("/*"); Collection indexes = new ArrayList<>(); Index stringIndex = Index.Range(DataType.STRING); - stringIndex.set("precision", -1); + BridgeInternal.setProperty(stringIndex, "precision", -1); indexes.add(stringIndex); Index numberIndex = Index.Range(DataType.NUMBER); - numberIndex.set("precision", -1); + BridgeInternal.setProperty(numberIndex, "precision", -1); indexes.add(numberIndex); includedPath.indexes(indexes); includedPaths.add(includedPath); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java index 29ca7655d1b81..41c373439442e 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.rx.examples; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; @@ -217,7 +218,7 @@ public void createDocument_toBlocking() { public void createDocumentWithProgrammableDocumentDefinition() throws Exception { Document documentDefinition = new Document(); documentDefinition.id("test-document"); - documentDefinition.set("counter", 1); + BridgeInternal.setProperty(documentDefinition, "counter", 1); // CREATE a document Document createdDocument = client diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java index 8572869e0399b..6efe0b1b9df83 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.rx.examples; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; @@ -160,11 +161,11 @@ private DocumentCollection getMultiPartitionCollectionDefinition() { includedPath.path("/*"); Collection indexes = new ArrayList<>(); Index stringIndex = Index.Range(DataType.STRING); - stringIndex.set("precision", -1); + BridgeInternal.setProperty(stringIndex, "precision", -1); indexes.add(stringIndex); Index numberIndex = Index.Range(DataType.NUMBER); - numberIndex.set("precision", -1); + BridgeInternal.setProperty(numberIndex, "precision", -1); indexes.add(numberIndex); includedPath.indexes(indexes); includedPaths.add(includedPath); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java index 09a9aef2772d7..53b98fb4cefb9 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.rx.examples; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; @@ -250,11 +251,11 @@ private static DocumentCollection getMultiPartitionCollectionDefinition() { includedPath.path("/*"); Collection indexes = new ArrayList(); Index stringIndex = Index.Range(DataType.STRING); - stringIndex.set("precision", -1); + BridgeInternal.setProperty(stringIndex, "precision", -1); indexes.add(stringIndex); Index numberIndex = Index.Range(DataType.NUMBER); - numberIndex.set("precision", -1); + BridgeInternal.setProperty(numberIndex, "precision", -1); indexes.add(numberIndex); includedPath.indexes(indexes); includedPaths.add(includedPath); diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java index af0c75f888cc5..c5ce551dc29d4 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java @@ -118,7 +118,7 @@ public Flux> drainAsync(int maxPageSize) { if (this.aggregator.getResult() == null || !this.aggregator.getResult().equals(Undefined.Value())) { Document aggregateDocument = new Document(); - aggregateDocument.set(Constants.Properties.AGGREGATE, this.aggregator.getResult()); + BridgeInternal.setProperty(aggregateDocument, Constants.Properties.AGGREGATE, this.aggregator.getResult()); aggregateResults.add(aggregateDocument); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java index 27e8ed69d592c..c7c8f64d2b0d9 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.internal.query; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.routing.Range; @@ -105,7 +106,7 @@ public Range getRange() { * the token to set */ private void setToken(String token) { - super.set(TokenPropertyName, token); + BridgeInternal.setProperty(this, TokenPropertyName, token); } /** @@ -114,6 +115,6 @@ private void setToken(String token) { */ private void setRange(Range range) { /* TODO: Don't stringify the range */ - super.set(RangePropertyName, range.toString()); + BridgeInternal.setProperty(this, RangePropertyName, range.toString()); } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java index 5928d5fa0cd6b..64993e10cece8 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.internal.query; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.fasterxml.jackson.databind.JsonNode; @@ -135,18 +136,18 @@ public boolean getInclusive() { } private void setCompositeContinuationToken(CompositeContinuationToken compositeContinuationToken) { - super.set(CompositeContinuationTokenPropertyName, compositeContinuationToken.toJson()); + BridgeInternal.setProperty(this, CompositeContinuationTokenPropertyName, compositeContinuationToken.toJson()); } private void setOrderByItems(QueryItem[] orderByItems) { - super.set(OrderByItemsPropetryName, orderByItems); + BridgeInternal.setProperty(this, OrderByItemsPropetryName, orderByItems); } private void setRid(String rid) { - super.set(RidPropertyName, rid); + BridgeInternal.setProperty(this, RidPropertyName, rid); } private void setInclusive(boolean inclusive) { - super.set(InclusivePropertyName, inclusive); + BridgeInternal.setProperty(this, InclusivePropertyName, inclusive); } } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java index 0052d917d6582..cdf64044c4140 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.internal.query; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.routing.Range; @@ -44,7 +45,7 @@ public final class PartitionedQueryExecutionInfo extends JsonSerializable { this.queryInfo = queryInfo; this.queryRanges = queryRanges; - super.set( + BridgeInternal.setProperty(this, PartitionedQueryExecutionInfoInternal.PARTITIONED_QUERY_EXECUTION_INFO_VERSION_PROPERTY, Constants.PartitionedQueryExecutionInfo.VERSION_1); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java index 3fd872b9607fb..64b0061044c8d 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.internal.query; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.Utils; @@ -45,7 +46,7 @@ public final class PartitionedQueryExecutionInfoInternal extends JsonSerializabl private List> queryRanges; public PartitionedQueryExecutionInfoInternal() { - super.set(PARTITIONED_QUERY_EXECUTION_INFO_VERSION_PROPERTY, Constants.PartitionedQueryExecutionInfo.VERSION_1); + BridgeInternal.setProperty(this, PARTITIONED_QUERY_EXECUTION_INFO_VERSION_PROPERTY, Constants.PartitionedQueryExecutionInfo.VERSION_1); } public PartitionedQueryExecutionInfoInternal(String jsonString) { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java index c0922f0d454a6..37562f903246a 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.internal.query; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.internal.Utils.ValueHolder; import org.slf4j.Logger; @@ -82,10 +83,10 @@ public String getSourceToken() { } private void setTakeCount(int takeCount) { - super.set(LimitPropertyName, takeCount); + BridgeInternal.setProperty(this, LimitPropertyName, takeCount); } private void setSourceToken(String sourceToken) { - super.set(SourceTokenPropetryName, sourceToken); + BridgeInternal.setProperty(this, SourceTokenPropetryName, sourceToken); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java index fb27309978719..619dc39a8fe05 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; @@ -208,7 +209,7 @@ public void upsert() throws Exception { String propName = "newProp"; String propValue = "hello"; - document.set(propName, propValue); + BridgeInternal.setProperty(document, propName, propValue); ResourceResponseValidator validator = ResourceResponseValidator.builder() .withProperty(propName, propValue) @@ -331,8 +332,8 @@ private String getCollectionLink() { private Document getDocumentDefinition() { Document doc = new Document(); doc.id(UUID.randomUUID().toString()); - doc.set(PARTITION_KEY_FIELD_NAME, UUID.randomUUID().toString()); - doc.set("name", "Hafez"); + BridgeInternal.setProperty(doc, PARTITION_KEY_FIELD_NAME, UUID.randomUUID().toString()); + BridgeInternal.setProperty(doc, "name", "Hafez"); return doc; } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java index f472bed820437..a021a53055da7 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; @@ -237,7 +238,7 @@ public void validateSessionTokenAsync() { List documents = new ArrayList<>(); for (int i = 0; i < 1000; i++) { Document documentDefinition = getDocumentDefinition(); - documentDefinition.set(UUID.randomUUID().toString(), UUID.randomUUID().toString()); + BridgeInternal.setProperty(documentDefinition, UUID.randomUUID().toString(), UUID.randomUUID().toString()); documents.add(documentDefinition); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java index a54430f7d4f5c..a484d2d21e390 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java @@ -230,7 +230,7 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { { Document document2 = new Document(); document2.id("test" + UUID.randomUUID().toString()); - document2.set("customerid", 2); + BridgeInternal.setProperty(document2, "customerid", 2); // name link ResourceResponse document = writeClient.createDocument(BridgeInternal.getAltLink(coll), document2, null, false) @@ -244,7 +244,7 @@ void validateSessionContainerAfterCollectionCreateReplace(boolean useGateway) { { Document document2 = new Document(); document2.id("test" + UUID.randomUUID().toString()); - document2.set("customerid", 3); + BridgeInternal.setProperty(document2, "customerid", 3); // name link ResourceResponse document = writeClient.createDocument(BridgeInternal.getAltLink(coll), document2, null, false) @@ -689,7 +689,7 @@ void validateSessionTokenMultiPartitionCollection(boolean useGateway) throws Exc // Document to lock pause/resume clients Document document1 = new Document(); document1.id("test" + UUID.randomUUID().toString()); - document1.set("mypk", 1); + BridgeInternal.setProperty(document1, "mypk", 1); ResourceResponse childResource1 = writeClient.createDocument(createdCollection.selfLink(), document1, null, true).blockFirst(); logger.info("Created {} child resource", childResource1.getResource().resourceId()); assertThat(childResource1.getSessionToken()).isNotNull(); @@ -700,7 +700,7 @@ void validateSessionTokenMultiPartitionCollection(boolean useGateway) throws Exc // Document to lock pause/resume clients Document document2 = new Document(); document2.id("test" + UUID.randomUUID().toString()); - document2.set("mypk", 2); + BridgeInternal.setProperty(document2, "mypk", 2); ResourceResponse childResource2 = writeClient.createDocument(createdCollection.selfLink(), document2, null, true).blockFirst(); assertThat(childResource2.getSessionToken()).isNotNull(); assertThat(childResource2.getSessionToken().contains(":")).isTrue(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java index cc0efac77bc01..52db5a19d3c44 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; @@ -154,7 +155,7 @@ public void sessionConsistency_ReadYourWrites(boolean isNameBased) { public void sessionTokenInDocumentRead(boolean isNameBased) throws UnsupportedEncodingException { Document document = new Document(); document.id(UUID.randomUUID().toString()); - document.set("pk", "pk"); + BridgeInternal.setProperty(document, "pk", "pk"); document = spyClient.createDocument(getCollectionLink(isNameBased), document, null, false) .blockFirst() .getResource(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index 3cf4df21c8c0f..2190e5e7cc18d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -24,6 +24,7 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.CompositePathSortOrder; import com.azure.data.cosmos.ConnectionMode; @@ -512,11 +513,11 @@ static protected DocumentCollection getCollectionDefinitionWithRangeRangeIndex() includedPath.path("/*"); Collection indexes = new ArrayList<>(); Index stringIndex = Index.Range(DataType.STRING); - stringIndex.set("precision", -1); + BridgeInternal.setProperty(stringIndex, "precision", -1); indexes.add(stringIndex); Index numberIndex = Index.Range(DataType.NUMBER); - numberIndex.set("precision", -1); + BridgeInternal.setProperty(numberIndex, "precision", -1); indexes.add(numberIndex); includedPath.indexes(indexes); includedPaths.add(includedPath); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java index ca84a0fb8f4aa..2e96da81b22ff 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.internal.query; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Document; @@ -485,12 +486,12 @@ private List> mockFeedResponsesPartiallySorted(String par Document d = getDocumentDefinition(); if (isOrderby) { - d.set(OrderByIntFieldName, orderByFieldInitialVal + RandomUtils.nextInt(0, 3)); - d.set(DocumentPartitionKeyRangeIdFieldName, partitionKeyRangeId); + BridgeInternal.setProperty(d, OrderByIntFieldName, orderByFieldInitialVal + RandomUtils.nextInt(0, 3)); + BridgeInternal.setProperty(d, DocumentPartitionKeyRangeIdFieldName, partitionKeyRangeId); PartitionKeyRange pkr = mockPartitionKeyRange(partitionKeyRangeId); - d.set(DocumentPartitionKeyRangeMinInclusiveFieldName, pkr.getMinInclusive()); - d.set(DocumentPartitionKeyRangeMaxExclusiveFieldName, pkr.getMaxExclusive()); + BridgeInternal.setProperty(d, DocumentPartitionKeyRangeMinInclusiveFieldName, pkr.getMinInclusive()); + BridgeInternal.setProperty(d, DocumentPartitionKeyRangeMaxExclusiveFieldName, pkr.getMaxExclusive()); QueryItem qi = new QueryItem("{ \"item\": " + Integer.toString(d.getInt(OrderByIntFieldName)) + " }"); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java index 21d529771076f..934bb0abef8fc 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; @@ -116,15 +117,15 @@ public void generateTestData() { for (int i = 0; i < values.length; i++) { CosmosItemProperties d = new CosmosItemProperties(); d.id(UUID.randomUUID().toString()); - d.set(partitionKey, values[i]); + BridgeInternal.setProperty(d, partitionKey, values[i]); docs.add(d); } for (int i = 0; i < numberOfDocsWithSamePartitionKey; i++) { CosmosItemProperties d = new CosmosItemProperties(); - d.set(partitionKey, uniquePartitionKey); - d.set("resourceId", Integer.toString(i)); - d.set(field, i + 1); + BridgeInternal.setProperty(d, partitionKey, uniquePartitionKey); + BridgeInternal.setProperty(d, "resourceId", Integer.toString(i)); + BridgeInternal.setProperty(d, field, i + 1); d.id(UUID.randomUUID().toString()); docs.add(d); } @@ -132,7 +133,7 @@ public void generateTestData() { numberOfDocumentsWithNumericId = numberOfDocuments - values.length - numberOfDocsWithSamePartitionKey; for (int i = 0; i < numberOfDocumentsWithNumericId; i++) { CosmosItemProperties d = new CosmosItemProperties(); - d.set(partitionKey, i + 1); + BridgeInternal.setProperty(d, partitionKey, i + 1); d.id(UUID.randomUUID().toString()); docs.add(d); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java index 8ae7dfb3d54d3..7a15af63df499 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ClientUnderTestBuilder; import com.azure.data.cosmos.CosmosBridgeInternal; import com.azure.data.cosmos.CosmosClient; @@ -89,11 +90,11 @@ static protected CosmosContainerSettings getCollectionDefinition() { includedPath.path("/*"); Collection indexes = new ArrayList<>(); Index stringIndex = Index.Range(DataType.STRING); - stringIndex.set("precision", -1); + BridgeInternal.setProperty(stringIndex, "precision", -1); indexes.add(stringIndex); Index numberIndex = Index.Range(DataType.NUMBER); - numberIndex.set("precision", -1); + BridgeInternal.setProperty(numberIndex, "precision", -1); indexes.add(numberIndex); includedPath.indexes(indexes); includedPaths.add(includedPath); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java index 4921e5fca1260..3f473eafe03c1 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java @@ -300,8 +300,8 @@ private static Document getDocumentDefinition(String partitionKey) { String uuid = UUID.randomUUID().toString(); Document doc = new Document(); doc.id(uuid); - doc.set("mypk", partitionKey); - doc.set("prop", uuid); + BridgeInternal.setProperty(doc, "mypk", partitionKey); + BridgeInternal.setProperty(doc, "prop", uuid); return doc; } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java index ace4d5c9b7dcd..45fa411048c6f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.CompositePathSortOrder; import com.azure.data.cosmos.CosmosClient; @@ -278,8 +279,8 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { CosmosItemProperties document = new CosmosItemProperties(); document.id("doc"); - document.set("name", "New Document"); - document.set("mypk", "mypkValue"); + BridgeInternal.setProperty(document, "name", "New Document"); + BridgeInternal.setProperty(document, "mypk", "mypkValue"); CosmosItem item = createDocument(collection, document); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.partitionKey(new PartitionKey("mypkValue")); @@ -287,7 +288,7 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { logger.info("Client 1 READ Document Client Side Request Statistics {}", readDocumentResponse.requestDiagnosticsString()); logger.info("Client 1 READ Document Latency {}", readDocumentResponse.requestLatency()); - document.set("name", "New Updated Document"); + BridgeInternal.setProperty(document, "name", "New Updated Document"); CosmosItemResponse upsertDocumentResponse = collection.upsertItem(document).block(); logger.info("Client 1 Upsert Document Client Side Request Statistics {}", upsertDocumentResponse.requestDiagnosticsString()); logger.info("Client 1 Upsert Document Latency {}", upsertDocumentResponse.requestLatency()); @@ -299,8 +300,8 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { CosmosItemProperties newDocument = new CosmosItemProperties(); newDocument.id("doc"); - newDocument.set("name", "New Created Document"); - newDocument.set("mypk", "mypk"); + BridgeInternal.setProperty(newDocument, "name", "New Created Document"); + BridgeInternal.setProperty(newDocument, "mypk", "mypk"); createDocument(collection2, newDocument); readDocumentResponse = client1.getDatabase(dbId).getContainer(collectionId).getItem(newDocument.id(), newDocument.get("mypk")).read().block(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java index 11c3a09b738e0..b8a32cd2980f8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; @@ -39,6 +40,7 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; import reactor.core.publisher.Mono; +import sun.corba.Bridge; import java.time.Duration; import java.time.OffsetDateTime; @@ -87,7 +89,7 @@ public void createLargeDocument(String documentId) throws InterruptedException { //Keep size as ~ 1.5MB to account for size of other props int size = (int) (ONE_MB * 1.5); - docDefinition.set("largeString", StringUtils.repeat("x", size)); + BridgeInternal.setProperty(docDefinition, "largeString", StringUtils.repeat("x", size)); Mono createObservable = container.createItem(docDefinition, new CosmosItemRequestOptions()); @@ -105,7 +107,7 @@ public void createDocumentWithVeryLargePartitionKey(String documentId) throws In for(int i = 0; i < 100; i++) { sb.append(i).append("x"); } - docDefinition.set("mypk", sb.toString()); + BridgeInternal.setProperty(docDefinition, "mypk", sb.toString()); Mono createObservable = container.createItem(docDefinition, new CosmosItemRequestOptions()); @@ -123,7 +125,7 @@ public void readDocumentWithVeryLargePartitionKey(String documentId) throws Inte for(int i = 0; i < 100; i++) { sb.append(i).append("x"); } - docDefinition.set("mypk", sb.toString()); + BridgeInternal.setProperty(docDefinition, "mypk", sb.toString()); CosmosItem createdDocument = TestSuiteBase.createDocument(container, docDefinition); @@ -286,7 +288,7 @@ public void replaceDocument(String documentId) throws InterruptedException { CosmosItem document = container.createItem(docDefinition, new CosmosItemRequestOptions()).block().item(); String newPropValue = UUID.randomUUID().toString(); - docDefinition.set("newProp", newPropValue); + BridgeInternal.setProperty(docDefinition, "newProp", newPropValue); CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.partitionKey(new PartitionKey(docDefinition.get("mypk"))); @@ -322,7 +324,7 @@ public void upsertDocument_ReplaceDocument(String documentId) throws Throwable { properties = container.createItem(properties, new CosmosItemRequestOptions()).block().properties(); String newPropValue = UUID.randomUUID().toString(); - properties.set("newProp", newPropValue); + BridgeInternal.setProperty(properties, "newProp", newPropValue); // Replace document diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java index 744e3c5d9b718..3e8df4deff1d7 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.CompositePathSortOrder; import com.azure.data.cosmos.CosmosClient; @@ -157,23 +158,23 @@ public void beforeClass() throws Exception { // Permute all the fields so that there are duplicates with tie breaks CosmosItemProperties numberClone = new CosmosItemProperties(multiOrderByDocumentString); - numberClone.set(NUMBER_FIELD, random.nextInt(5)); + BridgeInternal.setProperty(numberClone, NUMBER_FIELD, random.nextInt(5)); numberClone.id(UUID.randomUUID().toString()); this.documents.add(numberClone); CosmosItemProperties stringClone = new CosmosItemProperties(multiOrderByDocumentString); - stringClone.set(STRING_FIELD, Integer.toString(random.nextInt(5))); + BridgeInternal.setProperty(stringClone, STRING_FIELD, Integer.toString(random.nextInt(5))); stringClone.id(UUID.randomUUID().toString()); this.documents.add(stringClone); CosmosItemProperties boolClone = new CosmosItemProperties(multiOrderByDocumentString); - boolClone.set(BOOL_FIELD, random.nextInt(2) % 2 == 0); + BridgeInternal.setProperty(boolClone, BOOL_FIELD, random.nextInt(2) % 2 == 0); boolClone.id(UUID.randomUUID().toString()); this.documents.add(boolClone); // Also fuzz what partition it goes to CosmosItemProperties partitionClone = new CosmosItemProperties(multiOrderByDocumentString); - partitionClone.set(PARTITION_KEY, random.nextInt(5)); + BridgeInternal.setProperty(partitionClone, PARTITION_KEY, random.nextInt(5)); partitionClone.id(UUID.randomUUID().toString()); this.documents.add(partitionClone); } @@ -188,18 +189,18 @@ private CosmosItemProperties generateMultiOrderByDocument() { Random random = new Random(); CosmosItemProperties document = new CosmosItemProperties(); document.id(UUID.randomUUID().toString()); - document.set(NUMBER_FIELD, random.nextInt(5)); - document.set(NUMBER_FIELD_2, random.nextInt(5)); - document.set(BOOL_FIELD, (random.nextInt() % 2) == 0); - document.set(STRING_FIELD, Integer.toString(random.nextInt(5))); - document.set(STRING_FIELD_2, Integer.toString(random.nextInt(5))); - document.set(NULL_FIELD, null); - document.set(OBJECT_FIELD, ""); - document.set(ARRAY_FIELD, (new ObjectMapper()).createArrayNode()); - document.set(SHORT_STRING_FIELD, "a" + random.nextInt(100)); - document.set(MEDIUM_STRING_FIELD, "a" + random.nextInt(128) + 100); - document.set(LONG_STRING_FIELD, "a" + random.nextInt(255) + 128); - document.set(PARTITION_KEY, random.nextInt(5)); + BridgeInternal.setProperty(document, NUMBER_FIELD, random.nextInt(5)); + BridgeInternal.setProperty(document, NUMBER_FIELD_2, random.nextInt(5)); + BridgeInternal.setProperty(document, BOOL_FIELD, (random.nextInt() % 2) == 0); + BridgeInternal.setProperty(document, STRING_FIELD, Integer.toString(random.nextInt(5))); + BridgeInternal.setProperty(document, STRING_FIELD_2, Integer.toString(random.nextInt(5))); + BridgeInternal.setProperty(document, NULL_FIELD, null); + BridgeInternal.setProperty(document, OBJECT_FIELD, ""); + BridgeInternal.setProperty(document, ARRAY_FIELD, (new ObjectMapper()).createArrayNode()); + BridgeInternal.setProperty(document, SHORT_STRING_FIELD, "a" + random.nextInt(100)); + BridgeInternal.setProperty(document, MEDIUM_STRING_FIELD, "a" + random.nextInt(128) + 100); + BridgeInternal.setProperty(document, LONG_STRING_FIELD, "a" + random.nextInt(255) + 128); + BridgeInternal.setProperty(document, PARTITION_KEY, random.nextInt(5)); return document; } @@ -278,7 +279,7 @@ public void queryDocumentsWithMultiOrder() throws CosmosClientException, Interru // CREATE document with numberField not set. // This query would then be invalid. CosmosItemProperties documentWithEmptyField = generateMultiOrderByDocument(); - documentWithEmptyField.remove(NUMBER_FIELD); + BridgeInternal.remove(documentWithEmptyField, NUMBER_FIELD); documentCollection.createItem(documentWithEmptyField, new CosmosItemRequestOptions()).block(); String query = "SELECT [root." + NUMBER_FIELD + ",root." + STRING_FIELD + "] FROM root ORDER BY root." + NUMBER_FIELD + " ASC ,root." + STRING_FIELD + " DESC"; Flux> queryObservable = documentCollection.queryItems(query, feedOptions); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index 1a9e52beb4e33..e9bf59a68bff3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.CompositePathSortOrder; import com.azure.data.cosmos.ConnectionMode; @@ -512,11 +513,11 @@ static protected CosmosContainerSettings getCollectionDefinitionWithRangeRangeIn includedPath.path("/*"); Collection indexes = new ArrayList<>(); Index stringIndex = Index.Range(DataType.STRING); - stringIndex.set("precision", -1); + BridgeInternal.setProperty(stringIndex, "precision", -1); indexes.add(stringIndex); Index numberIndex = Index.Range(DataType.NUMBER); - numberIndex.set("precision", -1); + BridgeInternal.setProperty(numberIndex, "precision", -1); indexes.add(numberIndex); includedPath.indexes(indexes); includedPaths.add(includedPath); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java index fca092e56c44c..ce34953600b2a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java @@ -381,10 +381,10 @@ public void readChangeFeedWithAllPermission(ConnectionMode connectionMode) throw String partitionKeyValue = "pk"; Document document1 = new Document(); document1.id(id1); - document1.set(partitionKey, partitionKeyValue); + BridgeInternal.setProperty(document1, partitionKey, partitionKeyValue); Document document2 = new Document(); document2.id(id2); - document2.set(partitionKey, partitionKeyValue); + BridgeInternal.setProperty(document2, partitionKey, partitionKeyValue); try { asyncClientWithTokenResolver = buildClient(connectionMode, PermissionMode.ALL); OffsetDateTime befTime = OffsetDateTime.now(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java index b8db0be7977ec..81acc28ad5b60 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; @@ -195,16 +196,16 @@ public void generateTestData() { for (int i = 0; i < 10; i++) { CosmosItemProperties d = new CosmosItemProperties(); d.id(Integer.toString(i)); - d.set(field, i); - d.set(partitionKey, firstPk); + BridgeInternal.setProperty(d, field, i); + BridgeInternal.setProperty(d, partitionKey, firstPk); docs.add(d); } for (int i = 10; i < 20; i++) { CosmosItemProperties d = new CosmosItemProperties(); d.id(Integer.toString(i)); - d.set(field, i); - d.set(partitionKey, secondPk); + BridgeInternal.setProperty(d, field, i); + BridgeInternal.setProperty(d, partitionKey, secondPk); docs.add(d); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java index d83db3e2d1421..5e69089374d64 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; @@ -90,7 +91,7 @@ private void createLargeDocument() { //Keep size as ~ 1.999MB to account for size of other props int size = (int) (ONE_MB * 1.999); - docDefinition.set("largeString", StringUtils.repeat("x", size)); + BridgeInternal.setProperty(docDefinition, "largeString", StringUtils.repeat("x", size)); Mono createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); From e720b844eb6a5ec24b25702eba171700688178f5 Mon Sep 17 00:00:00 2001 From: Milis Date: Tue, 25 Jun 2019 16:43:39 -0700 Subject: [PATCH 47/85] Refactor Change Feed surface area (#199) * Add test case for change feed processor. The test creates a bunch of documents and compare them with what change feed processor receives. Fix couple bugs in the implementation of change feed processor including an issue related to continuation tokens which were previously not correctly retrieved. * Cleanup public interfaces (remove "with") and other tweaks. * Move ChangeFeedProcessor implementation inside "internal". Only two public interfaces/classes are exposed to the users, ChangeFeedProcessor and ChangeFeedProcessorOptions. * Update CFP Builder interface to accept a Consumer for handling the feed changes. * Remove CheckpointFrequency setting from the user facing public APIs. * Remove blocking calls from ChangeFeedProcessorBuilderImpl implementation * Fix documentation capture. * Cleanup/fixes for Mono.error() calls. Renamings/refactoring. * Test cleanup; add extra coverage for ChangeFeedProcessorOptions argument. * Test fix * Change feed test refactoring. Disable resourceLeak() test that it causes runs to timeout * increase the "AfterMethod" timeout. * Refactor test assets. Add test case for ChangeFeedProcessorOptions "startTime" option. * Increase timeouts; move map initialization inside the test. * Rename syncHandleChanges to handleChanges. Return an actual instance of the ChangeFeedProcessor rather than a Reactor Mono. Some initialization code will need to be moved to from builder to start of the processing in a later check-in. * cleanup * Updates * Fix for release of a lease. * switch to publishing on a different scheduler to avoid blocking on netty threads. --- .../ChangeFeed/SampleChangeFeedProcessor.java | 37 ++- .../data/cosmos/ChangeFeedProcessor.java | 51 +-- .../cosmos/ChangeFeedProcessorOptions.java | 48 +-- .../com/azure/data/cosmos/CosmosConflict.java | 7 +- .../azure/data/cosmos/CosmosContainer.java | 4 +- .../changefeed/ContainerConnectionInfo.java | 186 ----------- .../DocumentServiceLeaseUpdaterImpl.java | 152 --------- .../internal/PartitionSupervisorImpl.java | 168 ---------- .../changefeed/Bootstrapper.java | 2 +- .../changefeed/CancellationToken.java | 2 +- .../changefeed/CancellationTokenSource.java | 2 +- .../changefeed/ChangeFeedContextClient.java | 2 +- .../changefeed}/ChangeFeedObserver.java | 4 +- .../ChangeFeedObserverCloseReason.java | 2 +- .../ChangeFeedObserverContext.java | 4 +- .../ChangeFeedObserverFactory.java | 2 +- .../changefeed/CheckpointFrequency.java | 2 +- .../changefeed/HealthMonitor.java | 2 +- .../changefeed/HealthMonitoringRecord.java | 2 +- .../{ => internal}/changefeed/Lease.java | 2 +- .../changefeed/LeaseCheckpointer.java | 2 +- .../changefeed/LeaseContainer.java | 2 +- .../changefeed/LeaseManager.java | 4 +- .../changefeed/LeaseRenewer.java | 2 +- .../{ => internal}/changefeed/LeaseStore.java | 2 +- .../changefeed/LeaseStoreManager.java | 14 +- .../changefeed/LeaseStoreManagerSettings.java | 2 +- .../changefeed/PartitionCheckpointer.java | 2 +- .../changefeed/PartitionController.java | 2 +- .../changefeed/PartitionLoadBalancer.java | 2 +- .../PartitionLoadBalancingStrategy.java | 2 +- .../changefeed/PartitionManager.java | 2 +- .../changefeed/PartitionProcessor.java | 4 +- .../changefeed/PartitionProcessorFactory.java | 4 +- .../changefeed/PartitionSupervisor.java | 2 +- .../PartitionSupervisorFactory.java | 2 +- .../changefeed/PartitionSynchronizer.java | 2 +- .../changefeed/ProcessorSettings.java | 2 +- .../changefeed/RemainingPartitionWork.java | 2 +- .../changefeed/RemainingWorkEstimator.java | 6 +- .../changefeed/RequestOptionsFactory.java | 2 +- .../changefeed/ServiceItemLease.java | 5 +- .../changefeed/ServiceItemLeaseUpdater.java | 2 +- .../exceptions/LeaseLostException.java | 4 +- .../exceptions/ObserverException.java | 2 +- .../exceptions/PartitionException.java | 2 +- .../PartitionNotFoundException.java | 2 +- .../exceptions/PartitionSplitException.java | 2 +- .../exceptions/TaskCancelledException.java | 2 +- .../implementation}/AutoCheckpointer.java | 12 +- .../implementation}/BootstrapperImpl.java | 10 +- .../ChangeFeedContextClientImpl.java | 32 +- .../implementation}/ChangeFeedHelper.java | 32 +- .../ChangeFeedObserverContextImpl.java | 8 +- .../ChangeFeedObserverFactoryImpl.java | 8 +- .../ChangeFeedProcessorBuilderImpl.java | 133 ++++---- .../CheckpointerObserverFactory.java | 10 +- .../changefeed/implementation}/Constants.java | 4 +- .../implementation/DefaultObserver.java | 37 ++- .../DefaultObserverFactory.java | 47 +++ .../DocumentServiceLeaseStore.java | 27 +- .../DocumentServiceLeaseUpdaterImpl.java | 204 ++++++++++++ .../EqualPartitionsBalancingStrategy.java | 8 +- .../implementation}/ExceptionClassifier.java | 4 +- ...onitoringPartitionControllerDecorator.java | 12 +- .../implementation}/LeaseRenewerImpl.java | 14 +- .../LeaseStoreManagerImpl.java | 100 +++--- ...onWrappingChangeFeedObserverDecorator.java | 12 +- .../PartitionCheckpointerImpl.java | 10 +- .../PartitionControllerImpl.java | 77 ++--- .../PartitionLoadBalancerImpl.java | 26 +- .../implementation}/PartitionManagerImpl.java | 20 +- .../PartitionProcessorFactoryImpl.java | 20 +- .../PartitionProcessorImpl.java | 24 +- .../PartitionSupervisorFactoryImpl.java | 22 +- .../PartitionSupervisorImpl.java | 167 ++++++++++ .../PartitionSynchronizerImpl.java | 14 +- ...edByIdCollectionRequestOptionsFactory.java | 8 +- .../RemainingPartitionWorkImpl.java | 6 +- .../RemainingWorkEstimatorImpl.java | 18 +- .../implementation}/StatusCodeErrorType.java | 4 +- .../implementation}/TraceHealthMonitor.java | 8 +- .../implementation}/WorkerTask.java | 25 +- .../cosmos/rx/ChangeFeedProcessorTest.java | 305 ++++++++++++++++++ 84 files changed, 1205 insertions(+), 1029 deletions(-) delete mode 100644 sdk/src/main/java/com/azure/data/cosmos/changefeed/ContainerConnectionInfo.java delete mode 100644 sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java delete mode 100644 sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/Bootstrapper.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/CancellationToken.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/CancellationTokenSource.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/ChangeFeedContextClient.java (99%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal/changefeed}/ChangeFeedObserver.java (95%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal/changefeed}/ChangeFeedObserverCloseReason.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal/changefeed}/ChangeFeedObserverContext.java (93%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal/changefeed}/ChangeFeedObserverFactory.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/CheckpointFrequency.java (98%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/HealthMonitor.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/HealthMonitoringRecord.java (98%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/Lease.java (98%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/LeaseCheckpointer.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/LeaseContainer.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/LeaseManager.java (95%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/LeaseRenewer.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/LeaseStore.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/LeaseStoreManager.java (88%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/LeaseStoreManagerSettings.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/PartitionCheckpointer.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/PartitionController.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/PartitionLoadBalancer.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/PartitionLoadBalancingStrategy.java (98%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/PartitionManager.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/PartitionProcessor.java (93%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/PartitionProcessorFactory.java (94%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/PartitionSupervisor.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/PartitionSupervisorFactory.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/PartitionSynchronizer.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/ProcessorSettings.java (98%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/RemainingPartitionWork.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/RemainingWorkEstimator.java (92%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/RequestOptionsFactory.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/ServiceItemLease.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/ServiceItemLeaseUpdater.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/exceptions/LeaseLostException.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/exceptions/ObserverException.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/exceptions/PartitionException.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/exceptions/PartitionNotFoundException.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/exceptions/PartitionSplitException.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/changefeed/exceptions/TaskCancelledException.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/AutoCheckpointer.java (88%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/BootstrapperImpl.java (92%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/ChangeFeedContextClientImpl.java (87%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/ChangeFeedHelper.java (82%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/ChangeFeedObserverContextImpl.java (91%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/ChangeFeedObserverFactoryImpl.java (85%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/ChangeFeedProcessorBuilderImpl.java (78%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/CheckpointerObserverFactory.java (87%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/Constants.java (99%) rename examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java => sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserver.java (59%) create mode 100644 sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserverFactory.java rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/DocumentServiceLeaseStore.java (89%) create mode 100644 sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseUpdaterImpl.java rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/EqualPartitionsBalancingStrategy.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/ExceptionClassifier.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/HealthMonitoringPartitionControllerDecorator.java (85%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/LeaseRenewerImpl.java (91%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/LeaseStoreManagerImpl.java (79%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/ObserverExceptionWrappingChangeFeedObserverDecorator.java (85%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/PartitionCheckpointerImpl.java (86%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/PartitionControllerImpl.java (71%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/PartitionLoadBalancerImpl.java (87%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/PartitionManagerImpl.java (76%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/PartitionProcessorFactoryImpl.java (84%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/PartitionProcessorImpl.java (90%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/PartitionSupervisorFactoryImpl.java (80%) create mode 100644 sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/PartitionSynchronizerImpl.java (93%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/PartitionedByIdCollectionRequestOptionsFactory.java (86%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/RemainingPartitionWorkImpl.java (91%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/RemainingWorkEstimatorImpl.java (83%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/StatusCodeErrorType.java (93%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/TraceHealthMonitor.java (87%) rename sdk/src/main/java/com/azure/data/cosmos/{changefeed/internal => internal/changefeed/implementation}/WorkerTask.java (64%) create mode 100644 sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java index 5f15e70098fc4..16348a9bf6821 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java @@ -40,7 +40,7 @@ import java.time.Duration; /** - * Sample class to test the implementation. + * Sample for Change Feed Processor. * */ public class SampleChangeFeedProcessor { @@ -69,15 +69,12 @@ public static void main (String[]args) { System.out.println("-->CREATE container for lease: " + COLLECTION_NAME + "-leases"); CosmosContainer leaseContainer = createNewLeaseCollection(client, DATABASE_NAME, COLLECTION_NAME + "-leases"); - Mono changeFeedProcessor1 = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); + changeFeedProcessorInstance = getChangeFeedProcessor("SampleHost_1", feedContainer, leaseContainer); - changeFeedProcessor1.subscribe(changeFeedProcessor -> { - changeFeedProcessorInstance = changeFeedProcessor; - changeFeedProcessor.start().subscribe(aVoid -> { - createNewDocuments(feedContainer, 10, Duration.ofSeconds(3)); - isWorkCompleted = true; - }); - }); + changeFeedProcessorInstance.start().subscribe(aVoid -> { + createNewDocuments(feedContainer, 10, Duration.ofSeconds(3)); + isWorkCompleted = true; + }); long remainingWork = WAIT_FOR_WORK; while (!isWorkCompleted && remainingWork > 0) { @@ -87,7 +84,7 @@ public static void main (String[]args) { if (isWorkCompleted) { if (changeFeedProcessorInstance != null) { - changeFeedProcessorInstance.stop().wait(10000); + changeFeedProcessorInstance.stop().subscribe().wait(10000); } } else { throw new RuntimeException("The change feed processor initialization and automatic create document feeding process did not complete in the expected time"); @@ -96,7 +93,7 @@ public static void main (String[]args) { System.out.println("-->DELETE sample's database: " + DATABASE_NAME); deleteDatabase(cosmosDatabase); - Thread.sleep(15000); + Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); @@ -106,12 +103,20 @@ public static void main (String[]args) { System.exit(0); } - public static Mono getChangeFeedProcessor(String hostName, CosmosContainer feedContainer, CosmosContainer leaseContainer) { + public static ChangeFeedProcessor getChangeFeedProcessor(String hostName, CosmosContainer feedContainer, CosmosContainer leaseContainer) { return ChangeFeedProcessor.Builder() - .withHostName(hostName) - .withFeedContainerClient(feedContainer) - .withLeaseContainerClient(leaseContainer) - .withChangeFeedObserver(SampleObserverImpl.class) + .hostName(hostName) + .feedContainerClient(feedContainer) + .leaseContainerClient(leaseContainer) + .handleChanges(docs -> { + System.out.println("--->handleChanges() START"); + + for (CosmosItemProperties document : docs) { + System.out.println("---->DOCUMENT RECEIVED: " + document.toJson(SerializationFormattingPolicy.INDENTED)); + } + System.out.println("--->handleChanges() END"); + + }) .build(); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java index fce5651c8feb0..4c5ca0234cdc5 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java @@ -22,9 +22,14 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.changefeed.internal.ChangeFeedProcessorBuilderImpl; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverFactory; +import com.azure.data.cosmos.internal.changefeed.implementation.ChangeFeedProcessorBuilderImpl; import reactor.core.publisher.Mono; +import java.util.List; +import java.util.function.Consumer; + /** * Simple host for distributing change feed events across observers and thus allowing these observers scale. * It distributes the load across its instances and allows dynamic scaling: @@ -42,10 +47,12 @@ *

* {@code * ChangeFeedProcessor changeFeedProcessor = ChangeFeedProcessor.Builder() - * .withHostName(hostName) - * .withFeedContainerClient(feedContainer) - * .withLeaseContainerClient(leaseContainer) - * .withChangeFeedObserver(SampleObserverImpl.class) + * .hostName(hostName) + * .feedContainerClient(feedContainer) + * .leaseContainerClient(leaseContainer) + * .handleChanges(docs -> { + * // Implementation for handling and processing CosmosItemProperties list goes here + * }) * .build(); * } */ @@ -72,10 +79,12 @@ public interface ChangeFeedProcessor { * {@code * * ChangeFeedProcessor.Builder() - * .withHostName("SampleHost") - * .withFeedContainerClient(feedContainer) - * .withLeaseContainerClient(leaseContainer) - * .withChangeFeedObserver(SampleObserverImpl.class) + * .hostName("SampleHost") + * .feedContainerClient(feedContainer) + * .leaseContainerClient(leaseContainer) + * .handleChanges(docs -> { + * // Implementation for handling and processing CosmosItemProperties list goes here + * }) * .build(); * } * @@ -92,7 +101,7 @@ interface BuilderDefinition { * @param hostName the name to be used for the host. When using multiple hosts, each host must have a unique name. * @return current Builder. */ - BuilderDefinition withHostName(String hostName); + BuilderDefinition hostName(String hostName); /** * Sets and existing {@link CosmosContainer} to be used to read from the monitored collection. @@ -100,7 +109,7 @@ interface BuilderDefinition { * @param feedContainerClient the instance of {@link CosmosContainer} to be used. * @return current Builder. */ - BuilderDefinition withFeedContainerClient(CosmosContainer feedContainerClient); + BuilderDefinition feedContainerClient(CosmosContainer feedContainerClient); /** * Sets the {@link ChangeFeedProcessorOptions} to be used. @@ -108,23 +117,15 @@ interface BuilderDefinition { * @param changeFeedProcessorOptions the change feed processor options to use. * @return current Builder. */ - BuilderDefinition withProcessorOptions(ChangeFeedProcessorOptions changeFeedProcessorOptions); - - /** - * Sets the {@link ChangeFeedObserverFactory} to be used to generate {@link ChangeFeedObserver} - * - * @param observerFactory The instance of {@link ChangeFeedObserverFactory} to use. - * @return current Builder. - */ - BuilderDefinition withChangeFeedObserverFactory(ChangeFeedObserverFactory observerFactory); + BuilderDefinition options(ChangeFeedProcessorOptions changeFeedProcessorOptions); /** - * Sets an existing {@link ChangeFeedObserver} type to be used by a {@link ChangeFeedObserverFactory} to process changes. + * Sets a consumer function which will be called to process changes. * - * @param type the type of {@link ChangeFeedObserver} to be used. + * @param consumer the consumer of {@link ChangeFeedObserver} to call for handling the feeds. * @return current Builder. */ - BuilderDefinition withChangeFeedObserver(Class type); + BuilderDefinition handleChanges(Consumer> consumer); /** * Sets an existing {@link CosmosContainer} to be used to read from the leases collection. @@ -132,13 +133,13 @@ interface BuilderDefinition { * @param leaseCosmosClient the instance of {@link CosmosContainer} to use. * @return current Builder. */ - BuilderDefinition withLeaseContainerClient(CosmosContainer leaseCosmosClient); + BuilderDefinition leaseContainerClient(CosmosContainer leaseCosmosClient); /** * Builds a new instance of the {@link ChangeFeedProcessor} with the specified configuration asynchronously. * * @return an instance of {@link ChangeFeedProcessor}. */ - Mono build(); + ChangeFeedProcessor build(); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java index d6a592e643781..ea0981425dec8 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java @@ -22,11 +22,10 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.changefeed.CheckpointFrequency; +import com.azure.data.cosmos.internal.changefeed.CheckpointFrequency; import java.time.Duration; import java.time.OffsetDateTime; -import java.util.concurrent.ExecutorService; public class ChangeFeedProcessorOptions { private static final int DefaultQueryPartitionsMaxBatchSize = 100; @@ -39,7 +38,6 @@ public class ChangeFeedProcessorOptions { private Duration leaseAcquireInterval; private Duration leaseExpirationInterval; private Duration feedPollDelay; - private CheckpointFrequency checkpointFrequency; private String leasePrefix; private int maxItemCount; @@ -52,7 +50,6 @@ public class ChangeFeedProcessorOptions { private boolean discardExistingLeases; private int queryPartitionsMaxBatchSize; private int degreeOfParallelism; - private ExecutorService executorService; public ChangeFeedProcessorOptions() { this.maxItemCount = 100; @@ -62,10 +59,8 @@ public ChangeFeedProcessorOptions() { this.leaseExpirationInterval = DefaultExpirationInterval; this.feedPollDelay = DefaultFeedPollDelay; this.queryPartitionsMaxBatchSize = DefaultQueryPartitionsMaxBatchSize; - this.checkpointFrequency = new CheckpointFrequency(); this.maxPartitionCount = 0; // unlimited this.degreeOfParallelism = 25; // default - this.executorService = null; } /** @@ -155,26 +150,6 @@ public ChangeFeedProcessorOptions feedPollDelay(Duration feedPollDelay) { return this; } - /** - * Gets the frequency how often to checkpoint leases. - * - * @return the frequency how often to checkpoint leases. - */ - public CheckpointFrequency checkpointFrequency() { - return this.checkpointFrequency; - } - - /** - * Sets the frequency how often to checkpoint leases. - * - * @param checkpointFrequency the frequency how often to checkpoint leases. - * @return the current ChangeFeedProcessorOptions instance. - */ - public ChangeFeedProcessorOptions checkpointFrequency(CheckpointFrequency checkpointFrequency) { - this.checkpointFrequency = checkpointFrequency; - return this; - } - /** * Gets a prefix to be used as part of the lease ID. *

@@ -450,25 +425,4 @@ public ChangeFeedProcessorOptions degreeOfParallelism(int defaultQueryPartitions this.queryPartitionsMaxBatchSize = queryPartitionsMaxBatchSize; return this; } - - /** - * Gets the current {@link ExecutorService} which will be used to control the thread pool. - * - * @return current ExecutorService instance. - */ - public ExecutorService executorService() { - return this.executorService; - } - - /** - * Sets the {@link ExecutorService} to be used to control the thread pool. - * - * @param executorService The instance of {@link ExecutorService} to use. - * @return current ChangeFeedProcessorOptions instance. - */ - public ChangeFeedProcessorOptions executorService(ExecutorService executorService) { - this.executorService = executorService; - return this; - } - } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java index 0a7fcc8b3a16a..03499f248ee43 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java @@ -22,9 +22,10 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper; import reactor.core.publisher.Mono; +import static com.azure.data.cosmos.internal.Paths.CONFLICTS_PATH_SEGMENT; + public class CosmosConflict extends CosmosResource { private CosmosContainer container; @@ -86,11 +87,11 @@ public Mono delete(CosmosConflictRequestOptions options) @Override protected String URIPathSegment() { - return ChangeFeedHelper.Paths.CONFLICTS_PATH_SEGMENT; + return CONFLICTS_PATH_SEGMENT; } @Override protected String parentLink() { return this.container.getLink(); } -} \ No newline at end of file +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index 7d00a870f7028..21d95837054a1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -356,9 +356,9 @@ public Flux> queryChangeFeedItems(ChangeFeedO return getDatabase() .getDocClientWrapper() .queryDocumentChangeFeed(getLink(), changeFeedOptions) - .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( + .map(response-> new FeedResponse( CosmosItemProperties.getFromV2Results(response.results()), - response.responseHeaders(), response.queryMetrics())); + response.responseHeaders(), false)); } /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ContainerConnectionInfo.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/ContainerConnectionInfo.java deleted file mode 100644 index 6ce60b11999d1..0000000000000 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ContainerConnectionInfo.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.azure.data.cosmos.changefeed; - -import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.ConsistencyLevel; - -import java.net.URI; -import java.net.URISyntaxException; - -/** - * Holds information specifying how to get the Cosmos container. - */ -public class ContainerConnectionInfo { - private ConnectionPolicy connectionPolicy; - private ConsistencyLevel consistencyLevel; - private String serviceEndpointUri; - private String keyOrResourceToken; - private String databaseName; - private String containerName; - - /** - * Initializes a new instance of the {@link ContainerConnectionInfo} class. - */ - public ContainerConnectionInfo() { - this.connectionPolicy = new ConnectionPolicy(); - this.consistencyLevel = ConsistencyLevel.SESSION; - } - - /** - * Initializes a new instance of the {@link ContainerConnectionInfo} class. - * - * @param containerConnectionInfo the {@link ContainerConnectionInfo} instance to copy the settings from. - */ - public ContainerConnectionInfo(ContainerConnectionInfo containerConnectionInfo) { - this.connectionPolicy = containerConnectionInfo.connectionPolicy; - this.consistencyLevel = containerConnectionInfo.consistencyLevel; - this.serviceEndpointUri = containerConnectionInfo.serviceEndpointUri; - this.keyOrResourceToken = containerConnectionInfo.keyOrResourceToken; - this.databaseName = containerConnectionInfo.databaseName; - this.containerName = containerConnectionInfo.containerName; - } - - /** - * Gets the connection policy to connect to Cosmos service. - * - * @return the connection policy to connect to Cosmos service. - */ - public ConnectionPolicy getConnectionPolicy() { - return this.connectionPolicy; - } - - /** - * Gets the consistency level; default is "SESSION". - * @return the consistency level. - */ - public ConsistencyLevel getConsistencyLevel() { - return this.consistencyLevel; - } - - /** - * Gets the URI of the Document service. - * - * @return the URI of the Document service. - */ - public String getServiceEndpointUri() { - return this.serviceEndpointUri; - } - - /** - * Gets the secret master key to connect to the Cosmos service. - * - * @return the secret master key to connect to the Cosmos service. - */ - public String getKeyOrResourceToken() { - return this.keyOrResourceToken; - } - - /** - * Gets the name of the database the container resides in. - * - * @return the name of the database the container resides in. - */ - public String getDatabaseName() { - return this.databaseName; - } - - /** - * Gets the name of the Cosmos container. - * - * @return the name of the Cosmos container. - */ - public String getContainerName() { - return this.containerName; - } - - /** - * Sets the connection policy to connect to Cosmos service. - * - * @param connectionPolicy the connection policy to connect to Cosmos service. - * @return current instance of {@link ContainerConnectionInfo} - */ - public ContainerConnectionInfo withConnectionPolicy(ConnectionPolicy connectionPolicy) { - this.connectionPolicy = connectionPolicy; - return this; - } - - /** - * Sets the consistency level. - * - * @param consistencyLevel the consistency level. - * @return current instance of {@link ContainerConnectionInfo} - */ - public ContainerConnectionInfo withConsistencyLevel(ConsistencyLevel consistencyLevel) { - this.consistencyLevel = consistencyLevel; - return this; - } - - /** - * Sets the URI of the Document service. - * @param serviceEndpoint the URI of the Cosmos service. - * @return current instance of {@link ContainerConnectionInfo} - */ - public ContainerConnectionInfo withServiceEndpointUri(String serviceEndpoint) { - try { - new URI(serviceEndpoint); - } catch (URISyntaxException ex) { - throw new IllegalArgumentException("serviceEndpointUri"); - } - - this.serviceEndpointUri = serviceEndpoint; - return this; - } - - /** - * Sets the secret master key to connect to the Cosmos service. - * @param keyOrResourceToken the secret master key to connect to the Cosmos service. - * @return current instance of {@link ContainerConnectionInfo} - */ - public ContainerConnectionInfo withKeyOrResourceToken(String keyOrResourceToken) { - this.keyOrResourceToken = keyOrResourceToken; - return this; - } - - /** - * Sets the name of the database the container resides in. - * - * @param databaseName the name of the database the container resides in. - * @return current instance of {@link ContainerConnectionInfo} - */ - public ContainerConnectionInfo withDatabaseName(String databaseName) { - this.databaseName = databaseName; - return this; - } - - /** - * Sets the name of the Cosmos container. - * - * @param containerName the name of the Cosmos container. - * @return current instance of {@link ContainerConnectionInfo} - */ - public ContainerConnectionInfo withContainerName(String containerName) { - this.containerName = containerName; - return this; - } -} diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java deleted file mode 100644 index 0fdd09b749c97..0000000000000 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseUpdaterImpl.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.azure.data.cosmos.changefeed.internal; - -import com.azure.data.cosmos.AccessCondition; -import com.azure.data.cosmos.AccessConditionType; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosItem; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.CosmosItemRequestOptions; -import com.azure.data.cosmos.CosmosItemResponse; -import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.ServiceItemLease; -import com.azure.data.cosmos.changefeed.ServiceItemLeaseUpdater; -import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import reactor.core.publisher.Mono; - -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.function.Function; - -import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT; -import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; -import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.HTTP_STATUS_CODE_PRECONDITION_FAILED; - -/** - * Implementation for service lease updater interface. - */ -public class DocumentServiceLeaseUpdaterImpl implements ServiceItemLeaseUpdater { - private final Logger logger = LoggerFactory.getLogger(TraceHealthMonitor.class); - private final int RETRY_COUNT_ON_CONFLICT = 5; - private final ChangeFeedContextClient client; - - public DocumentServiceLeaseUpdaterImpl(ChangeFeedContextClient client) { - if (client == null) { - throw new IllegalArgumentException("client"); - } - - this.client = client; - } - - @Override - public Mono updateLease(Lease cachedLease, CosmosItem itemLink, CosmosItemRequestOptions requestOptions, Function updateLease) { - Lease lease = cachedLease; - - for (int retryCount = RETRY_COUNT_ON_CONFLICT; retryCount > 0; retryCount--) { - lease = updateLease.apply(lease); - - if (lease == null) { - return null; - } - - lease.setTimestamp(ZonedDateTime.now(ZoneId.of("UTC"))); - CosmosItemProperties leaseDocument = this.tryReplaceLease(lease, itemLink); - - if (leaseDocument != null) { - return Mono.just(ServiceItemLease.fromDocument(leaseDocument)); - } - - // Partition lease update conflict. Reading the current version of lease. - CosmosItemProperties document = null; - try { - CosmosItemResponse response = this.client.readItem(itemLink, requestOptions) - .block(); - document = response.properties(); - } catch (RuntimeException re) { - if (re.getCause() instanceof CosmosClientException) { - CosmosClientException ex = (CosmosClientException) re.getCause(); - if (ex.statusCode() == HTTP_STATUS_CODE_NOT_FOUND) { - // Partition lease no longer exists - throw new LeaseLostException(lease); - } - } - throw re; - } - - ServiceItemLease serverLease = ServiceItemLease.fromDocument(document); -// Logger.InfoFormat( -// "Partition {0} update failed because the lease with token '{1}' was updated by host '{2}' with token '{3}'. Will retry, {4} retry(s) left.", -// lease.LeaseToken, -// lease.ConcurrencyToken, -// serverLease.Owner, -// serverLease.ConcurrencyToken, -// retryCount); - - lease = serverLease; - } - - throw new LeaseLostException(lease); - } - - private CosmosItemProperties tryReplaceLease(Lease lease, CosmosItem itemLink) throws LeaseLostException { - try { - CosmosItemResponse response = this.client.replaceItem(itemLink, lease, this.getCreateIfMatchOptions(lease)) - .block(); - return response.properties(); - } catch (RuntimeException re) { - if (re.getCause() instanceof CosmosClientException) { - CosmosClientException ex = (CosmosClientException) re.getCause(); - switch (ex.statusCode()) { - case HTTP_STATUS_CODE_PRECONDITION_FAILED: { - return null; - } - case HTTP_STATUS_CODE_CONFLICT: { - throw new LeaseLostException(lease, ex, false); - } - case HTTP_STATUS_CODE_NOT_FOUND: { - throw new LeaseLostException(lease, ex, true); - } - default: { - throw re; - } - } - } - throw re; - } - } - - private CosmosItemRequestOptions getCreateIfMatchOptions(Lease lease) { - AccessCondition ifMatchCondition = new AccessCondition(); - ifMatchCondition.type(AccessConditionType.IF_MATCH); - ifMatchCondition.condition(lease.getConcurrencyToken()); - - CosmosItemRequestOptions createIfMatchOptions = new CosmosItemRequestOptions(); - createIfMatchOptions.accessCondition(ifMatchCondition); - - return createIfMatchOptions; - } -} diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java deleted file mode 100644 index e25a94b466063..0000000000000 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorImpl.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.azure.data.cosmos.changefeed.internal; - -import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedObserverCloseReason; -import com.azure.data.cosmos.ChangeFeedObserverContext; -import com.azure.data.cosmos.changefeed.CancellationToken; -import com.azure.data.cosmos.changefeed.CancellationTokenSource; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.LeaseRenewer; -import com.azure.data.cosmos.changefeed.PartitionProcessor; -import com.azure.data.cosmos.changefeed.PartitionSupervisor; -import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; -import com.azure.data.cosmos.changefeed.exceptions.ObserverException; -import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; -import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; -import reactor.core.publisher.Mono; - -import java.io.Closeable; -import java.io.IOException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * Implementation for {@link PartitionSupervisor}. - */ -public class PartitionSupervisorImpl implements PartitionSupervisor, Closeable { - private final Lease lease; - private final ChangeFeedObserver observer; - private final PartitionProcessor processor; - private final LeaseRenewer renewer; - private CancellationTokenSource renewerCancellation; - private CancellationTokenSource processorCancellation; - - private RuntimeException resultException; - - private ExecutorService executorService; - - public PartitionSupervisorImpl(Lease lease, ChangeFeedObserver observer, PartitionProcessor processor, LeaseRenewer renewer, ExecutorService executorService) { - this.lease = lease; - this.observer = observer; - this.processor = processor; - this.renewer = renewer; - this.executorService = executorService; - - if (executorService == null) { - this.executorService = Executors.newFixedThreadPool(3); - } - } - - @Override - public Mono run(CancellationToken shutdownToken) { - PartitionSupervisorImpl self = this; - this.resultException = null; - - return Mono.fromRunnable(() -> { - - ChangeFeedObserverContext context = new ChangeFeedObserverContextImpl(self.lease.getLeaseToken()); - - self.observer.open(context); - - ChangeFeedObserverCloseReason closeReason = ChangeFeedObserverCloseReason.UNKNOWN; - - try { - self.processorCancellation = new CancellationTokenSource(); - - Thread processorThread = new Thread(new Runnable() { - @Override - public void run() { - self.processor.run(self.processorCancellation.getToken()).block(); - } - }); - - self.renewerCancellation = new CancellationTokenSource(); - - Thread renewerThread = new Thread(new Runnable() { - @Override - public void run() { - self.renewer.run(self.renewerCancellation.getToken()).block(); - } - }); - - self.executorService.execute(processorThread); - self.executorService.execute(renewerThread); - - while (!shutdownToken.isCancellationRequested() && self.processor.getResultException() == null && self.renewer.getResultException() == null) { - try { - Thread.sleep(100); - } catch (InterruptedException iex) { - break; - } - } - - this.processorCancellation.cancel(); - this.renewerCancellation.cancel(); - executorService.shutdown(); - - if (self.processor.getResultException() != null) { - throw self.processor.getResultException(); - } - - if (self.renewer.getResultException() != null) { - throw self.renewer.getResultException(); - } - - closeReason = shutdownToken.isCancellationRequested() ? - ChangeFeedObserverCloseReason.SHUTDOWN : - ChangeFeedObserverCloseReason.UNKNOWN; - - } catch (LeaseLostException llex) { - closeReason = ChangeFeedObserverCloseReason.LEASE_LOST; - self.resultException = llex; - } catch (PartitionSplitException pex) { - closeReason = ChangeFeedObserverCloseReason.LEASE_GONE; - self.resultException = pex; - } catch (TaskCancelledException tcex) { - closeReason = ChangeFeedObserverCloseReason.SHUTDOWN; - self.resultException = null; - } catch (ObserverException oex) { - closeReason = ChangeFeedObserverCloseReason.OBSERVER_ERROR; - self.resultException = oex; - } catch (Exception ex) { - closeReason = ChangeFeedObserverCloseReason.UNKNOWN; - } finally { - self.observer.close(context, closeReason); - - if (self.resultException != null) { - Mono.error(self.resultException); - } - } - }); - } - - @Override - public RuntimeException getResultException() { - return this.resultException; - } - - @Override - public void close() throws IOException { - if (this.processorCancellation != null) { - this.processorCancellation.close(); - } - - this.renewerCancellation.close(); - } -} diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/Bootstrapper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Bootstrapper.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/Bootstrapper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Bootstrapper.java index eb8531657596f..1ebd65c2160bf 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/Bootstrapper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Bootstrapper.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationToken.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationToken.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationToken.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationToken.java index da39c5af6069b..cf5ff3eddd2b4 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationToken.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationToken.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; /** * Propagates notification that operations should be canceled.. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationTokenSource.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationTokenSource.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationTokenSource.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationTokenSource.java index 964196cdceded..7cb363ca3a96a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/CancellationTokenSource.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationTokenSource.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import java.io.Closeable; import java.io.IOException; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ChangeFeedContextClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java similarity index 99% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/ChangeFeedContextClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java index ecb79c0552b31..a76633e5c7df9 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ChangeFeedContextClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.CosmosContainer; diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserver.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserver.java similarity index 95% rename from sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserver.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserver.java index e2e0b638454af..b360c22b4c44d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserver.java @@ -20,7 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal.changefeed; + +import com.azure.data.cosmos.CosmosItemProperties; import java.util.List; diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverCloseReason.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverCloseReason.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverCloseReason.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverCloseReason.java index 1bd720fef5ffb..4b2ef51483b51 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverCloseReason.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverCloseReason.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal.changefeed; /** * The reason for the {@link ChangeFeedObserver} to close. diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverContext.java similarity index 93% rename from sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverContext.java index 0614d06aed4e6..15d18034a8e2a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverContext.java @@ -20,8 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal.changefeed; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.FeedResponse; import reactor.core.publisher.Mono; /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverFactory.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverFactory.java index 4574b4c409054..b87929bd4a1cc 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedObserverFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverFactory.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal.changefeed; /** * Factory class used to create instance(s) of {@link ChangeFeedObserver}. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/CheckpointFrequency.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CheckpointFrequency.java similarity index 98% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/CheckpointFrequency.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CheckpointFrequency.java index 4d19665fade2f..e6ab9a3e83eee 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/CheckpointFrequency.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CheckpointFrequency.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import java.time.Duration; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitor.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitor.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitor.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitor.java index 6afae75c7cdc3..f5c99caeea8d6 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitor.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitoringRecord.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitoringRecord.java similarity index 98% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitoringRecord.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitoringRecord.java index a875cfcd5ddbf..c0aadd7660feb 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/HealthMonitoringRecord.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitoringRecord.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; /** * A record used in the health monitoring. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/Lease.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Lease.java similarity index 98% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/Lease.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Lease.java index 3b10675c61dd7..178dd354080d4 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/Lease.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Lease.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import com.azure.data.cosmos.ChangeFeedProcessor; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseCheckpointer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseCheckpointer.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseCheckpointer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseCheckpointer.java index 501595f13f1ff..da413ca2bdefd 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseCheckpointer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseCheckpointer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseContainer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseContainer.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseContainer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseContainer.java index 0af0613e4810c..be77084431c3d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseContainer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Flux; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseManager.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseManager.java similarity index 95% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseManager.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseManager.java index b6c80a72e50fc..342213d20d075 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseManager.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseManager.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; -import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.internal.changefeed.exceptions.LeaseLostException; import reactor.core.publisher.Mono; /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseRenewer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseRenewer.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseRenewer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseRenewer.java index 1eca3a46aa61a..07795e34f8131 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseRenewer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseRenewer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStore.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStore.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStore.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStore.java index e656044cdb910..b443127de135b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStore.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStore.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManager.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManager.java similarity index 88% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManager.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManager.java index d11e3e8866e10..75f06ef593fd2 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManager.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManager.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.changefeed.internal.LeaseStoreManagerImpl; +import com.azure.data.cosmos.internal.changefeed.implementation.LeaseStoreManagerImpl; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -39,15 +39,15 @@ public interface LeaseStoreManager extends LeaseContainer, LeaseManager, LeaseSt * For the actual creation of lease manager instance, delegates to lease manager factory. */ interface LeaseStoreManagerBuilderDefinition { - LeaseStoreManagerBuilderDefinition withLeaseContextClient(ChangeFeedContextClient leaseContextClient); + LeaseStoreManagerBuilderDefinition leaseContextClient(ChangeFeedContextClient leaseContextClient); - LeaseStoreManagerBuilderDefinition withLeasePrefix(String leasePrefix); + LeaseStoreManagerBuilderDefinition leasePrefix(String leasePrefix); - LeaseStoreManagerBuilderDefinition withLeaseCollectionLink(CosmosContainer leaseCollectionLink); + LeaseStoreManagerBuilderDefinition leaseCollectionLink(CosmosContainer leaseCollectionLink); - LeaseStoreManagerBuilderDefinition withRequestOptionsFactory(RequestOptionsFactory requestOptionsFactory); + LeaseStoreManagerBuilderDefinition requestOptionsFactory(RequestOptionsFactory requestOptionsFactory); - LeaseStoreManagerBuilderDefinition withHostName(String hostName); + LeaseStoreManagerBuilderDefinition hostName(String hostName); Mono build(); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManagerSettings.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManagerSettings.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java index d2e2f9da56c5e..b08edecce5a0f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/LeaseStoreManagerSettings.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import com.azure.data.cosmos.CosmosContainer; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionCheckpointer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionCheckpointer.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionCheckpointer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionCheckpointer.java index 298fd5956f8c9..62abcd75e7d16 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionCheckpointer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionCheckpointer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionController.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionController.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionController.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionController.java index 1c9871a2fc0d5..8e30828ad016b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionController.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionController.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancer.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancer.java index e10d6320640d1..4d580d67bbbe5 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancingStrategy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancingStrategy.java similarity index 98% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancingStrategy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancingStrategy.java index 865c034e28bea..b8ad4f05fec68 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionLoadBalancingStrategy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancingStrategy.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import com.azure.data.cosmos.ChangeFeedProcessorOptions; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionManager.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionManager.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionManager.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionManager.java index adcbb26bf439d..a82f07e70b2bc 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionManager.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionManager.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessor.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessor.java similarity index 93% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessor.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessor.java index fcbac93e50e50..5f0a7b54ca584 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessor.java @@ -20,10 +20,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; -import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedObserverContext; import reactor.core.publisher.Mono; /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessorFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessorFactory.java similarity index 94% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessorFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessorFactory.java index c7194df7972a2..23f1e357e2e22 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionProcessorFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessorFactory.java @@ -20,9 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; - -import com.azure.data.cosmos.ChangeFeedObserver; +package com.azure.data.cosmos.internal.changefeed; /** * Factory class used to create instance(s) of {@link PartitionProcessor}. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisor.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisor.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisor.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisor.java index 442a34182bf64..49a934d8bdf4d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisor.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisorFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisorFactory.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisorFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisorFactory.java index a15763e00e85f..3dfffb012078c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSupervisorFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisorFactory.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; /** * Interface for the partition supervisor factory. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSynchronizer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSynchronizer.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSynchronizer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSynchronizer.java index 89173d1fae0f0..fdd24569726ea 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/PartitionSynchronizer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSynchronizer.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ProcessorSettings.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java similarity index 98% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/ProcessorSettings.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java index ad0f04e5bccb2..ae61fade13ecd 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ProcessorSettings.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import com.azure.data.cosmos.CosmosContainer; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingPartitionWork.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingPartitionWork.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingPartitionWork.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingPartitionWork.java index 4c325534bcc69..ec348e16d1911 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingPartitionWork.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingPartitionWork.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; /** * Interface for remaining partition work. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingWorkEstimator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingWorkEstimator.java similarity index 92% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingWorkEstimator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingWorkEstimator.java index c7ecc032ca8f4..95ceb66be6517 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/RemainingWorkEstimator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingWorkEstimator.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -35,12 +35,12 @@ public interface RemainingWorkEstimator { * * @return an estimation of pending work in amount of documents. */ - Mono getEstimatedRemainingWork(); + Mono estimatedRemainingWork(); /** * Calculates an estimate of the pending work remaining to be read in the Change Feed in amount of documents per partition. * * @return an estimation of pending work in amount of documents per partitions. */ - Flux getEstimatedRemainingWorkPerPartition(); + Flux estimatedRemainingWorkPerPartition(); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/RequestOptionsFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RequestOptionsFactory.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/RequestOptionsFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RequestOptionsFactory.java index fcdbe03d69192..7db485a8a3351 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/RequestOptionsFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RequestOptionsFactory.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.FeedOptions; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLease.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLease.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java index 19e4b177030ef..336577103e4eb 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLease.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java @@ -20,11 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.changefeed.internal.Constants; +//import com.azure.data.cosmos.internal.changefeed.internal.Constants; +import com.azure.data.cosmos.internal.Constants; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLeaseUpdater.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLeaseUpdater.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLeaseUpdater.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLeaseUpdater.java index bca52fbdd9fd2..92f6da3d26818 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/ServiceItemLeaseUpdater.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLeaseUpdater.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed; +package com.azure.data.cosmos.internal.changefeed; import com.azure.data.cosmos.CosmosItem; import com.azure.data.cosmos.CosmosItemRequestOptions; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/LeaseLostException.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/LeaseLostException.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/LeaseLostException.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/LeaseLostException.java index 61bf59ee18ced..126e27bfdaceb 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/LeaseLostException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/LeaseLostException.java @@ -20,9 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.internal.changefeed.exceptions; -import com.azure.data.cosmos.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.Lease; /** * Exception occurred when lease is lost, that would typically happen when it is taken by another host. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/ObserverException.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/ObserverException.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/ObserverException.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/ObserverException.java index 225cff2039389..fd052ec2b4845 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/ObserverException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/ObserverException.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.internal.changefeed.exceptions; /** * Exception occurred when an operation in a ChangeFeedObserver is running and throws by user code. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionException.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionException.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionException.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionException.java index a0d890d8062e2..5a4f543a83884 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionException.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.internal.changefeed.exceptions; /** * General exception occurred during partition processing. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionNotFoundException.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionNotFoundException.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionNotFoundException.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionNotFoundException.java index d9b8206ae157d..9205bfffc5e81 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionNotFoundException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionNotFoundException.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.internal.changefeed.exceptions; /** * Exception occurred when partition wasn't found. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionSplitException.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionSplitException.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionSplitException.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionSplitException.java index 424e8d09f6381..9b9d5be037bd1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/PartitionSplitException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionSplitException.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.internal.changefeed.exceptions; /** * Exception occurred during partition split. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/TaskCancelledException.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/TaskCancelledException.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/TaskCancelledException.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/TaskCancelledException.java index 626aa3f4246c0..affa262512545 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/exceptions/TaskCancelledException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/TaskCancelledException.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.exceptions; +package com.azure.data.cosmos.internal.changefeed.exceptions; /** * Exception occurred when an operation in a ChangeFeedObserver was canceled. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/AutoCheckpointer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java similarity index 88% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/AutoCheckpointer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java index c7b0df8f5d996..6a24632d086db 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/AutoCheckpointer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedObserverCloseReason; -import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverCloseReason; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.changefeed.CheckpointFrequency; +import com.azure.data.cosmos.internal.changefeed.CheckpointFrequency; import java.time.Duration; import java.time.ZoneId; @@ -36,7 +36,7 @@ /** * Auto check-pointer implementation for {@link ChangeFeedObserver}. */ -public class AutoCheckpointer implements ChangeFeedObserver { +class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private int processedDocCount; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/BootstrapperImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/BootstrapperImpl.java similarity index 92% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/BootstrapperImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/BootstrapperImpl.java index c3fd5af65f63d..701071019dead 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/BootstrapperImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/BootstrapperImpl.java @@ -20,11 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.changefeed.Bootstrapper; -import com.azure.data.cosmos.changefeed.LeaseStore; -import com.azure.data.cosmos.changefeed.PartitionSynchronizer; +import com.azure.data.cosmos.internal.changefeed.Bootstrapper; +import com.azure.data.cosmos.internal.changefeed.LeaseStore; +import com.azure.data.cosmos.internal.changefeed.PartitionSynchronizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -34,7 +34,7 @@ /** * Implementation for the bootstrapping interface. */ -public class BootstrapperImpl implements Bootstrapper { +class BootstrapperImpl implements Bootstrapper { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private final PartitionSynchronizer synchronizer; private final LeaseStore leaseStore; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java similarity index 87% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java index 6460e7e0fca6d..b5e584f8c7ae6 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedContextClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ChangeFeedOptions; @@ -39,7 +39,7 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; @@ -90,55 +90,60 @@ public ChangeFeedContextClientImpl(CosmosContainer cosmosContainer, Scheduler rx @Override public Flux> readPartitionKeyRangeFeed(String partitionKeyRangesOrCollectionLink, FeedOptions feedOptions) { return this.documentClient.readPartitionKeyRanges(partitionKeyRangesOrCollectionLink, feedOptions) - .subscribeOn(this.rxScheduler); + .publishOn(this.rxScheduler); } @Override public Flux> createDocumentChangeFeedQuery(CosmosContainer collectionLink, ChangeFeedOptions feedOptions) { return collectionLink.queryChangeFeedItems(feedOptions) - .subscribeOn(this.rxScheduler); + .publishOn(this.rxScheduler); } @Override public Mono readDatabase(CosmosDatabase database, CosmosDatabaseRequestOptions options) { return database.read() - .subscribeOn(this.rxScheduler); + .publishOn(this.rxScheduler); } @Override public Mono readContainer(CosmosContainer containerLink, CosmosContainerRequestOptions options) { return containerLink.read(options) - .subscribeOn(this.rxScheduler); + .publishOn(this.rxScheduler); } @Override public Mono createItem(CosmosContainer containerLink, Object document, CosmosItemRequestOptions options, boolean disableAutomaticIdGeneration) { - return containerLink.createItem(document, options) - .subscribeOn(this.rxScheduler); + if (options != null) { + return containerLink.createItem(document, options) + .publishOn(this.rxScheduler); + } else { + return containerLink.createItem(document) + .publishOn(this.rxScheduler); + } } @Override public Mono deleteItem(CosmosItem itemLink, CosmosItemRequestOptions options) { return itemLink.delete(options) - .subscribeOn(this.rxScheduler); + .publishOn(this.rxScheduler); } @Override public Mono replaceItem(CosmosItem itemLink, Object document, CosmosItemRequestOptions options) { return itemLink.replace(document, options) - .subscribeOn(this.rxScheduler); + .publishOn(this.rxScheduler); } @Override public Mono readItem(CosmosItem itemLink, CosmosItemRequestOptions options) { return itemLink.read(options) - .subscribeOn(this.rxScheduler); + .publishOn(this.rxScheduler); } @Override public Flux> queryItems(CosmosContainer containerLink, SqlQuerySpec querySpec, FeedOptions options) { return containerLink.queryItems(querySpec, options) - .subscribeOn(this.rxScheduler); + .publishOn(this.rxScheduler); } @Override @@ -148,7 +153,8 @@ public URI getServiceEndpoint() { @Override public Mono readContainerSettings(CosmosContainer containerLink, CosmosContainerRequestOptions options) { - return null; + return containerLink.read(options) + .map(cosmosContainerResponse -> cosmosContainerResponse.settings()); } @Override diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedHelper.java similarity index 82% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedHelper.java index 7639ec6b6b705..dee963a1b3754 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedHelper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedHelper.java @@ -20,9 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; - -import com.azure.data.cosmos.changefeed.ContainerConnectionInfo; +package com.azure.data.cosmos.internal.changefeed.implementation; import java.net.MalformedURLException; import java.net.URI; @@ -30,14 +28,14 @@ import java.net.URL; import java.util.Map; -import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.Paths.COLLECTIONS_PATH_SEGMENT; -import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.Paths.DATABASES_ROOT; -import static com.azure.data.cosmos.changefeed.internal.ChangeFeedHelper.Paths.DOCUMENTS_PATH_SEGMENT; +import static com.azure.data.cosmos.internal.changefeed.implementation.ChangeFeedHelper.Paths.COLLECTIONS_PATH_SEGMENT; +import static com.azure.data.cosmos.internal.changefeed.implementation.ChangeFeedHelper.Paths.DATABASES_ROOT; +import static com.azure.data.cosmos.internal.changefeed.implementation.ChangeFeedHelper.Paths.DOCUMENTS_PATH_SEGMENT; /** * Implement static methods used for various simple transformations and tasks. */ -public class ChangeFeedHelper { +class ChangeFeedHelper { private static final String DEFAULT_USER_AGENT_SUFFIX = "changefeed-2.2.6"; public static final int HTTP_STATUS_CODE_NOT_FOUND = 404; @@ -47,21 +45,6 @@ public class ChangeFeedHelper { public static final int HTTP_STATUS_CODE_TOO_MANY_REQUESTS = 429; public static final int HTTP_STATUS_CODE_INTERNAL_SERVER_ERROR = 500; - public static ContainerConnectionInfo canonicalize(ContainerConnectionInfo leaseCollectionLocation) { - ContainerConnectionInfo result = leaseCollectionLocation; - - if (leaseCollectionLocation == null || leaseCollectionLocation.getConnectionPolicy() == null) { - throw new IllegalArgumentException("leaseCollectionLocation"); - } - if (leaseCollectionLocation.getConnectionPolicy().userAgentSuffix() == null - || leaseCollectionLocation.getConnectionPolicy().userAgentSuffix().isEmpty()) { - result = new ContainerConnectionInfo(leaseCollectionLocation); - result.getConnectionPolicy().userAgentSuffix(DEFAULT_USER_AGENT_SUFFIX); - } - - return result; - } - public static String getDatabaseLink(String databaseName) { return String.format("/dbs/%s", databaseName); } @@ -70,11 +53,6 @@ public static String getCollectionLink(String databaseName, String collectionNam return String.format("/dbs/%s/colls/%s", databaseName, collectionName); } - public static String getCollectionSelfLink(ContainerConnectionInfo collectionInfo) - { - return UriFactory.createDocumentCollectionUri(collectionInfo.getDatabaseName(), collectionInfo.getContainerName()); - } - public static class UriFactory { /** * A database link in the format of "dbs/{0}/". diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java similarity index 91% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java index 6d462d8ef64ac..cbf3fe6939d09 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverContextImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java @@ -20,19 +20,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.changefeed.PartitionCheckpointer; +import com.azure.data.cosmos.internal.changefeed.PartitionCheckpointer; import reactor.core.publisher.Mono; /** * Implementation for ChangeFeedObserverContext. */ -public class ChangeFeedObserverContextImpl implements ChangeFeedObserverContext { +class ChangeFeedObserverContextImpl implements ChangeFeedObserverContext { private final PartitionCheckpointer checkpointer; private final String partitionKeyRangeId; private final FeedResponse feedResponse; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverFactoryImpl.java similarity index 85% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverFactoryImpl.java index a7cf1282c160e..6c218c4caed60 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedObserverFactoryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverFactoryImpl.java @@ -20,11 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedObserverFactory; -import com.azure.data.cosmos.changefeed.exceptions.ObserverException; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverFactory; +import com.azure.data.cosmos.internal.changefeed.exceptions.ObserverException; /** * DEFAULT implementation for {@link ChangeFeedObserverFactory}. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java similarity index 78% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java index b395a103015cc..b874bf4261ec6 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ChangeFeedProcessorBuilderImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java @@ -20,32 +20,36 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedObserverFactory; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverFactory; import com.azure.data.cosmos.ChangeFeedProcessor; import com.azure.data.cosmos.ChangeFeedProcessorOptions; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.changefeed.Bootstrapper; -import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; -import com.azure.data.cosmos.changefeed.HealthMonitor; -import com.azure.data.cosmos.changefeed.LeaseStoreManager; -import com.azure.data.cosmos.changefeed.PartitionController; -import com.azure.data.cosmos.changefeed.PartitionLoadBalancer; -import com.azure.data.cosmos.changefeed.PartitionLoadBalancingStrategy; -import com.azure.data.cosmos.changefeed.PartitionManager; -import com.azure.data.cosmos.changefeed.PartitionProcessor; -import com.azure.data.cosmos.changefeed.PartitionProcessorFactory; -import com.azure.data.cosmos.changefeed.PartitionSupervisorFactory; -import com.azure.data.cosmos.changefeed.RequestOptionsFactory; +import com.azure.data.cosmos.internal.changefeed.Bootstrapper; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.CheckpointFrequency; +import com.azure.data.cosmos.internal.changefeed.HealthMonitor; +import com.azure.data.cosmos.internal.changefeed.LeaseStoreManager; +import com.azure.data.cosmos.internal.changefeed.PartitionController; +import com.azure.data.cosmos.internal.changefeed.PartitionLoadBalancer; +import com.azure.data.cosmos.internal.changefeed.PartitionLoadBalancingStrategy; +import com.azure.data.cosmos.internal.changefeed.PartitionManager; +import com.azure.data.cosmos.internal.changefeed.PartitionProcessor; +import com.azure.data.cosmos.internal.changefeed.PartitionProcessorFactory; +import com.azure.data.cosmos.internal.changefeed.PartitionSupervisorFactory; +import com.azure.data.cosmos.internal.changefeed.RequestOptionsFactory; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import java.net.URI; import java.time.Duration; +import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.function.Consumer; /** * Helper class to build {@link ChangeFeedProcessor} instances @@ -54,10 +58,13 @@ *

  * {@code
  *  ChangeFeedProcessor.Builder()
- *     .withHostName(hostName)
- *     .withFeedContainerClient(feedContainer)
- *     .withLeaseContainerClient(leaseContainer)
- *     .withChangeFeedObserver(SampleObserverImpl.class)
+ *     .hostName(hostName)
+ *     .feedContainerClient(feedContainer)
+ *     .leaseContainerClient(leaseContainer)
+ *     .handleChanges(docs -> {
+ *         // Implementation for handling and processing CosmosItemProperties list goes here
+ *      })
+ *     .observer(SampleObserverImpl.class)
  *     .build();
  * }
  * 
@@ -109,7 +116,7 @@ public Mono stop() { * @return current Builder. */ @Override - public ChangeFeedProcessorBuilderImpl withHostName(String hostName) { + public ChangeFeedProcessorBuilderImpl hostName(String hostName) { this.hostName = hostName; return this; } @@ -121,7 +128,7 @@ public ChangeFeedProcessorBuilderImpl withHostName(String hostName) { * @return current Builder. */ @Override - public ChangeFeedProcessorBuilderImpl withFeedContainerClient(CosmosContainer feedDocumentClient) { + public ChangeFeedProcessorBuilderImpl feedContainerClient(CosmosContainer feedDocumentClient) { if (feedDocumentClient == null) { throw new IllegalArgumentException("feedContextClient"); } @@ -137,13 +144,12 @@ public ChangeFeedProcessorBuilderImpl withFeedContainerClient(CosmosContainer fe * @return current Builder. */ @Override - public ChangeFeedProcessorBuilderImpl withProcessorOptions(ChangeFeedProcessorOptions changeFeedProcessorOptions) { + public ChangeFeedProcessorBuilderImpl options(ChangeFeedProcessorOptions changeFeedProcessorOptions) { if (changeFeedProcessorOptions == null) { throw new IllegalArgumentException("changeFeedProcessorOptions"); } this.changeFeedProcessorOptions = changeFeedProcessorOptions; - this.executorService = changeFeedProcessorOptions.executorService(); return this; } @@ -154,8 +160,7 @@ public ChangeFeedProcessorBuilderImpl withProcessorOptions(ChangeFeedProcessorOp * @param observerFactory The instance of {@link ChangeFeedObserverFactory} to use. * @return current Builder. */ - @Override - public ChangeFeedProcessorBuilderImpl withChangeFeedObserverFactory(ChangeFeedObserverFactory observerFactory) { + public ChangeFeedProcessorBuilderImpl observerFactory(ChangeFeedObserverFactory observerFactory) { if (observerFactory == null) { throw new IllegalArgumentException("observerFactory"); } @@ -169,8 +174,7 @@ public ChangeFeedProcessorBuilderImpl withChangeFeedObserverFactory(ChangeFeedOb * @param type the type of {@link ChangeFeedObserver} to be used. * @return current Builder. */ - @Override - public ChangeFeedProcessorBuilderImpl withChangeFeedObserver(Class type) { + public ChangeFeedProcessorBuilderImpl observer(Class type) { if (type == null) { throw new IllegalArgumentException("type"); } @@ -180,6 +184,11 @@ public ChangeFeedProcessorBuilderImpl withChangeFeedObserver(Class> consumer) { + return this.observerFactory(new DefaultObserverFactory(consumer)); + } + /** * Sets the database resource ID of the monitored collection. * @@ -208,7 +217,7 @@ public ChangeFeedProcessorBuilderImpl withCollectionResourceId(String collection * @return current Builder. */ @Override - public ChangeFeedProcessorBuilderImpl withLeaseContainerClient(CosmosContainer leaseDocumentClient) { + public ChangeFeedProcessorBuilderImpl leaseContainerClient(CosmosContainer leaseDocumentClient) { if (leaseDocumentClient == null) { throw new IllegalArgumentException("leaseContextClient"); } @@ -283,7 +292,7 @@ public ChangeFeedProcessorBuilderImpl withHealthMonitor(HealthMonitor healthMoni * @return an instance of {@link ChangeFeedProcessor}. */ @Override - public Mono build() { + public ChangeFeedProcessor build() { ChangeFeedProcessorBuilderImpl self = this; if (this.hostName == null) @@ -300,11 +309,13 @@ public Mono build() { this.executorService = Executors.newCachedThreadPool(); } - this.initializeCollectionPropertiesForBuild().block(); - LeaseStoreManager leaseStoreManager = this.getLeaseStoreManager().block(); - this.partitionManager = this.buildPartitionManager(leaseStoreManager).block(); - - return Mono.just(this); + // TBD: Move this initialization code as part of the start() call. + return this.initializeCollectionPropertiesForBuild() + .then(self.getLeaseStoreManager().flatMap(leaseStoreManager -> self.buildPartitionManager(leaseStoreManager))) + .map(partitionManager1 -> { + self.partitionManager = partitionManager1; + return self; + }).block(); } public ChangeFeedProcessorBuilderImpl() { @@ -321,31 +332,19 @@ private Mono initializeCollectionPropertiesForBuild() { this.changeFeedProcessorOptions = new ChangeFeedProcessorOptions(); } - if (this.databaseResourceId == null) { - this.feedContextClient - .readDatabase(this.feedContextClient.getDatabaseClient(), null) - .map( databaseResourceResponse -> { - self.databaseResourceId = databaseResourceResponse.database().id(); - return self.databaseResourceId; - }) - .subscribeOn(Schedulers.elastic()) - .then() - .block(); - } - - if (this.collectionResourceId == null) { - self.feedContextClient + return this.feedContextClient + .readDatabase(this.feedContextClient.getDatabaseClient(), null) + .map( databaseResourceResponse -> { + self.databaseResourceId = databaseResourceResponse.database().id(); + return self.databaseResourceId; + }) + .flatMap( id -> self.feedContextClient .readContainer(self.feedContextClient.getContainerClient(), null) .map(documentCollectionResourceResponse -> { self.collectionResourceId = documentCollectionResourceResponse.container().id(); return self.collectionResourceId; - }) - .subscribeOn(Schedulers.elastic()) - .then() - .block(); - } - - return Mono.empty(); + })) + .then(); } private Mono getLeaseStoreManager() { @@ -354,29 +353,31 @@ private Mono getLeaseStoreManager() { if (this.leaseStoreManager == null) { return this.leaseContextClient.readContainerSettings(this.leaseContextClient.getContainerClient(), null) - .map( collectionSettings -> { + .flatMap( collectionSettings -> { boolean isPartitioned = collectionSettings.partitionKey() != null && collectionSettings.partitionKey().paths() != null && collectionSettings.partitionKey().paths().size() > 0; if (!isPartitioned || (collectionSettings.partitionKey().paths().size() != 1 || !collectionSettings.partitionKey().paths().get(0).equals("/id"))) { // throw new IllegalArgumentException("The lease collection, if partitioned, must have partition key equal to id."); - Mono.error(new IllegalArgumentException("The lease collection must have partition key equal to id.")); + return Mono.error(new IllegalArgumentException("The lease collection must have partition key equal to id.")); } RequestOptionsFactory requestOptionsFactory = new PartitionedByIdCollectionRequestOptionsFactory(); String leasePrefix = self.getLeasePrefix(); - self.leaseStoreManager = LeaseStoreManager.Builder() - .withLeasePrefix(leasePrefix) - .withLeaseContextClient(self.leaseContextClient) - .withRequestOptionsFactory(requestOptionsFactory) - .withHostName(self.hostName) + return LeaseStoreManager.Builder() + .leasePrefix(leasePrefix) + .leaseCollectionLink(self.leaseContextClient.getContainerClient()) + .leaseContextClient(self.leaseContextClient) + .requestOptionsFactory(requestOptionsFactory) + .hostName(self.hostName) .build() - .block(); - - return self.leaseStoreManager; + .map(manager -> { + self.leaseStoreManager = manager; + return self.leaseStoreManager; + }); }); } @@ -403,7 +404,7 @@ private String getLeasePrefix() { private Mono buildPartitionManager(LeaseStoreManager leaseStoreManager) { ChangeFeedProcessorBuilderImpl self = this; - CheckpointerObserverFactory factory = new CheckpointerObserverFactory(this.observerFactory, this.changeFeedProcessorOptions.checkpointFrequency()); + CheckpointerObserverFactory factory = new CheckpointerObserverFactory(this.observerFactory, new CheckpointFrequency()); PartitionSynchronizerImpl synchronizer = new PartitionSynchronizerImpl( this.feedContextClient, diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/CheckpointerObserverFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/CheckpointerObserverFactory.java similarity index 87% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/CheckpointerObserverFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/CheckpointerObserverFactory.java index fa85b98b90d81..8d982b76afbf0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/CheckpointerObserverFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/CheckpointerObserverFactory.java @@ -20,16 +20,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedObserverFactory; -import com.azure.data.cosmos.changefeed.CheckpointFrequency; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverFactory; +import com.azure.data.cosmos.internal.changefeed.CheckpointFrequency; /** * Factory class used to create instance(s) of {@link ChangeFeedObserver}. */ -public class CheckpointerObserverFactory implements ChangeFeedObserverFactory { +class CheckpointerObserverFactory implements ChangeFeedObserverFactory { private final ChangeFeedObserverFactory observerFactory; private final CheckpointFrequency checkpointFrequency; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/Constants.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/Constants.java similarity index 99% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/Constants.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/Constants.java index 3c9814a2d9827..8c1ba053b79f2 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/Constants.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/Constants.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; /** * Used internally. Constants in the Azure Cosmos DB database service Java SDK. */ -public final class Constants { +final class Constants { public static final class Quota { // Quota Strings diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserver.java similarity index 59% rename from examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserver.java index 0f12dd70894b1..7b2f609a46279 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleObserverImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserver.java @@ -20,37 +20,40 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.examples.ChangeFeed; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedObserverCloseReason; -import com.azure.data.cosmos.ChangeFeedObserverContext; import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.SerializationFormattingPolicy; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverCloseReason; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; +import java.util.function.Consumer; + +class DefaultObserver implements ChangeFeedObserver { + private final Logger log = LoggerFactory.getLogger(DefaultObserver.class); + private Consumer> consumer; + + public DefaultObserver(Consumer> consumer) { + this.consumer = consumer; + } -/** - * Sample ChangeFeedObserver. - */ -public class SampleObserverImpl implements ChangeFeedObserver { @Override public void open(ChangeFeedObserverContext context) { - System.out.println("--->SampleObserverImpl::open()"); + log.info("Open processing from thread {}", Thread.currentThread().getId()); } @Override public void close(ChangeFeedObserverContext context, ChangeFeedObserverCloseReason reason) { - System.out.println("--->SampleObserverImpl::close() -> " + reason.name()); + log.info("Close processing from thread {}", Thread.currentThread().getId()); } @Override public void processChanges(ChangeFeedObserverContext context, List docs) { - System.out.println("--->SampleObserverImpl::processChanges() START"); - - for (CosmosItemProperties document : docs) { - System.out.println("---->DOCUMENT RECEIVED: " + document.toJson(SerializationFormattingPolicy.INDENTED)); - } - System.out.println("--->SampleObserverImpl::processChanges() END"); + log.info("Start processing from thread {}", Thread.currentThread().getId()); + consumer.accept(docs); + log.info("Done processing from thread {}", Thread.currentThread().getId()); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserverFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserverFactory.java new file mode 100644 index 0000000000000..73b70cf4fd0d9 --- /dev/null +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserverFactory.java @@ -0,0 +1,47 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.internal.changefeed.implementation; + +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.function.Consumer; + +class DefaultObserverFactory implements ChangeFeedObserverFactory { + private final Logger log = LoggerFactory.getLogger(DefaultObserverFactory.class); + + private Consumer> consumer; + + public DefaultObserverFactory(Consumer> consumer) { + this.consumer = consumer; + } + + @Override + public ChangeFeedObserver createObserver() { + return new DefaultObserver(consumer); + } +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseStore.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java similarity index 89% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseStore.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java index 60254fcc80ec1..855369da1e6e3 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/DocumentServiceLeaseStore.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; import com.azure.data.cosmos.AccessCondition; import com.azure.data.cosmos.AccessConditionType; @@ -29,11 +29,10 @@ import com.azure.data.cosmos.CosmosItem; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemRequestOptions; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; -import com.azure.data.cosmos.changefeed.LeaseStore; -import com.azure.data.cosmos.changefeed.RequestOptionsFactory; -import com.azure.data.cosmos.changefeed.ServiceItemLease; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.LeaseStore; +import com.azure.data.cosmos.internal.changefeed.RequestOptionsFactory; +import com.azure.data.cosmos.internal.changefeed.ServiceItemLease; import reactor.core.publisher.Mono; import java.time.Duration; @@ -41,7 +40,7 @@ /** * Implementation for LeaseStore. */ -public class DocumentServiceLeaseStore implements LeaseStore { +class DocumentServiceLeaseStore implements LeaseStore { private ChangeFeedContextClient client; private String containerNamePrefix; private CosmosContainer leaseCollectionLink; @@ -81,8 +80,7 @@ public Mono isInitialized() { return Mono.just(false); } } - Mono.error(throwable); - return Mono.empty(); + return Mono.error(throwable); }); } @@ -108,9 +106,10 @@ public Mono markInitialized() { @Override public Mono acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); - Document containerDocument = new Document(); + CosmosItemProperties containerDocument = new CosmosItemProperties(); containerDocument.id(lockId); - containerDocument.setTimeToLive(Long.valueOf(lockExpirationTime.getSeconds()).intValue()); + containerDocument.set(com.azure.data.cosmos.internal.Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); + DocumentServiceLeaseStore self = this; return this.client.createItem(this.leaseCollectionLink, containerDocument, null, false) @@ -129,8 +128,7 @@ public Mono acquireInitializationLock(Duration lockExpirationTime) { return Mono.just(false); } } - Mono.error(throwable); - return Mono.empty(); + return Mono.error(throwable); }); } @@ -171,8 +169,7 @@ public Mono releaseInitializationLock() { } } - Mono.error(throwable); - return Mono.empty(); + return Mono.error(throwable); }); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseUpdaterImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseUpdaterImpl.java new file mode 100644 index 0000000000000..eee04010a4c19 --- /dev/null +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseUpdaterImpl.java @@ -0,0 +1,204 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.internal.changefeed.implementation; + +import com.azure.data.cosmos.AccessCondition; +import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosItem; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.CosmosItemRequestOptions; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.ServiceItemLease; +import com.azure.data.cosmos.internal.changefeed.ServiceItemLeaseUpdater; +import com.azure.data.cosmos.internal.changefeed.exceptions.LeaseLostException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.Exceptions; +import reactor.core.publisher.Mono; + +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.function.Function; + +import static com.azure.data.cosmos.internal.changefeed.implementation.ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT; +import static com.azure.data.cosmos.internal.changefeed.implementation.ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND; +import static com.azure.data.cosmos.internal.changefeed.implementation.ChangeFeedHelper.HTTP_STATUS_CODE_PRECONDITION_FAILED; + +/** + * Implementation for service lease updater interface. + */ +class DocumentServiceLeaseUpdaterImpl implements ServiceItemLeaseUpdater { + private final Logger logger = LoggerFactory.getLogger(DocumentServiceLeaseUpdaterImpl.class); + private final int RETRY_COUNT_ON_CONFLICT = 5; + private final ChangeFeedContextClient client; + + public DocumentServiceLeaseUpdaterImpl(ChangeFeedContextClient client) { + if (client == null) { + throw new IllegalArgumentException("client"); + } + + this.client = client; + } + + @Override + public Mono updateLease(Lease cachedLease, CosmosItem itemLink, CosmosItemRequestOptions requestOptions, Function updateLease) { + DocumentServiceLeaseUpdaterImpl self = this; + Lease arrayLease[] = {cachedLease}; + arrayLease[0] = updateLease.apply(cachedLease); + + if (arrayLease[0] == null) { + return Mono.empty(); + } + + arrayLease[0].setTimestamp(ZonedDateTime.now(ZoneId.of("UTC"))); + + return self.tryReplaceLease(arrayLease[0], itemLink) + .map(leaseDocument -> { + arrayLease[0] = ServiceItemLease.fromDocument(leaseDocument); + return arrayLease[0]; + }) + .hasElement() + .flatMap(hasItems -> { + if (hasItems) { + return Mono.just(arrayLease[0]); + } + // Partition lease update conflict. Reading the current version of lease. + return this.client.readItem(itemLink, requestOptions) + .onErrorResume(throwable -> { + if (throwable instanceof CosmosClientException) { + CosmosClientException ex = (CosmosClientException) throwable; + if (ex.statusCode() == HTTP_STATUS_CODE_NOT_FOUND) { + // Partition lease no longer exists + throw Exceptions.propagate(new LeaseLostException(arrayLease[0])); + } + } + return Mono.error(throwable); + }) + .map(cosmosItemResponse -> { + CosmosItemProperties document = cosmosItemResponse.properties(); + ServiceItemLease serverLease = ServiceItemLease.fromDocument(document); + logger.info( + "Partition {} update failed because the lease with token '{}' was updated by host '{}' with token '{}'.", + arrayLease[0].getLeaseToken(), + arrayLease[0].getConcurrencyToken(), + serverLease.getOwner(), + serverLease.getConcurrencyToken()); + arrayLease[0] = serverLease; + + throw Exceptions.propagate(new RuntimeException("")); + }); + }) + .retry(RETRY_COUNT_ON_CONFLICT, throwable -> { + if (throwable instanceof RuntimeException) { + return throwable instanceof LeaseLostException; + } + return false; + }); + +// Lease lease = cachedLease; +// +// for (int retryCount = RETRY_COUNT_ON_CONFLICT; retryCount > 0; retryCount--) { +// lease = updateLease.apply(lease); +// +// if (lease == null) { +// return Mono.empty(); +// } +// +// lease.setTimestamp(ZonedDateTime.now(ZoneId.of("UTC"))); +// CosmosItemProperties leaseDocument = this.tryReplaceLease(lease, itemLink).block(); +// +// if (leaseDocument != null) { +// return Mono.just(ServiceItemLease.fromDocument(leaseDocument)); +// } +// +// // Partition lease update conflict. Reading the current version of lease. +// CosmosItemProperties document = null; +// try { +// CosmosItemResponse response = this.client.readItem(itemLink, requestOptions) +// .block(); +// document = response.properties(); +// } catch (RuntimeException re) { +// if (re.getCause() instanceof CosmosClientException) { +// CosmosClientException ex = (CosmosClientException) re.getCause(); +// if (ex.statusCode() == HTTP_STATUS_CODE_NOT_FOUND) { +// // Partition lease no longer exists +// throw new LeaseLostException(lease); +// } +// } +// throw re; +// } +// +// ServiceItemLease serverLease = ServiceItemLease.fromDocument(document); +// logger.info( +// "Partition {} update failed because the lease with token '{}' was updated by host '{}' with token '{}'. Will retry, {} retry(s) left.", +// lease.getLeaseToken(), +// lease.getConcurrencyToken(), +// serverLease.getOwner(), +// serverLease.getConcurrencyToken(), +// retryCount); +// +// lease = serverLease; +// } +// +// throw new LeaseLostException(lease); + } + + private Mono tryReplaceLease(Lease lease, CosmosItem itemLink) throws LeaseLostException { + DocumentServiceLeaseUpdaterImpl self = this; + return this.client.replaceItem(itemLink, lease, this.getCreateIfMatchOptions(lease)) + .map(cosmosItemResponse -> cosmosItemResponse.properties()) + .onErrorResume(re -> { + if (re instanceof CosmosClientException) { + CosmosClientException ex = (CosmosClientException) re; + switch (ex.statusCode()) { + case HTTP_STATUS_CODE_PRECONDITION_FAILED: { + return Mono.empty(); + } + case HTTP_STATUS_CODE_CONFLICT: { + throw Exceptions.propagate( new LeaseLostException(lease, ex, false)); + } + case HTTP_STATUS_CODE_NOT_FOUND: { + throw Exceptions.propagate( new LeaseLostException(lease, ex, true)); + } + default: { + return Mono.error(re); + } + } + } + return Mono.error(re); + }); + } + + private CosmosItemRequestOptions getCreateIfMatchOptions(Lease lease) { + AccessCondition ifMatchCondition = new AccessCondition(); + ifMatchCondition.type(AccessConditionType.IF_MATCH); + ifMatchCondition.condition(lease.getConcurrencyToken()); + + CosmosItemRequestOptions createIfMatchOptions = new CosmosItemRequestOptions(); + createIfMatchOptions.accessCondition(ifMatchCondition); + + return createIfMatchOptions; + } +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java index 3b671beaf867b..bb3942f7a8329 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/EqualPartitionsBalancingStrategy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.PartitionLoadBalancingStrategy; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.PartitionLoadBalancingStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,7 +38,7 @@ /** * Implementation for {@link PartitionLoadBalancingStrategy}. */ -public class EqualPartitionsBalancingStrategy implements PartitionLoadBalancingStrategy { +class EqualPartitionsBalancingStrategy implements PartitionLoadBalancingStrategy { private final Logger logger = LoggerFactory.getLogger(EqualPartitionsBalancingStrategy.class); private final String hostName; private final int minPartitionCount; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ExceptionClassifier.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ExceptionClassifier.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ExceptionClassifier.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ExceptionClassifier.java index 950d74b6cb238..f6b9468690907 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ExceptionClassifier.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ExceptionClassifier.java @@ -20,14 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; import com.azure.data.cosmos.CosmosClientException; /** * Classifies exceptions based on the status codes. */ -public class ExceptionClassifier { +class ExceptionClassifier { public static final int SubStatusCode_Undefined = -1; // 410: partition key range is gone. diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/HealthMonitoringPartitionControllerDecorator.java similarity index 85% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/HealthMonitoringPartitionControllerDecorator.java index 7756d54e7ddb9..8ea9440903f46 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/HealthMonitoringPartitionControllerDecorator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/HealthMonitoringPartitionControllerDecorator.java @@ -20,19 +20,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.changefeed.HealthMonitor; -import com.azure.data.cosmos.changefeed.HealthMonitoringRecord; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.PartitionController; +import com.azure.data.cosmos.internal.changefeed.HealthMonitor; +import com.azure.data.cosmos.internal.changefeed.HealthMonitoringRecord; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.PartitionController; import reactor.core.publisher.Mono; /** * Monitors partition controller health. */ -public class HealthMonitoringPartitionControllerDecorator implements PartitionController { +class HealthMonitoringPartitionControllerDecorator implements PartitionController { private final PartitionController inner; private final HealthMonitor monitor; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseRenewerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseRenewerImpl.java similarity index 91% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseRenewerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseRenewerImpl.java index a6b7ef61ca05d..dddba5eb9d257 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseRenewerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseRenewerImpl.java @@ -20,13 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.changefeed.CancellationToken; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.LeaseManager; -import com.azure.data.cosmos.changefeed.LeaseRenewer; -import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.internal.changefeed.CancellationToken; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.LeaseManager; +import com.azure.data.cosmos.internal.changefeed.LeaseRenewer; +import com.azure.data.cosmos.internal.changefeed.exceptions.LeaseLostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -36,7 +36,7 @@ /** * Implementation for the {@link LeaseRenewer}. */ -public class LeaseRenewerImpl implements LeaseRenewer { +class LeaseRenewerImpl implements LeaseRenewer { private final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseStoreManagerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java similarity index 79% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseStoreManagerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java index 426640a6079ee..ad0f0ba3ddec2 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/LeaseStoreManagerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; @@ -30,17 +30,18 @@ import com.azure.data.cosmos.SqlParameter; import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.LeaseStore; -import com.azure.data.cosmos.changefeed.LeaseStoreManager; -import com.azure.data.cosmos.changefeed.LeaseStoreManagerSettings; -import com.azure.data.cosmos.changefeed.RequestOptionsFactory; -import com.azure.data.cosmos.changefeed.ServiceItemLease; -import com.azure.data.cosmos.changefeed.ServiceItemLeaseUpdater; -import com.azure.data.cosmos.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.LeaseStore; +import com.azure.data.cosmos.internal.changefeed.LeaseStoreManager; +import com.azure.data.cosmos.internal.changefeed.LeaseStoreManagerSettings; +import com.azure.data.cosmos.internal.changefeed.RequestOptionsFactory; +import com.azure.data.cosmos.internal.changefeed.ServiceItemLease; +import com.azure.data.cosmos.internal.changefeed.ServiceItemLeaseUpdater; +import com.azure.data.cosmos.internal.changefeed.exceptions.LeaseLostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import reactor.core.Exceptions; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -69,9 +70,9 @@ public LeaseStoreManagerImpl() { } @Override - public LeaseStoreManagerBuilderDefinition withLeaseContextClient(ChangeFeedContextClient leaseContextClient) { - if (leaseDocumentClient == null) { - throw new IllegalArgumentException("leaseDocumentClient"); + public LeaseStoreManagerBuilderDefinition leaseContextClient(ChangeFeedContextClient leaseContextClient) { + if (leaseContextClient == null) { + throw new IllegalArgumentException("leaseContextClient"); } this.leaseDocumentClient = leaseContextClient; @@ -79,7 +80,7 @@ public LeaseStoreManagerBuilderDefinition withLeaseContextClient(ChangeFeedConte } @Override - public LeaseStoreManagerBuilderDefinition withLeasePrefix(String leasePrefix) { + public LeaseStoreManagerBuilderDefinition leasePrefix(String leasePrefix) { if (leasePrefix == null) { throw new IllegalArgumentException("leasePrefix"); } @@ -89,7 +90,7 @@ public LeaseStoreManagerBuilderDefinition withLeasePrefix(String leasePrefix) { } @Override - public LeaseStoreManagerBuilderDefinition withLeaseCollectionLink(CosmosContainer leaseCollectionLink) { + public LeaseStoreManagerBuilderDefinition leaseCollectionLink(CosmosContainer leaseCollectionLink) { if (leaseCollectionLink == null) { throw new IllegalArgumentException("leaseCollectionLink"); } @@ -99,7 +100,7 @@ public LeaseStoreManagerBuilderDefinition withLeaseCollectionLink(CosmosContaine } @Override - public LeaseStoreManagerBuilderDefinition withRequestOptionsFactory(RequestOptionsFactory requestOptionsFactory) { + public LeaseStoreManagerBuilderDefinition requestOptionsFactory(RequestOptionsFactory requestOptionsFactory) { if (requestOptionsFactory == null) { throw new IllegalArgumentException("requestOptionsFactory"); } @@ -109,7 +110,7 @@ public LeaseStoreManagerBuilderDefinition withRequestOptionsFactory(RequestOptio } @Override - public LeaseStoreManagerBuilderDefinition withHostName(String hostName) { + public LeaseStoreManagerBuilderDefinition hostName(String hostName) { if (hostName == null) { throw new IllegalArgumentException("hostName"); } @@ -173,29 +174,30 @@ public Mono createLeaseIfNotExist(String leaseToken, String continuationT if (ex instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) ex; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { - //Logger.InfoFormat("Some other host created lease for {0}.", leaseToken); + logger.info("Some other host created lease for {}.", leaseToken); return Mono.empty(); } } - Mono.error(ex); - return Mono.empty(); + return Mono.error(ex); }) .map(documentResourceResponse -> { if (documentResourceResponse == null) return null; CosmosItemProperties document = documentResourceResponse.properties(); + + logger.info("Created lease for partition {}.", leaseToken); + return documentServiceLease .withId(document.id()) .withEtag(document.etag()) .withTs(document.getString(Constants.Properties.LAST_MODIFIED)); }); - //Logger.InfoFormat("Created lease for partition {0}.", leaseToken); } @Override public Mono delete(Lease lease) { - if (lease == null || lease.getId() == null) throw new IllegalArgumentException("lease"); + if (lease == null || lease.getId() == null) throw Exceptions.propagate(new IllegalArgumentException("lease")); CosmosItem itemForLease = this.createItemForLease(lease.getId()); @@ -210,8 +212,7 @@ public Mono delete(Lease lease) { } } - Mono.error(ex); - return Mono.empty(); + return Mono.error(ex); }) // return some add-hoc value since we don't actually care about the result. .map( documentResourceResponse -> true) @@ -220,7 +221,7 @@ public Mono delete(Lease lease) { @Override public Mono acquire(Lease lease) { - if (lease == null) throw new IllegalArgumentException("lease"); + if (lease == null) throw Exceptions.propagate(new IllegalArgumentException("lease")); String oldOwner = lease.getOwner(); @@ -230,8 +231,8 @@ public Mono acquire(Lease lease) { this.requestOptionsFactory.createRequestOptions(lease), serverLease -> { if (serverLease.getOwner() != null && !serverLease.getOwner().equalsIgnoreCase(oldOwner)) { - // Logger.InfoFormat("Partition {0} lease was taken over by owner '{1}'", lease.LeaseToken, serverLease.Owner); - Mono.error(new LeaseLostException(lease)); + logger.info("Partition {} lease was taken over by owner '{}'", lease.getLeaseToken(), serverLease.getOwner()); + throw Exceptions.propagate(new LeaseLostException(lease)); } serverLease.setOwner(this.settings.getHostName()); serverLease.setProperties(lease.getProperties()); @@ -242,7 +243,7 @@ public Mono acquire(Lease lease) { @Override public Mono release(Lease lease) { - if (lease == null) throw new IllegalArgumentException("lease"); + if (lease == null) throw Exceptions.propagate(new IllegalArgumentException("lease")); CosmosItem itemForLease = this.createItemForLease(lease.getId()); LeaseStoreManagerImpl self = this; @@ -252,13 +253,12 @@ public Mono release(Lease lease) { if (ex instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) ex; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND) { - // Logger.InfoFormat("Partition {0} failed to renew lease. The lease is gone already.", lease.LeaseToken); - Mono.error(new LeaseLostException(lease)); + logger.info("Partition {} failed to renew lease. The lease is gone already.", lease.getLeaseToken()); + throw Exceptions.propagate(new LeaseLostException(lease)); } } - Mono.error(ex); - return Mono.empty(); + return Mono.error(ex); }) .map( documentResourceResponse -> ServiceItemLease.fromDocument(documentResourceResponse.properties())) .flatMap( refreshedLease -> self.leaseUpdater.updateLease( @@ -268,8 +268,8 @@ public Mono release(Lease lease) { serverLease -> { if (!serverLease.getOwner().equalsIgnoreCase(lease.getOwner())) { - //Logger.InfoFormat("Partition {0} no need to release lease. The lease was already taken by another host '{1}'.", lease.LeaseToken, serverLease.Owner); - Mono.error(new LeaseLostException(lease)); + logger.info("Partition {} no need to release lease. The lease was already taken by another host '{}'.", lease.getLeaseToken(), serverLease.getOwner()); + throw Exceptions.propagate(new LeaseLostException(lease)); } serverLease.setOwner(null); @@ -281,7 +281,7 @@ public Mono release(Lease lease) { @Override public Mono renew(Lease lease) { - if (lease == null) throw new IllegalArgumentException("lease"); + if (lease == null) throw Exceptions.propagate(new IllegalArgumentException("lease")); // Get fresh lease. The assumption here is that check-pointing is done with higher frequency than lease renewal so almost // certainly the lease was updated in between. @@ -293,13 +293,12 @@ public Mono renew(Lease lease) { if (ex instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) ex; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_NOT_FOUND) { - // Logger.InfoFormat("Partition {0} failed to renew lease. The lease is gone already.", lease.LeaseToken); - Mono.error(new LeaseLostException(lease)); + logger.info("Partition {} failed to renew lease. The lease is gone already.", lease.getLeaseToken()); + throw Exceptions.propagate(new LeaseLostException(lease)); } } - Mono.error(ex); - return Mono.empty(); + return Mono.error(ex); }) .map( documentResourceResponse -> ServiceItemLease.fromDocument(documentResourceResponse.properties())) .flatMap( refreshedLease -> self.leaseUpdater.updateLease( @@ -309,8 +308,8 @@ public Mono renew(Lease lease) { serverLease -> { if (!serverLease.getOwner().equalsIgnoreCase(lease.getOwner())) { - // Logger.InfoFormat("Partition {0} lease was taken over by owner '{1}'", lease.LeaseToken, serverLease.Owner); - Mono.error(new LeaseLostException(lease)); + logger.info("Partition {} lease was taken over by owner '{}'", lease.getLeaseToken(), serverLease.getOwner()); + throw Exceptions.propagate(new LeaseLostException(lease)); } return serverLease; @@ -320,12 +319,12 @@ public Mono renew(Lease lease) { @Override public Mono updateProperties(Lease lease) { - if (lease == null) throw new IllegalArgumentException("lease"); + if (lease == null) throw Exceptions.propagate(new IllegalArgumentException("lease")); if (!lease.getOwner().equalsIgnoreCase(this.settings.getHostName())) { - // Logger.InfoFormat("Partition '{0}' lease was taken over by owner '{1}' before lease item update", lease.LeaseToken, lease.Owner); - Mono.error(new LeaseLostException(lease)); + logger.info("Partition '{}' lease was taken over by owner '{}' before lease item update", lease.getLeaseToken(), lease.getOwner()); + throw new LeaseLostException(lease); } return this.leaseUpdater.updateLease( @@ -334,8 +333,8 @@ public Mono updateProperties(Lease lease) { this.requestOptionsFactory.createRequestOptions(lease), serverLease -> { if (!serverLease.getOwner().equalsIgnoreCase(lease.getOwner())) { - // Logger.InfoFormat("Partition '{0}' lease was taken over by owner '{1}'", lease.LeaseToken, serverLease.Owner); - Mono.error(new LeaseLostException(lease)); + logger.info("Partition '{}' lease was taken over by owner '{}'", lease.getLeaseToken(), serverLease.getOwner()); + throw Exceptions.propagate(new LeaseLostException(lease)); } serverLease.setProperties(lease.getProperties()); return serverLease; @@ -344,7 +343,7 @@ public Mono updateProperties(Lease lease) { @Override public Mono checkpoint(Lease lease, String continuationToken) { - if (lease == null) throw new IllegalArgumentException("lease"); + if (lease == null) throw Exceptions.propagate(new IllegalArgumentException("lease")); if (continuationToken == null || continuationToken.isEmpty()) { throw new IllegalArgumentException("continuationToken must be a non-empty string"); @@ -356,8 +355,8 @@ public Mono checkpoint(Lease lease, String continuationToken) { this.requestOptionsFactory.createRequestOptions(lease), serverLease -> { if (serverLease.getOwner() != null && !serverLease.getOwner().equalsIgnoreCase(lease.getOwner())) { - //Logger.InfoFormat("Partition {0} lease was taken over by owner '{1}'", lease.LeaseToken, serverLease.Owner); - Mono.error(new LeaseLostException(lease)); + logger.info("Partition {} lease was taken over by owner '{}'", lease.getLeaseToken(), serverLease.getOwner()); + throw Exceptions.propagate(new LeaseLostException(lease)); } serverLease.setContinuationToken(continuationToken); @@ -397,8 +396,7 @@ private Mono tryGetLease(Lease lease) { } } - Mono.error(ex); - return Mono.empty(); + return Mono.error(ex); }) .map( documentResourceResponse -> { if (documentResourceResponse == null) return null; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java similarity index 85% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java index 76f36ef92ccf2..d908f6f25c328 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/ObserverExceptionWrappingChangeFeedObserverDecorator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java @@ -20,20 +20,20 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedObserverCloseReason; -import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverCloseReason; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.changefeed.exceptions.ObserverException; +import com.azure.data.cosmos.internal.changefeed.exceptions.ObserverException; import java.util.List; /** * Exception wrapping decorator implementation for {@link ChangeFeedObserver}. */ -public class ObserverExceptionWrappingChangeFeedObserverDecorator implements ChangeFeedObserver { +class ObserverExceptionWrappingChangeFeedObserverDecorator implements ChangeFeedObserver { private ChangeFeedObserver changeFeedObserver; public ObserverExceptionWrappingChangeFeedObserverDecorator(ChangeFeedObserver changeFeedObserver) diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionCheckpointerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionCheckpointerImpl.java similarity index 86% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionCheckpointerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionCheckpointerImpl.java index 9b9f576799854..08519d7c4dedb 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionCheckpointerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionCheckpointerImpl.java @@ -20,11 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.LeaseCheckpointer; -import com.azure.data.cosmos.changefeed.PartitionCheckpointer; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.LeaseCheckpointer; +import com.azure.data.cosmos.internal.changefeed.PartitionCheckpointer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -32,7 +32,7 @@ /** * Checkpoint the given partition up to the given continuation token. */ -public class PartitionCheckpointerImpl implements PartitionCheckpointer { +class PartitionCheckpointerImpl implements PartitionCheckpointer { private final Logger logger = LoggerFactory.getLogger(PartitionCheckpointerImpl.class); private final LeaseCheckpointer leaseCheckpointer; private Lease lease; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionControllerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionControllerImpl.java similarity index 71% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionControllerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionControllerImpl.java index b53cce50cd806..b290114d48dc0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionControllerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionControllerImpl.java @@ -20,19 +20,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; - -import com.azure.data.cosmos.changefeed.CancellationToken; -import com.azure.data.cosmos.changefeed.CancellationTokenSource; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.LeaseContainer; -import com.azure.data.cosmos.changefeed.LeaseManager; -import com.azure.data.cosmos.changefeed.PartitionController; -import com.azure.data.cosmos.changefeed.PartitionSupervisor; -import com.azure.data.cosmos.changefeed.PartitionSupervisorFactory; -import com.azure.data.cosmos.changefeed.PartitionSynchronizer; -import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; -import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; +package com.azure.data.cosmos.internal.changefeed.implementation; + +import com.azure.data.cosmos.internal.changefeed.CancellationToken; +import com.azure.data.cosmos.internal.changefeed.CancellationTokenSource; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.LeaseContainer; +import com.azure.data.cosmos.internal.changefeed.LeaseManager; +import com.azure.data.cosmos.internal.changefeed.PartitionController; +import com.azure.data.cosmos.internal.changefeed.PartitionSupervisor; +import com.azure.data.cosmos.internal.changefeed.PartitionSupervisorFactory; +import com.azure.data.cosmos.internal.changefeed.PartitionSynchronizer; +import com.azure.data.cosmos.internal.changefeed.exceptions.PartitionSplitException; +import com.azure.data.cosmos.internal.changefeed.exceptions.TaskCancelledException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -44,9 +44,8 @@ /** * Implementation for {@link PartitionController}. */ -public class PartitionControllerImpl implements PartitionController { +class PartitionControllerImpl implements PartitionController { private final Logger logger = LoggerFactory.getLogger(PartitionControllerImpl.class); - // private final Map currentlyOwnedPartitions = new ConcurrentHashMap(); private final Map currentlyOwnedPartitions = new ConcurrentHashMap<>(); private final LeaseContainer leaseContainer; @@ -123,7 +122,6 @@ private Mono loadLeases() { } private Mono removeLease(Lease lease) { - return Mono.fromRunnable(() -> { if (this.currentlyOwnedPartitions.get(lease.getLeaseToken()) != null) { WorkerTask workerTask = this.currentlyOwnedPartitions.remove(lease.getLeaseToken()); @@ -132,16 +130,16 @@ private Mono removeLease(Lease lease) { } logger.info(String.format("Partition %s: released.", lease.getLeaseToken())); - - try { - this.leaseManager.release(lease).block(); - } catch (Exception e) { - logger.warn(String.format("Partition %s: failed to remove lease.", lease.getLeaseToken()), e); - } finally { - // TODO: Stop the corresponding threads. - } } - }); + + return this.leaseManager.release(lease) + .onErrorResume(e -> { + logger.warn(String.format("Partition %s: failed to remove lease.", lease.getLeaseToken()), e); + return Mono.empty(); + } + ).doOnSuccess(aVoid -> { + logger.info("Partition {}: successfully removed lease.", lease.getLeaseToken()); + }); } private WorkerTask processPartition(PartitionSupervisor partitionSupervisor, Lease lease) { @@ -149,19 +147,22 @@ private WorkerTask processPartition(PartitionSupervisor partitionSupervisor, Lea CancellationToken cancellationToken = this.shutdownCts.getToken(); - WorkerTask partitionSupervisorTask = new WorkerTask(Mono.fromRunnable( () -> { - try { - partitionSupervisor.run(cancellationToken).block(); - } catch (PartitionSplitException ex) { - self.handleSplit(lease, ex.getLastContinuation()).block(); - } catch (TaskCancelledException tcex) { - logger.debug(String.format("Partition %s: processing canceled.", lease.getLeaseToken())); - } catch (Exception e) { - logger.warn(String.format("Partition %s: processing failed.", lease.getLeaseToken()), e); - } - - self.removeLease(lease).block(); - })); + WorkerTask partitionSupervisorTask = new WorkerTask(lease, () -> { + partitionSupervisor.run(cancellationToken) + .onErrorResume(throwable -> { + if (throwable instanceof PartitionSplitException) { + PartitionSplitException ex = (PartitionSplitException) throwable; + return self.handleSplit(lease, ex.getLastContinuation()); + } else if (throwable instanceof TaskCancelledException) { + logger.debug(String.format("Partition %s: processing canceled.", lease.getLeaseToken())); + } else { + logger.warn(String.format("Partition %s: processing failed.", lease.getLeaseToken()), throwable); + } + + return Mono.empty(); + }) + .then(self.removeLease(lease)).subscribe(); + }); this.executorService.execute(partitionSupervisorTask); diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionLoadBalancerImpl.java similarity index 87% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionLoadBalancerImpl.java index fdab39a5cd084..316a9fbce4231 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionLoadBalancerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionLoadBalancerImpl.java @@ -20,15 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; - -import com.azure.data.cosmos.changefeed.CancellationToken; -import com.azure.data.cosmos.changefeed.CancellationTokenSource; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.LeaseContainer; -import com.azure.data.cosmos.changefeed.PartitionController; -import com.azure.data.cosmos.changefeed.PartitionLoadBalancer; -import com.azure.data.cosmos.changefeed.PartitionLoadBalancingStrategy; +package com.azure.data.cosmos.internal.changefeed.implementation; + +import com.azure.data.cosmos.internal.changefeed.CancellationToken; +import com.azure.data.cosmos.internal.changefeed.CancellationTokenSource; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.LeaseContainer; +import com.azure.data.cosmos.internal.changefeed.PartitionController; +import com.azure.data.cosmos.internal.changefeed.PartitionLoadBalancer; +import com.azure.data.cosmos.internal.changefeed.PartitionLoadBalancingStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -40,7 +40,7 @@ /** * Implementation for {@link PartitionLoadBalancer}. */ -public class PartitionLoadBalancerImpl implements PartitionLoadBalancer { +class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; @@ -101,11 +101,11 @@ public Mono stop() { return Mono.fromRunnable( () -> { synchronized (lock) { this.started = false; - this.cancellationTokenSource.cancel(); - this.partitionController.shutdown().block(); - this.cancellationTokenSource = null; } + + this.partitionController.shutdown().block(); + this.cancellationTokenSource = null; }); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionManagerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionManagerImpl.java similarity index 76% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionManagerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionManagerImpl.java index f383ccfbb1b5f..3ca256c544573 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionManagerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionManagerImpl.java @@ -20,18 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.changefeed.Bootstrapper; -import com.azure.data.cosmos.changefeed.PartitionController; -import com.azure.data.cosmos.changefeed.PartitionLoadBalancer; -import com.azure.data.cosmos.changefeed.PartitionManager; +import com.azure.data.cosmos.internal.changefeed.Bootstrapper; +import com.azure.data.cosmos.internal.changefeed.PartitionController; +import com.azure.data.cosmos.internal.changefeed.PartitionLoadBalancer; +import com.azure.data.cosmos.internal.changefeed.PartitionManager; import reactor.core.publisher.Mono; /** * Implementation for {@link PartitionManager}. */ -public class PartitionManagerImpl implements PartitionManager { +class PartitionManagerImpl implements PartitionManager { private final Bootstrapper bootstrapper; private final PartitionController partitionController; private final PartitionLoadBalancer partitionLoadBalancer; @@ -46,14 +46,14 @@ public PartitionManagerImpl(Bootstrapper bootstrapper, PartitionController parti public Mono start() { PartitionManagerImpl self = this; - return this.bootstrapper.initialize() - .then(this.partitionController.initialize()) - .then(Mono.fromRunnable(self.partitionLoadBalancer::start)); + return self.bootstrapper.initialize() + .then(self.partitionController.initialize()) + .then(self.partitionLoadBalancer.start()); } @Override public Mono stop() { PartitionManagerImpl self = this; - return Mono.fromRunnable(self.partitionLoadBalancer::stop); + return self.partitionLoadBalancer.stop(); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java similarity index 84% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java index 7371bd77730c2..6d0a1d00d2d8a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorFactoryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java @@ -20,23 +20,23 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; import com.azure.data.cosmos.ChangeFeedProcessorOptions; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.LeaseCheckpointer; -import com.azure.data.cosmos.changefeed.PartitionCheckpointer; -import com.azure.data.cosmos.changefeed.PartitionProcessor; -import com.azure.data.cosmos.changefeed.PartitionProcessorFactory; -import com.azure.data.cosmos.changefeed.ProcessorSettings; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.LeaseCheckpointer; +import com.azure.data.cosmos.internal.changefeed.PartitionCheckpointer; +import com.azure.data.cosmos.internal.changefeed.PartitionProcessor; +import com.azure.data.cosmos.internal.changefeed.PartitionProcessorFactory; +import com.azure.data.cosmos.internal.changefeed.ProcessorSettings; /** * Implementation for {@link PartitionProcessorFactory}. */ -public class PartitionProcessorFactoryImpl implements PartitionProcessorFactory { +class PartitionProcessorFactoryImpl implements PartitionProcessorFactory { private final ChangeFeedContextClient documentClient; private final ChangeFeedProcessorOptions changeFeedProcessorOptions; private final LeaseCheckpointer leaseCheckpointer; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java similarity index 90% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java index e596806cf47f1..e9d3b9c1cef9f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionProcessorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java @@ -20,22 +20,22 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedObserverContext; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.changefeed.CancellationToken; -import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; -import com.azure.data.cosmos.changefeed.PartitionCheckpointer; -import com.azure.data.cosmos.changefeed.PartitionProcessor; -import com.azure.data.cosmos.changefeed.ProcessorSettings; -import com.azure.data.cosmos.changefeed.exceptions.PartitionNotFoundException; -import com.azure.data.cosmos.changefeed.exceptions.PartitionSplitException; -import com.azure.data.cosmos.changefeed.exceptions.TaskCancelledException; +import com.azure.data.cosmos.internal.changefeed.CancellationToken; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.PartitionCheckpointer; +import com.azure.data.cosmos.internal.changefeed.PartitionProcessor; +import com.azure.data.cosmos.internal.changefeed.ProcessorSettings; +import com.azure.data.cosmos.internal.changefeed.exceptions.PartitionNotFoundException; +import com.azure.data.cosmos.internal.changefeed.exceptions.PartitionSplitException; +import com.azure.data.cosmos.internal.changefeed.exceptions.TaskCancelledException; import reactor.core.publisher.Mono; import java.time.Duration; @@ -44,7 +44,7 @@ /** * Implementation for {@link PartitionProcessor}. */ -public class PartitionProcessorImpl implements PartitionProcessor { +class PartitionProcessorImpl implements PartitionProcessor { private static final int DefaultMaxItemCount = 100; // private final Observable> query; private final ProcessorSettings settings; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java similarity index 80% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java index 8830f758f9529..c9414d8a71cb4 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSupervisorFactoryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java @@ -20,25 +20,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.ChangeFeedObserver; -import com.azure.data.cosmos.ChangeFeedObserverFactory; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverFactory; import com.azure.data.cosmos.ChangeFeedProcessorOptions; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.LeaseManager; -import com.azure.data.cosmos.changefeed.LeaseRenewer; -import com.azure.data.cosmos.changefeed.PartitionProcessor; -import com.azure.data.cosmos.changefeed.PartitionProcessorFactory; -import com.azure.data.cosmos.changefeed.PartitionSupervisor; -import com.azure.data.cosmos.changefeed.PartitionSupervisorFactory; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.LeaseManager; +import com.azure.data.cosmos.internal.changefeed.LeaseRenewer; +import com.azure.data.cosmos.internal.changefeed.PartitionProcessor; +import com.azure.data.cosmos.internal.changefeed.PartitionProcessorFactory; +import com.azure.data.cosmos.internal.changefeed.PartitionSupervisor; +import com.azure.data.cosmos.internal.changefeed.PartitionSupervisorFactory; import java.util.concurrent.ExecutorService; /** * Implementation for the partition supervisor factory. */ -public class PartitionSupervisorFactoryImpl implements PartitionSupervisorFactory { +class PartitionSupervisorFactoryImpl implements PartitionSupervisorFactory { private final ChangeFeedObserverFactory observerFactory; private final LeaseManager leaseManager; private final ChangeFeedProcessorOptions changeFeedProcessorOptions; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java new file mode 100644 index 0000000000000..70dfd1a3c48f5 --- /dev/null +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java @@ -0,0 +1,167 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.internal.changefeed.implementation; + +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverCloseReason; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; +import com.azure.data.cosmos.internal.changefeed.CancellationToken; +import com.azure.data.cosmos.internal.changefeed.CancellationTokenSource; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.LeaseRenewer; +import com.azure.data.cosmos.internal.changefeed.PartitionProcessor; +import com.azure.data.cosmos.internal.changefeed.PartitionSupervisor; +import com.azure.data.cosmos.internal.changefeed.exceptions.LeaseLostException; +import com.azure.data.cosmos.internal.changefeed.exceptions.ObserverException; +import com.azure.data.cosmos.internal.changefeed.exceptions.PartitionSplitException; +import com.azure.data.cosmos.internal.changefeed.exceptions.TaskCancelledException; +import reactor.core.publisher.Mono; + +import java.io.Closeable; +import java.io.IOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Implementation for {@link PartitionSupervisor}. + */ +class PartitionSupervisorImpl implements PartitionSupervisor, Closeable { + private final Lease lease; + private final ChangeFeedObserver observer; + private final PartitionProcessor processor; + private final LeaseRenewer renewer; + private CancellationTokenSource renewerCancellation; + private CancellationTokenSource processorCancellation; + + private RuntimeException resultException; + + private ExecutorService executorService; + + public PartitionSupervisorImpl(Lease lease, ChangeFeedObserver observer, PartitionProcessor processor, LeaseRenewer renewer, ExecutorService executorService) { + this.lease = lease; + this.observer = observer; + this.processor = processor; + this.renewer = renewer; + this.executorService = executorService; + + if (executorService == null) { + this.executorService = Executors.newFixedThreadPool(3); + } + } + + @Override + public Mono run(CancellationToken shutdownToken) { + PartitionSupervisorImpl self = this; + this.resultException = null; + + ChangeFeedObserverContext context = new ChangeFeedObserverContextImpl(self.lease.getLeaseToken()); + + self.observer.open(context); + + ChangeFeedObserverCloseReason closeReason = ChangeFeedObserverCloseReason.UNKNOWN; + + try { + self.processorCancellation = new CancellationTokenSource(); + + Thread processorThread = new Thread(new Runnable() { + @Override + public void run() { + self.processor.run(self.processorCancellation.getToken()).block(); + } + }); + + self.renewerCancellation = new CancellationTokenSource(); + + Thread renewerThread = new Thread(new Runnable() { + @Override + public void run() { + self.renewer.run(self.renewerCancellation.getToken()).block(); + } + }); + + self.executorService.execute(processorThread); + self.executorService.execute(renewerThread); + + while (!shutdownToken.isCancellationRequested() && self.processor.getResultException() == null && self.renewer.getResultException() == null) { + try { + Thread.sleep(100); + } catch (InterruptedException iex) { + break; + } + } + + this.processorCancellation.cancel(); + this.renewerCancellation.cancel(); + executorService.shutdown(); + + if (self.processor.getResultException() != null) { + throw self.processor.getResultException(); + } + + if (self.renewer.getResultException() != null) { + throw self.renewer.getResultException(); + } + + closeReason = shutdownToken.isCancellationRequested() ? + ChangeFeedObserverCloseReason.SHUTDOWN : + ChangeFeedObserverCloseReason.UNKNOWN; + + } catch (LeaseLostException llex) { + closeReason = ChangeFeedObserverCloseReason.LEASE_LOST; + self.resultException = llex; + } catch (PartitionSplitException pex) { + closeReason = ChangeFeedObserverCloseReason.LEASE_GONE; + self.resultException = pex; + } catch (TaskCancelledException tcex) { + closeReason = ChangeFeedObserverCloseReason.SHUTDOWN; + self.resultException = null; + } catch (ObserverException oex) { + closeReason = ChangeFeedObserverCloseReason.OBSERVER_ERROR; + self.resultException = oex; + } catch (Exception ex) { + closeReason = ChangeFeedObserverCloseReason.UNKNOWN; + } finally { + self.observer.close(context, closeReason); + } + + if (self.resultException != null) { + return Mono.error(self.resultException); + } else { + return Mono.empty(); + } + } + + @Override + public RuntimeException getResultException() { + return this.resultException; + } + + @Override + public void close() throws IOException { + if (this.processorCancellation != null) { + this.processorCancellation.close(); + } + + this.renewerCancellation.close(); + } +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSynchronizerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java similarity index 93% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSynchronizerImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java index 0b9a9f4115d9c..b777341b321ac 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionSynchronizerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java @@ -20,16 +20,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.LeaseContainer; -import com.azure.data.cosmos.changefeed.LeaseManager; -import com.azure.data.cosmos.changefeed.PartitionSynchronizer; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.LeaseContainer; +import com.azure.data.cosmos.internal.changefeed.LeaseManager; +import com.azure.data.cosmos.internal.changefeed.PartitionSynchronizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; @@ -41,7 +41,7 @@ /** * Implementation for the partition synchronizer. */ -public class PartitionSynchronizerImpl implements PartitionSynchronizer { +class PartitionSynchronizerImpl implements PartitionSynchronizer { private final Logger logger = LoggerFactory.getLogger(PartitionSynchronizerImpl.class); private final ChangeFeedContextClient documentClient; private final CosmosContainer collectionSelfLink; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java similarity index 86% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java index 69d68d1ad3be9..c0fb1fcaf04c6 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/PartitionedByIdCollectionRequestOptionsFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java @@ -20,18 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.changefeed.Lease; -import com.azure.data.cosmos.changefeed.RequestOptionsFactory; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.RequestOptionsFactory; /** * Used to create request options for partitioned lease collections, when partition key is defined as /id. */ -public class PartitionedByIdCollectionRequestOptionsFactory implements RequestOptionsFactory { +class PartitionedByIdCollectionRequestOptionsFactory implements RequestOptionsFactory { @Override public CosmosItemRequestOptions createRequestOptions(Lease lease) { CosmosItemRequestOptions requestOptions = new CosmosItemRequestOptions(); diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingPartitionWorkImpl.java similarity index 91% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingPartitionWorkImpl.java index bd1e375a14460..c770966f9d8cf 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingPartitionWorkImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingPartitionWorkImpl.java @@ -20,14 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.changefeed.RemainingPartitionWork; +import com.azure.data.cosmos.internal.changefeed.RemainingPartitionWork; /** * Implements the {@link RemainingPartitionWork} interface. */ -public class RemainingPartitionWorkImpl implements RemainingPartitionWork { +class RemainingPartitionWorkImpl implements RemainingPartitionWork { private final String partitionKeyRangeId; private final long remainingWork; diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingWorkEstimatorImpl.java similarity index 83% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingWorkEstimatorImpl.java index 9394e73170bd9..c92785af3911f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/RemainingWorkEstimatorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingWorkEstimatorImpl.java @@ -20,19 +20,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.changefeed.ChangeFeedContextClient; -import com.azure.data.cosmos.changefeed.LeaseContainer; -import com.azure.data.cosmos.changefeed.RemainingPartitionWork; -import com.azure.data.cosmos.changefeed.RemainingWorkEstimator; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.LeaseContainer; +import com.azure.data.cosmos.internal.changefeed.RemainingPartitionWork; +import com.azure.data.cosmos.internal.changefeed.RemainingWorkEstimator; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * Implementation for {@link RemainingWorkEstimator}. */ -public class RemainingWorkEstimatorImpl implements RemainingWorkEstimator { +class RemainingWorkEstimatorImpl implements RemainingWorkEstimator { private final char PKRangeIdSeparator = ':'; private final char SegmentSeparator = '#'; private final String LSNPropertyName = "_lsn"; @@ -59,8 +59,8 @@ public RemainingWorkEstimatorImpl( } @Override - public Mono getEstimatedRemainingWork() { - return this.getEstimatedRemainingWorkPerPartition() + public Mono estimatedRemainingWork() { + return this.estimatedRemainingWorkPerPartition() .map(RemainingPartitionWork::getRemainingWork) .collectList() .map(list -> { @@ -79,7 +79,7 @@ public Mono getEstimatedRemainingWork() { } @Override - public Flux getEstimatedRemainingWorkPerPartition() { + public Flux estimatedRemainingWorkPerPartition() { return null; } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/StatusCodeErrorType.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/StatusCodeErrorType.java similarity index 93% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/StatusCodeErrorType.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/StatusCodeErrorType.java index 618bb53e32791..51a5dfeba3607 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/StatusCodeErrorType.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/StatusCodeErrorType.java @@ -20,12 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; /** * Groups types of status code errors returned while processing the change feeds. */ -public enum StatusCodeErrorType { +enum StatusCodeErrorType { UNDEFINED, PARTITION_NOT_FOUND, PARTITION_SPLIT, diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/TraceHealthMonitor.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/TraceHealthMonitor.java similarity index 87% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/TraceHealthMonitor.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/TraceHealthMonitor.java index 0af1a33f50255..8ac8060bb709f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/TraceHealthMonitor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/TraceHealthMonitor.java @@ -20,10 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.changefeed.HealthMonitor; -import com.azure.data.cosmos.changefeed.HealthMonitoringRecord; +import com.azure.data.cosmos.internal.changefeed.HealthMonitor; +import com.azure.data.cosmos.internal.changefeed.HealthMonitoringRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; @@ -31,7 +31,7 @@ /** * Implementation for trace health monitor. */ -public class TraceHealthMonitor implements HealthMonitor { +class TraceHealthMonitor implements HealthMonitor { private final Logger logger = LoggerFactory.getLogger(TraceHealthMonitor.class); @Override public Mono inspect(HealthMonitoringRecord record) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/WorkerTask.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java similarity index 64% rename from sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/WorkerTask.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java index ca74075c88f74..caa3a083870cc 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/changefeed/internal/WorkerTask.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java @@ -20,30 +20,43 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.changefeed.internal; +package com.azure.data.cosmos.internal.changefeed.implementation; -import reactor.core.publisher.Mono; +import com.azure.data.cosmos.internal.changefeed.Lease; +import com.azure.data.cosmos.internal.changefeed.LeaseManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Worker task that executes in a separate thread. */ -public class WorkerTask extends Thread { +class WorkerTask extends Thread { + private final Logger logger = LoggerFactory.getLogger(WorkerTask.class); private boolean done = false; - private Mono job; + private Runnable job; + private Lease lease; - WorkerTask(Mono job) { + WorkerTask(Lease lease, Runnable job) { + this.lease = lease; this.job = job; } @Override public void run() { try { - job.block(); + job.run(); + logger.info("Partition controller worker task {} has finished running.", lease.getLeaseToken()); } finally { + logger.info("Partition controller worker task {} has exited.", lease.getLeaseToken()); + job = null; this.done = true; } } + public Lease lease() { + return this.lease; + } + public boolean isRunning() { return !this.done; } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java new file mode 100644 index 0000000000000..c129312f20eee --- /dev/null +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java @@ -0,0 +1,305 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos.rx; + +import com.azure.data.cosmos.ChangeFeedProcessor; +import com.azure.data.cosmos.ChangeFeedProcessorOptions; +import com.azure.data.cosmos.CosmosClient; +import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerRequestOptions; +import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosDatabase; +import com.azure.data.cosmos.CosmosItemProperties; +import com.azure.data.cosmos.SerializationFormattingPolicy; +import org.apache.commons.lang3.RandomStringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.AfterClass; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ChangeFeedProcessorTest extends TestSuiteBase { + private final static Logger log = LoggerFactory.getLogger(ChangeFeedProcessorTest.class); + + private CosmosDatabase createdDatabase; + private CosmosContainer createdFeedCollection; + private CosmosContainer createdLeaseCollection; + private List createdDocuments; + private static Map receivedDocuments; +// private final String databaseId = "testdb1"; +// private final String hostName = "TestHost1"; + private final String hostName = RandomStringUtils.randomAlphabetic(6); + private final int FEED_COUNT = 10; + private final int CHANGE_FEED_PROCESSOR_TIMEOUT = 5000; + + private CosmosClient client; + + private ChangeFeedProcessor changeFeedProcessor; + + @Factory(dataProvider = "clientBuilders") + public ChangeFeedProcessorTest(CosmosClientBuilder clientBuilder) { + super(clientBuilder); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT) + public void readFeedDocumentsStartFromBeginning() { + setupReadFeedDocuments(); + + changeFeedProcessor = ChangeFeedProcessor.Builder() + .hostName(hostName) + .handleChanges(docs -> { + ChangeFeedProcessorTest.log.info("START processing from thread {}", Thread.currentThread().getId()); + for (CosmosItemProperties item : docs) { + processItem(item); + } + ChangeFeedProcessorTest.log.info("END processing from thread {}", Thread.currentThread().getId()); + }) + .feedContainerClient(createdFeedCollection) + .leaseContainerClient(createdLeaseCollection) + .options(new ChangeFeedProcessorOptions() + .leaseRenewInterval(Duration.ofSeconds(20)) + .leaseAcquireInterval(Duration.ofSeconds(10)) + .leaseExpirationInterval(Duration.ofSeconds(30)) + .feedPollDelay(Duration.ofSeconds(2)) + .leasePrefix("TEST") + .maxItemCount(10) + .startFromBeginning(true) + .minPartitionCount(1) + .maxPartitionCount(3) + .discardExistingLeases(true) + .queryPartitionsMaxBatchSize(2) + .degreeOfParallelism(1) + ) + .build(); + + try { + changeFeedProcessor.start().subscribeOn(Schedulers.elastic()) + .timeout(Duration.ofMillis(CHANGE_FEED_PROCESSOR_TIMEOUT)) + .subscribe(); + } catch (Exception ex) { + log.error("Change feed processor did not start in the expected time", ex); + } + + // Wait for the feed processor to receive and process the documents. + try { + Thread.sleep(2 * CHANGE_FEED_PROCESSOR_TIMEOUT); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + changeFeedProcessor.stop().subscribeOn(Schedulers.elastic()).timeout(Duration.ofMillis(CHANGE_FEED_PROCESSOR_TIMEOUT)).subscribe(); + + for (CosmosItemProperties item : createdDocuments) { + assertThat(receivedDocuments.containsKey(item.id())).as("Document with id: " + item.id()).isTrue(); + } + + // Wait for the feed processor to shutdown. + try { + Thread.sleep(CHANGE_FEED_PROCESSOR_TIMEOUT); + } catch (InterruptedException e) { + e.printStackTrace(); + } + receivedDocuments.clear(); + } + + @Test(groups = { "emulator" }, timeOut = TIMEOUT) + public void readFeedDocumentsStartFromCustomDate() { + ChangeFeedProcessor changeFeedProcessor = ChangeFeedProcessor.Builder() + .hostName(hostName) + .handleChanges(docs -> { + ChangeFeedProcessorTest.log.info("START processing from thread {}", Thread.currentThread().getId()); + for (CosmosItemProperties item : docs) { + processItem(item); + } + ChangeFeedProcessorTest.log.info("END processing from thread {}", Thread.currentThread().getId()); + }) + .feedContainerClient(createdFeedCollection) + .leaseContainerClient(createdLeaseCollection) + .options(new ChangeFeedProcessorOptions() + .leaseRenewInterval(Duration.ofSeconds(20)) + .leaseAcquireInterval(Duration.ofSeconds(10)) + .leaseExpirationInterval(Duration.ofSeconds(30)) + .feedPollDelay(Duration.ofSeconds(1)) + .leasePrefix("TEST") + .maxItemCount(10) + .startTime(OffsetDateTime.now().minusDays(1)) + .minPartitionCount(1) + .maxPartitionCount(3) + .discardExistingLeases(true) + .queryPartitionsMaxBatchSize(2) + .degreeOfParallelism(2) + ) + .build(); + + try { + changeFeedProcessor.start().subscribeOn(Schedulers.elastic()) + .timeout(Duration.ofMillis(CHANGE_FEED_PROCESSOR_TIMEOUT)) + .subscribe(); + } catch (Exception ex) { + log.error("Change feed processor did not start in the expected time", ex); + } + + setupReadFeedDocuments(); + + // Wait for the feed processor to receive and process the documents. + long remainingWork = FEED_TIMEOUT; + while (remainingWork > 0 && receivedDocuments.size() < FEED_COUNT) { + remainingWork -= CHANGE_FEED_PROCESSOR_TIMEOUT; + try { + Thread.sleep(CHANGE_FEED_PROCESSOR_TIMEOUT); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + assertThat(remainingWork >= 0).as("Failed to receive all the feed documents").isTrue(); + + changeFeedProcessor.stop().subscribeOn(Schedulers.elastic()).timeout(Duration.ofMillis(2 * CHANGE_FEED_PROCESSOR_TIMEOUT)).subscribe(); + + for (CosmosItemProperties item : createdDocuments) { + assertThat(receivedDocuments.containsKey(item.id())).as("Document with id: " + item.id()).isTrue(); + } + + // Wait for the feed processor to shutdown. + try { + Thread.sleep(CHANGE_FEED_PROCESSOR_TIMEOUT); + } catch (InterruptedException e) { + e.printStackTrace(); + } + receivedDocuments.clear(); + } + + @BeforeMethod(groups = { "emulator" }, timeOut = 2 * SETUP_TIMEOUT, alwaysRun = true) + public void beforeMethod() { + createdFeedCollection = createFeedCollection(); + createdLeaseCollection = createLeaseCollection(); + } + + @BeforeClass(groups = { "emulator" }, timeOut = SETUP_TIMEOUT, alwaysRun = true) + public void beforeClass() { + client = clientBuilder().build(); + +// try { +// client.getDatabase(databaseId).read() +// .map(cosmosDatabaseResponse -> cosmosDatabaseResponse.database()) +// .flatMap(database -> database.delete()) +// .onErrorResume(throwable -> { +// if (throwable instanceof com.azure.data.cosmos.CosmosClientException) { +// com.azure.data.cosmos.CosmosClientException clientException = (com.azure.data.cosmos.CosmosClientException) throwable; +// if (clientException.statusCode() == 404) { +// return Mono.empty(); +// } +// } +// return Mono.error(throwable); +// }).block(); +// Thread.sleep(500); +// } catch (Exception e){ +// log.warn("Database delete", e); +// } +// createdDatabase = createDatabase(client, databaseId); + createdDatabase = getSharedCosmosDatabase(client); + } + + @AfterMethod(groups = { "emulator" }, timeOut = 3 * SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterMethod() { + safeDeleteCollection(createdFeedCollection); + safeDeleteCollection(createdLeaseCollection); + + // Allow some time for the collections and the database to be deleted before exiting. + try { + Thread.sleep(500); + } catch (Exception e){ } + } + + @AfterClass(groups = { "emulator" }, timeOut = 2 * SHUTDOWN_TIMEOUT, alwaysRun = true) + public void afterClass() { +// try { +// client.listDatabases() +// .flatMap(cosmosDatabaseSettingsFeedResponse -> reactor.core.publisher.Flux.fromIterable(cosmosDatabaseSettingsFeedResponse.results())) +// .flatMap(cosmosDatabaseSettings -> { +// CosmosDatabase cosmosDatabase = client.getDatabase(cosmosDatabaseSettings.id()); +// return cosmosDatabase.delete(); +// }).blockLast(); +// Thread.sleep(500); +// } catch (Exception e){ } + + safeClose(client); + } + + private void setupReadFeedDocuments() { + receivedDocuments = new ConcurrentHashMap<>(); + List docDefList = new ArrayList<>(); + + for(int i = 0; i < FEED_COUNT; i++) { + docDefList.add(getDocumentDefinition()); + } + + createdDocuments = bulkInsertBlocking(createdFeedCollection, docDefList); + waitIfNeededForReplicasToCatchUp(clientBuilder()); + } + + private CosmosItemProperties getDocumentDefinition() { + String uuid = UUID.randomUUID().toString(); + CosmosItemProperties doc = new CosmosItemProperties(String.format("{ " + + "\"id\": \"%s\", " + + "\"mypk\": \"%s\", " + + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]" + + "}" + , uuid, uuid)); + return doc; + } + + private CosmosContainer createFeedCollection() { + CosmosContainerRequestOptions optionsFeedCollection = new CosmosContainerRequestOptions(); + optionsFeedCollection.offerThroughput(10100); + return createCollection(createdDatabase, getCollectionDefinition(), optionsFeedCollection); + } + + private CosmosContainer createLeaseCollection() { + CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); + options.offerThroughput(400); + CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), "/id"); + return createCollection(createdDatabase, collectionDefinition, options); + } + + private static synchronized void processItem(CosmosItemProperties item) { + ChangeFeedProcessorTest.log.info("RECEIVED {}", item.toJson(SerializationFormattingPolicy.INDENTED)); + receivedDocuments.put(item.id(), item); + } +} From 98a3a9855b054aaeb88cb8b3c4d6d8b0454a66cc Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Tue, 25 Jun 2019 22:16:31 -0700 Subject: [PATCH 48/85] Users/kuthapar/v3 settings properties (#207) * Hiding Json Serializable set and remove methods and object mapper and object node return types * Renamed Settings suffixes to Properties suffixes * Refactored settings method to properties * Removed sdk - CosmosUserSettings, renamed commons - CosmosUserSettings to CosmosUserProperties --- .../com/azure/data/cosmos/BridgeInternal.java | 4 + ...gs.java => CosmosContainerProperties.java} | 42 +++++----- ...ngs.java => CosmosDatabaseProperties.java} | 14 ++-- ...a => CosmosStoredProcedureProperties.java} | 18 ++-- ...ings.java => CosmosTriggerProperties.java} | 26 +++--- ... CosmosUserDefinedFunctionProperties.java} | 22 ++--- .../data/cosmos/CosmosUserProperties.java | 31 +++---- .../azure/data/cosmos/CosmosUserSettings.java | 55 ------------- .../azure/data/cosmos/DocumentCollection.java | 2 +- .../azure/data/cosmos/examples/BasicDemo.java | 4 +- .../ChangeFeed/SampleChangeFeedProcessor.java | 6 +- .../com/azure/data/cosmos/CosmosClient.java | 30 +++---- .../azure/data/cosmos/CosmosContainer.java | 58 ++++++------- .../data/cosmos/CosmosContainerResponse.java | 10 +-- .../com/azure/data/cosmos/CosmosDatabase.java | 46 +++++------ .../data/cosmos/CosmosDatabaseResponse.java | 10 +-- .../azure/data/cosmos/CosmosPermission.java | 2 +- ...s.java => CosmosPermissionProperties.java} | 33 +++----- .../data/cosmos/CosmosPermissionResponse.java | 12 +-- .../data/cosmos/CosmosStoredProcedure.java | 2 +- .../cosmos/CosmosStoredProcedureResponse.java | 10 +-- .../com/azure/data/cosmos/CosmosTrigger.java | 2 +- .../data/cosmos/CosmosTriggerResponse.java | 18 ++-- .../com/azure/data/cosmos/CosmosUser.java | 14 ++-- .../cosmos/CosmosUserDefinedFunction.java | 2 +- .../CosmosUserDefinedFunctionResponse.java | 14 ++-- .../azure/data/cosmos/CosmosUserResponse.java | 8 +- .../changefeed/ChangeFeedContextClient.java | 4 +- .../ChangeFeedContextClientImpl.java | 6 +- .../ChangeFeedProcessorBuilderImpl.java | 8 +- .../DocumentServiceLeaseStore.java | 3 +- .../data/cosmos/CosmosBridgeInternal.java | 4 +- .../data/cosmos/CosmosDatabaseForTest.java | 12 +-- .../data/cosmos/CosmosPartitionKeyTests.java | 5 +- .../data/cosmos/CosmosResponseValidator.java | 32 ++++---- .../rx/BackPressureCrossPartitionTest.java | 6 +- .../data/cosmos/rx/BackPressureTest.java | 8 +- .../cosmos/rx/ChangeFeedProcessorTest.java | 5 +- .../data/cosmos/rx/CollectionCrudTest.java | 20 ++--- .../data/cosmos/rx/CollectionQueryTest.java | 26 +++--- .../data/cosmos/rx/DatabaseCrudTest.java | 8 +- .../data/cosmos/rx/DatabaseQueryTest.java | 26 +++--- .../rx/MultiMasterConflictResolutionTest.java | 20 ++--- .../cosmos/rx/MultiOrderByQueryTests.java | 4 +- .../data/cosmos/rx/PermissionCrudTest.java | 36 ++++---- .../cosmos/rx/ReadFeedCollectionsTest.java | 12 +-- .../data/cosmos/rx/ReadFeedDatabasesTest.java | 18 ++-- .../rx/ReadFeedExceptionHandlingTest.java | 14 ++-- .../rx/ReadFeedStoredProceduresTest.java | 18 ++-- .../data/cosmos/rx/ReadFeedTriggersTest.java | 18 ++-- .../data/cosmos/rx/ReadFeedUdfsTest.java | 16 ++-- .../data/cosmos/rx/ReadFeedUsersTest.java | 14 ++-- .../cosmos/rx/StoredProcedureCrudTest.java | 8 +- .../cosmos/rx/StoredProcedureQueryTest.java | 40 ++++----- .../rx/StoredProcedureUpsertReplaceTest.java | 9 +- .../azure/data/cosmos/rx/TestSuiteBase.java | 82 +++++++++---------- .../azure/data/cosmos/rx/TriggerCrudTest.java | 8 +- .../data/cosmos/rx/TriggerQueryTest.java | 40 ++++----- .../cosmos/rx/TriggerUpsertReplaceTest.java | 6 +- .../azure/data/cosmos/rx/UniqueIndexTest.java | 10 +-- .../azure/data/cosmos/rx/UserCrudTest.java | 14 ++-- .../rx/UserDefinedFunctionCrudTest.java | 8 +- .../rx/UserDefinedFunctionQueryTest.java | 38 ++++----- .../UserDefinedFunctionUpsertReplaceTest.java | 6 +- .../azure/data/cosmos/rx/UserQueryTest.java | 30 +++---- 65 files changed, 539 insertions(+), 598 deletions(-) rename commons/src/main/java/com/azure/data/cosmos/{CosmosContainerSettings.java => CosmosContainerProperties.java} (81%) rename commons/src/main/java/com/azure/data/cosmos/{CosmosDatabaseSettings.java => CosmosDatabaseProperties.java} (81%) rename commons/src/main/java/com/azure/data/cosmos/{CosmosStoredProcedureSettings.java => CosmosStoredProcedureProperties.java} (79%) rename commons/src/main/java/com/azure/data/cosmos/{CosmosTriggerSettings.java => CosmosTriggerProperties.java} (84%) rename commons/src/main/java/com/azure/data/cosmos/{CosmosUserDefinedFunctionSettings.java => CosmosUserDefinedFunctionProperties.java} (76%) rename sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java => commons/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java (59%) delete mode 100644 commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java rename sdk/src/main/java/com/azure/data/cosmos/{CosmosPermissionSettings.java => CosmosPermissionProperties.java} (78%) diff --git a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java index b4a9076e72c33..8464e9314bb80 100644 --- a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java @@ -303,4 +303,8 @@ public static void setProperty(JsonSerializable jsonSerializable, String pro public static void remove(JsonSerializable jsonSerializable, String propertyName) { jsonSerializable.remove(propertyName); } + + public static CosmosStoredProcedureProperties createCosmosStoredProcedureProperties(String jsonString) { + return new CosmosStoredProcedureProperties(jsonString); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosContainerSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java similarity index 81% rename from commons/src/main/java/com/azure/data/cosmos/CosmosContainerSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java index 675306a95f050..3f31a96b8755b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosContainerSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java @@ -36,7 +36,7 @@ * Being schema-free, the items in a container do not need to share the same structure or fields. Since containers * are application resources, they can be authorized using either the master key or resource keys. */ -public class CosmosContainerSettings extends Resource { +public class CosmosContainerProperties extends Resource { private IndexingPolicy indexingPolicy; private UniqueKeyPolicy uniqueKeyPolicy; @@ -47,13 +47,13 @@ public class CosmosContainerSettings extends Resource { * @param id id of the Container * @param partitionKeyPath partition key path */ - public CosmosContainerSettings(String id, String partitionKeyPath) { + public CosmosContainerProperties(String id, String partitionKeyPath) { super.id(id); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add(partitionKeyPath); partitionKeyDef.paths(paths); - setPartitionKey(partitionKeyDef); + partitionKeyDefinition(partitionKeyDef); } /** @@ -61,22 +61,22 @@ public CosmosContainerSettings(String id, String partitionKeyPath) { * @param id id of the container * @param partitionKeyDefinition the (@link PartitionKeyDefinition) */ - public CosmosContainerSettings(String id, PartitionKeyDefinition partitionKeyDefinition) { + public CosmosContainerProperties(String id, PartitionKeyDefinition partitionKeyDefinition) { super.id(id); - setPartitionKey(partitionKeyDefinition); + partitionKeyDefinition(partitionKeyDefinition); } - CosmosContainerSettings(ResourceResponse response) { + CosmosContainerProperties(ResourceResponse response) { super(response.getResource().toJson()); } - // Converting document collection to CosmosContainerSettings - CosmosContainerSettings(DocumentCollection collection){ + // Converting document collection to CosmosContainerProperties + CosmosContainerProperties(DocumentCollection collection){ super(collection.toJson()); } - static List getFromV2Results(List results){ - return results.stream().map(CosmosContainerSettings::new).collect(Collectors.toList()); + static List getFromV2Results(List results){ + return results.stream().map(CosmosContainerProperties::new).collect(Collectors.toList()); } /** @@ -100,9 +100,9 @@ public IndexingPolicy indexingPolicy() { * Sets the container's indexing policy * * @param indexingPolicy {@link IndexingPolicy} the indexing policy - * @return the CosmosContainerSettings. + * @return the CosmosContainerProperties. */ - public CosmosContainerSettings indexingPolicy(IndexingPolicy indexingPolicy) { + public CosmosContainerProperties indexingPolicy(IndexingPolicy indexingPolicy) { if (indexingPolicy == null) { throw new IllegalArgumentException("IndexingPolicy cannot be null."); } @@ -134,9 +134,9 @@ public UniqueKeyPolicy uniqueKeyPolicy() { * Sets the Containers unique key policy * * @param uniqueKeyPolicy the unique key policy - * @return the CosmosContainerSettings. + * @return the CosmosContainerProperties. */ - public CosmosContainerSettings uniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) { + public CosmosContainerProperties uniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) { if (uniqueKeyPolicy == null) { throw new IllegalArgumentException("uniqueKeyPolicy cannot be null."); } @@ -151,7 +151,7 @@ public CosmosContainerSettings uniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) * * @return the partition key definition. */ - public PartitionKeyDefinition partitionKey() { + public PartitionKeyDefinition partitionKeyDefinition() { if (this.partitionKeyDefinition == null) { if (super.has(Constants.Properties.PARTITION_KEY)) { @@ -168,11 +168,11 @@ public PartitionKeyDefinition partitionKey() { * Sets the containers's partition key definition. * * @param partitionKeyDefinition the partition key definition. - * @return the CosmosContainerSettings. + * @return the CosmosContainerProperties. */ - public CosmosContainerSettings setPartitionKey(PartitionKeyDefinition partitionKeyDefinition) { + public CosmosContainerProperties partitionKeyDefinition(PartitionKeyDefinition partitionKeyDefinition) { if (partitionKeyDefinition == null) { - throw new IllegalArgumentException("partitionKey cannot be null."); + throw new IllegalArgumentException("partitionKeyDefinition cannot be null."); } this.partitionKeyDefinition = partitionKeyDefinition; @@ -194,9 +194,9 @@ public ConflictResolutionPolicy conflictResolutionPolicy() { * on documents in different regions, in a collection in the Azure Cosmos DB service. * * @param value ConflictResolutionPolicy to be used. - * @return the CosmosContainerSettings. + * @return the CosmosContainerProperties. */ - public CosmosContainerSettings conflictResolutionPolicy(ConflictResolutionPolicy value) { + public CosmosContainerProperties conflictResolutionPolicy(ConflictResolutionPolicy value) { if (value == null) { throw new IllegalArgumentException("CONFLICT_RESOLUTION_POLICY cannot be null."); } @@ -207,7 +207,7 @@ public CosmosContainerSettings conflictResolutionPolicy(ConflictResolutionPolicy DocumentCollection getV2Collection(){ DocumentCollection collection = new DocumentCollection(this.toJson()); - collection.setPartitionKey(this.partitionKey()); + collection.setPartitionKey(this.partitionKeyDefinition()); collection.setIndexingPolicy(this.indexingPolicy()); return collection; } diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java similarity index 81% rename from commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java index 335c6758025eb..00600ed0670de 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java @@ -33,26 +33,26 @@ * more cosmos items. Since databases are an an administrative resource and the Service Key will be required in * order to access and successfully complete any action using the User APIs. */ -public class CosmosDatabaseSettings extends Resource { +public class CosmosDatabaseProperties extends Resource { /** * Constructor * @param id id of the database */ - public CosmosDatabaseSettings(String id) { + public CosmosDatabaseProperties(String id) { super.id(id); } - CosmosDatabaseSettings(ResourceResponse response) { + CosmosDatabaseProperties(ResourceResponse response) { super(response.getResource().toJson()); } - // Converting document collection to CosmosContainerSettings - CosmosDatabaseSettings(Database database){ + // Converting document collection to CosmosContainerProperties + CosmosDatabaseProperties(Database database){ super(database.toJson()); } - static List getFromV2Results(List results){ - return results.stream().map(CosmosDatabaseSettings::new).collect(Collectors.toList()); + static List getFromV2Results(List results){ + return results.stream().map(CosmosDatabaseProperties::new).collect(Collectors.toList()); } } \ No newline at end of file diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java similarity index 79% rename from commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java index df8236fa194f0..28547fbc392e4 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java @@ -27,22 +27,22 @@ import java.util.List; import java.util.stream.Collectors; -public class CosmosStoredProcedureSettings extends Resource { +public class CosmosStoredProcedureProperties extends Resource { /** * Constructor. * */ - public CosmosStoredProcedureSettings() { + public CosmosStoredProcedureProperties() { super(); } /** * Sets the id * @param id the name of the resource. - * @return return the Cosmos stored procedure settings with id set + * @return return the Cosmos stored procedure properties with id set */ - public CosmosStoredProcedureSettings id(String id){ + public CosmosStoredProcedureProperties id(String id){ super.id(id); return this; } @@ -52,7 +52,7 @@ public CosmosStoredProcedureSettings id(String id){ * * @param jsonString the json string that represents the stored procedure. */ - public CosmosStoredProcedureSettings(String jsonString) { + CosmosStoredProcedureProperties(String jsonString) { super(jsonString); } @@ -62,13 +62,13 @@ public CosmosStoredProcedureSettings(String jsonString) { * @param id the id of the stored procedure * @param body the body of the stored procedure */ - public CosmosStoredProcedureSettings(String id, String body) { + public CosmosStoredProcedureProperties(String id, String body) { super(); super.id(id); this.body(body); } - CosmosStoredProcedureSettings(ResourceResponse response) { + CosmosStoredProcedureProperties(ResourceResponse response) { super(response.getResource().toJson()); } @@ -91,7 +91,7 @@ public void body(String body) { } - static List getFromV2Results(List results) { - return results.stream().map(sproc -> new CosmosStoredProcedureSettings(sproc.toJson())).collect(Collectors.toList()); + static List getFromV2Results(List results) { + return results.stream().map(sproc -> new CosmosStoredProcedureProperties(sproc.toJson())).collect(Collectors.toList()); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java similarity index 84% rename from commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java index 93025d425c770..51c4580e1f880 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java @@ -28,12 +28,12 @@ import java.util.List; import java.util.stream.Collectors; -public class CosmosTriggerSettings extends Resource { +public class CosmosTriggerProperties extends Resource { /** * Constructor */ - public CosmosTriggerSettings(){ + public CosmosTriggerProperties(){ super(); } @@ -42,11 +42,11 @@ public CosmosTriggerSettings(){ * * @param jsonString the json string that represents the trigger settings. */ - public CosmosTriggerSettings(String jsonString){ + CosmosTriggerProperties(String jsonString){ super(jsonString); } - CosmosTriggerSettings(ResourceResponse response) { + CosmosTriggerProperties(ResourceResponse response) { super(response.getResource().toJson()); } @@ -56,7 +56,7 @@ public CosmosTriggerSettings(String jsonString){ * @param id the name of the resource. * @return the current cosmos trigger settings instance */ - public CosmosTriggerSettings id(String id) { + public CosmosTriggerProperties id(String id) { super.id(id); return this; } @@ -74,9 +74,9 @@ public String body() { * Set the body of the trigger. * * @param body the body of the trigger. - * @return the CosmosTriggerSettings. + * @return the CosmosTriggerProperties. */ - public CosmosTriggerSettings body(String body) { + public CosmosTriggerProperties body(String body) { super.set(Constants.Properties.BODY, body); return this; } @@ -102,9 +102,9 @@ public TriggerType triggerType() { * Set the type of the resource. * * @param triggerType the trigger type. - * @return the CosmosTriggerSettings. + * @return the CosmosTriggerProperties. */ - public CosmosTriggerSettings triggerType(TriggerType triggerType) { + public CosmosTriggerProperties triggerType(TriggerType triggerType) { super.set(Constants.Properties.TRIGGER_TYPE, triggerType.toString()); return this; } @@ -130,14 +130,14 @@ public TriggerOperation triggerOperation() { * Set the operation type of the trigger. * * @param triggerOperation the trigger operation. - * @return the CosmosTriggerSettings. + * @return the CosmosTriggerProperties. */ - public CosmosTriggerSettings triggerOperation(TriggerOperation triggerOperation) { + public CosmosTriggerProperties triggerOperation(TriggerOperation triggerOperation) { super.set(Constants.Properties.TRIGGER_OPERATION, triggerOperation.toString()); return this; } - static List getFromV2Results(List results) { - return results.stream().map(trigger -> new CosmosTriggerSettings(trigger.toJson())).collect(Collectors.toList()); + static List getFromV2Results(List results) { + return results.stream().map(trigger -> new CosmosTriggerProperties(trigger.toJson())).collect(Collectors.toList()); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java similarity index 76% rename from commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java index 9513a4d7246f8..1e9c5f49f462f 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java @@ -27,34 +27,34 @@ import java.util.List; import java.util.stream.Collectors; -public class CosmosUserDefinedFunctionSettings extends Resource { +public class CosmosUserDefinedFunctionProperties extends Resource { /** * Constructor */ - public CosmosUserDefinedFunctionSettings(){ + public CosmosUserDefinedFunctionProperties(){ super(); } - CosmosUserDefinedFunctionSettings(ResourceResponse response) { + CosmosUserDefinedFunctionProperties(ResourceResponse response) { super(response.getResource().toJson()); } /** * Constructor. * - * @param jsonString the json string that represents the cosmos user defined function settings. + * @param jsonString the json string that represents the cosmos user defined function properties. */ - public CosmosUserDefinedFunctionSettings(String jsonString) { + CosmosUserDefinedFunctionProperties(String jsonString) { super(jsonString); } /** * Sets the id * @param id the name of the resource. - * @return the current instance of cosmos user defined function settings + * @return the current instance of cosmos user defined function properties */ - public CosmosUserDefinedFunctionSettings id(String id) { + public CosmosUserDefinedFunctionProperties id(String id) { super.id(id); return this; } @@ -72,14 +72,14 @@ public String body() { * Set the body of the user defined function. * * @param body the body. - * @return the CosmosUserDefinedFunctionSettings. + * @return the CosmosUserDefinedFunctionProperties. */ - public CosmosUserDefinedFunctionSettings body(String body) { + public CosmosUserDefinedFunctionProperties body(String body) { super.set(Constants.Properties.BODY, body); return this; } - static List getFromV2Results(List results) { - return results.stream().map(udf -> new CosmosUserDefinedFunctionSettings(udf.toJson())).collect(Collectors.toList()); + static List getFromV2Results(List results) { + return results.stream().map(udf -> new CosmosUserDefinedFunctionProperties(udf.toJson())).collect(Collectors.toList()); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java similarity index 59% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java index 98a4d3cea5672..2dd56aadb690f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java @@ -5,21 +5,21 @@ import java.util.List; import java.util.stream.Collectors; -public class CosmosUserSettings extends Resource { +public class CosmosUserProperties extends Resource { /** * Initialize a user object. */ - public CosmosUserSettings() { + public CosmosUserProperties() { super(); } /** * Sets the id * @param id the name of the resource. - * @return the current instance of cosmos user settings + * @return the current instance of cosmos user properties */ - public CosmosUserSettings id(String id) { - return (CosmosUserSettings) super.id(id); + public CosmosUserProperties id(String id) { + return (CosmosUserProperties) super.id(id); } /** @@ -27,28 +27,25 @@ public CosmosUserSettings id(String id) { * * @param jsonString the json string that represents the database user. */ - public CosmosUserSettings(String jsonString) { + CosmosUserProperties(String jsonString) { super(jsonString); } - CosmosUserSettings(ResourceResponse response) { + CosmosUserProperties(ResourceResponse response) { super(response.getResource().toJson()); } - CosmosUserSettings(User user) { + // Converting document collection to CosmosContainerProperties + CosmosUserProperties(User user){ super(user.toJson()); } - static List getFromV2Results(List results, CosmosDatabase database) { - return results.stream().map(CosmosUserSettings::new).collect(Collectors.toList()); - } - /** * Gets the self-link of the permissions associated with the user. * * @return the permissions link. */ - public String permissionsLink() { + public String getPermissionsLink() { String selfLink = this.selfLink(); if (selfLink.endsWith("/")) { return selfLink + super.getString(Constants.Properties.PERMISSIONS_LINK); @@ -57,7 +54,11 @@ public String permissionsLink() { } } - User getV2User() { + public User getV2User() { return new User(this.toJson()); } -} + + static List getFromV2Results(List results) { + return results.stream().map(CosmosUserProperties::new).collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java b/commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java deleted file mode 100644 index 096921243331d..0000000000000 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosUserSettings.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.azure.data.cosmos; - -import com.azure.data.cosmos.internal.Constants; - -import java.util.List; -import java.util.stream.Collectors; - -public class CosmosUserSettings extends Resource { - /** - * Initialize a user object. - */ - public CosmosUserSettings() { - super(); - } - - /** - * Initialize a user object from json string. - * - * @param jsonString the json string that represents the database user. - */ - public CosmosUserSettings(String jsonString) { - super(jsonString); - } - - CosmosUserSettings(ResourceResponse response) { - super(response.getResource().toJson()); - } - - // Converting document collection to CosmosContainerSettings - CosmosUserSettings(User user){ - super(user.toJson()); - } - - /** - * Gets the self-link of the permissions associated with the user. - * - * @return the permissions link. - */ - public String getPermissionsLink() { - String selfLink = this.selfLink(); - if (selfLink.endsWith("/")) { - return selfLink + super.getString(Constants.Properties.PERMISSIONS_LINK); - } else { - return selfLink + "/" + super.getString(Constants.Properties.PERMISSIONS_LINK); - } - } - - public User getV2User() { - return new User(this.toJson()); - } - - static List getFromV2Results(List results) { - return results.stream().map(CosmosUserSettings::new).collect(Collectors.toList()); - } -} \ No newline at end of file diff --git a/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java b/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java index 0bb720a87eee3..a4d195d90d051 100644 --- a/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java +++ b/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java @@ -120,7 +120,7 @@ public PartitionKeyDefinition getPartitionKey() { */ public void setPartitionKey(PartitionKeyDefinition partitionKey) { if (partitionKey == null) { - throw new IllegalArgumentException("partitionKey cannot be null."); + throw new IllegalArgumentException("partitionKeyDefinition cannot be null."); } this.partitionKeyDefinition = partitionKey; diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java b/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java index 18e5f95c4e2ec..a7089befe8846 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosItem; import com.azure.data.cosmos.CosmosItemProperties; @@ -119,7 +119,7 @@ private void createAndReplaceItem() { private void createDbAndContainerBlocking() { client.createDatabaseIfNotExists(DATABASE_NAME) .doOnSuccess(cosmosDatabaseResponse -> log("Database: " + cosmosDatabaseResponse.database().id())) - .flatMap(dbResponse -> dbResponse.database().createContainerIfNotExists(new CosmosContainerSettings(CONTAINER_NAME, "/country"))) + .flatMap(dbResponse -> dbResponse.database().createContainerIfNotExists(new CosmosContainerProperties(CONTAINER_NAME, "/country"))) .doOnSuccess(cosmosContainerResponse -> log("Container: " + cosmosContainerResponse.container().id())) .doOnError(throwable -> log(throwable.getMessage())) .publishOn(Schedulers.elastic()) diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java index 16348a9bf6821..343b7a2f63d1e 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java @@ -28,9 +28,9 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.CosmosContainerSettings; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.SerializationFormattingPolicy; @@ -161,7 +161,7 @@ public static CosmosContainer createNewCollection(CosmosClient client, String da } } - CosmosContainerSettings containerSettings = new CosmosContainerSettings(collectionName, "/id"); + CosmosContainerProperties containerSettings = new CosmosContainerProperties(collectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); requestOptions.offerThroughput(10000); @@ -204,7 +204,7 @@ public static CosmosContainer createNewLeaseCollection(CosmosClient client, Stri } } - CosmosContainerSettings containerSettings = new CosmosContainerSettings(leaseCollectionName, "/id"); + CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); requestOptions.offerThroughput(400); diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java index 56882323ad7a1..3e59929fa0f10 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java @@ -146,11 +146,11 @@ public TokenResolver getTokenResolver() { * * The {@link Mono} upon successful completion will contain a single cosmos database response with the * created or existing database. - * @param databaseSettings CosmosDatabaseSettings + * @param databaseSettings CosmosDatabaseProperties * @return a {@link Mono} containing the cosmos database response with the created or existing database or * an error. */ - public Mono createDatabaseIfNotExists(CosmosDatabaseSettings databaseSettings) { + public Mono createDatabaseIfNotExists(CosmosDatabaseProperties databaseSettings) { return createDatabaseIfNotExistsInternal(getDatabase(databaseSettings.id())); } @@ -171,7 +171,7 @@ private Mono createDatabaseIfNotExistsInternal(CosmosDat if (exception instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) exception; if (cosmosClientException.statusCode() == HttpConstants.StatusCodes.NOTFOUND) { - return createDatabase(new CosmosDatabaseSettings(database.id()), new CosmosDatabaseRequestOptions()); + return createDatabase(new CosmosDatabaseProperties(database.id()), new CosmosDatabaseRequestOptions()); } } return Mono.error(exception); @@ -186,12 +186,12 @@ private Mono createDatabaseIfNotExistsInternal(CosmosDat * created database. * In case of failure the {@link Mono} will error. * - * @param databaseSettings {@link CosmosDatabaseSettings} + * @param databaseSettings {@link CosmosDatabaseProperties} * @param options {@link CosmosDatabaseRequestOptions} * @return an {@link Mono} containing the single cosmos database response with the created database or an error. */ - public Mono createDatabase(CosmosDatabaseSettings databaseSettings, - CosmosDatabaseRequestOptions options) { + public Mono createDatabase(CosmosDatabaseProperties databaseSettings, + CosmosDatabaseRequestOptions options) { if (options == null) { options = new CosmosDatabaseRequestOptions(); } @@ -209,10 +209,10 @@ public Mono createDatabase(CosmosDatabaseSettings databa * created database. * In case of failure the {@link Mono} will error. * - * @param databaseSettings {@link CosmosDatabaseSettings} + * @param databaseSettings {@link CosmosDatabaseProperties} * @return an {@link Mono} containing the single cosmos database response with the created database or an error. */ - public Mono createDatabase(CosmosDatabaseSettings databaseSettings) { + public Mono createDatabase(CosmosDatabaseProperties databaseSettings) { return createDatabase(databaseSettings, new CosmosDatabaseRequestOptions()); } @@ -228,7 +228,7 @@ public Mono createDatabase(CosmosDatabaseSettings databa * @return a {@link Mono} containing the single cosmos database response with the created database or an error. */ public Mono createDatabase(String id) { - return createDatabase(new CosmosDatabaseSettings(id), new CosmosDatabaseRequestOptions()); + return createDatabase(new CosmosDatabaseProperties(id), new CosmosDatabaseRequestOptions()); } /** @@ -241,9 +241,9 @@ public Mono createDatabase(String id) { * @param options {@link FeedOptions} * @return a {@link Flux} containing one or several feed response pages of read databases or an error. */ - public Flux> listDatabases(FeedOptions options) { + public Flux> listDatabases(FeedOptions options) { return getDocClientWrapper().readDatabases(options) - .map(response-> BridgeInternal.createFeedResponse(CosmosDatabaseSettings.getFromV2Results(response.results()), + .map(response-> BridgeInternal.createFeedResponse(CosmosDatabaseProperties.getFromV2Results(response.results()), response.responseHeaders())); } @@ -256,7 +256,7 @@ public Flux> listDatabases(FeedOptions opti * * @return a {@link Flux} containing one or several feed response pages of read databases or an error. */ - public Flux> listDatabases() { + public Flux> listDatabases() { return listDatabases(new FeedOptions()); } @@ -272,7 +272,7 @@ public Flux> listDatabases() { * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of read databases or an error. */ - public Flux> queryDatabases(String query, FeedOptions options){ + public Flux> queryDatabases(String query, FeedOptions options){ return queryDatabases(new SqlQuerySpec(query), options); } @@ -287,10 +287,10 @@ public Flux> queryDatabases(String query, F * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of read databases or an error. */ - public Flux> queryDatabases(SqlQuerySpec querySpec, FeedOptions options){ + public Flux> queryDatabases(SqlQuerySpec querySpec, FeedOptions options){ return getDocClientWrapper().queryDatabases(querySpec, options) .map(response-> BridgeInternal.createFeedResponse( - CosmosDatabaseSettings.getFromV2Results(response.results()), + CosmosDatabaseProperties.getFromV2Results(response.results()), response.responseHeaders())); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index 21d95837054a1..b9b585873e339 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -148,8 +148,8 @@ public Mono delete() { * @param options the cosmos container request options. * @return an {@link Mono} containing the single cosmos container response with the replaced document container or an error. */ - public Mono replace(CosmosContainerSettings containerSettings, - CosmosContainerRequestOptions options) { + public Mono replace(CosmosContainerProperties containerSettings, + CosmosContainerRequestOptions options) { validateResource(containerSettings); if(options == null){ options = new CosmosContainerRequestOptions(); @@ -385,7 +385,7 @@ public CosmosItem getItem(String id, Object partitionKey){ * @param settings the cosmos stored procedure settings. * @return an {@link Mono} containing the single cosmos stored procedure resource response or an error. */ - public Mono createStoredProcedure(CosmosStoredProcedureSettings settings){ + public Mono createStoredProcedure(CosmosStoredProcedureProperties settings){ return this.createStoredProcedure(settings, new CosmosStoredProcedureRequestOptions()); } @@ -401,8 +401,8 @@ public Mono createStoredProcedure(CosmosStoredPro * @param options the stored procedure request options. * @return an {@link Mono} containing the single cosmos stored procedure resource response or an error. */ - public Mono createStoredProcedure(CosmosStoredProcedureSettings settings, - CosmosStoredProcedureRequestOptions options){ + public Mono createStoredProcedure(CosmosStoredProcedureProperties settings, + CosmosStoredProcedureRequestOptions options){ if(options == null){ options = new CosmosStoredProcedureRequestOptions(); } @@ -426,10 +426,10 @@ public Mono createStoredProcedure(CosmosStoredPro * @return an {@link Flux} containing one or several feed response pages of the read cosmos stored procedures * settings or an error. */ - public Flux> listStoredProcedures(FeedOptions options){ + public Flux> listStoredProcedures(FeedOptions options){ return database.getDocClientWrapper() .readStoredProcedures(getLink(), options) - .map(response -> BridgeInternal.createFeedResponse(CosmosStoredProcedureSettings.getFromV2Results(response.results()), + .map(response -> BridgeInternal.createFeedResponse(CosmosStoredProcedureProperties.getFromV2Results(response.results()), response.responseHeaders())); } @@ -445,8 +445,8 @@ public Flux> listStoredProcedures(Fe * @return an {@link Flux} containing one or several feed response pages of the obtained stored procedures or * an error. */ - public Flux> queryStoredProcedures(String query, - FeedOptions options){ + public Flux> queryStoredProcedures(String query, + FeedOptions options){ return queryStoredProcedures(new SqlQuerySpec(query), options); } @@ -462,11 +462,11 @@ public Flux> queryStoredProcedures(S * @return an {@link Flux} containing one or several feed response pages of the obtained stored procedures or * an error. */ - public Flux> queryStoredProcedures(SqlQuerySpec querySpec, - FeedOptions options){ + public Flux> queryStoredProcedures(SqlQuerySpec querySpec, + FeedOptions options){ return database.getDocClientWrapper() .queryStoredProcedures(getLink(), querySpec,options) - .map(response -> BridgeInternal.createFeedResponse( CosmosStoredProcedureSettings.getFromV2Results(response.results()), + .map(response -> BridgeInternal.createFeedResponse( CosmosStoredProcedureProperties.getFromV2Results(response.results()), response.responseHeaders())); } @@ -493,8 +493,8 @@ public CosmosStoredProcedure getStoredProcedure(String id){ * @param options the cosmos request options. * @return an {@link Mono} containing the single resource response with the created user defined function or an error. */ - public Mono createUserDefinedFunction(CosmosUserDefinedFunctionSettings settings, - CosmosRequestOptions options){ + public Mono createUserDefinedFunction(CosmosUserDefinedFunctionProperties settings, + CosmosRequestOptions options){ UserDefinedFunction udf = new UserDefinedFunction(); udf.id(settings.id()); udf.setBody(settings.body()); @@ -516,10 +516,10 @@ public Mono createUserDefinedFunction(CosmosU * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the read user defined functions or an error. */ - public Flux> listUserDefinedFunctions(FeedOptions options){ + public Flux> listUserDefinedFunctions(FeedOptions options){ return database.getDocClientWrapper() .readUserDefinedFunctions(getLink(), options) - .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionSettings.getFromV2Results(response.results()), + .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionProperties.getFromV2Results(response.results()), response.responseHeaders())); } @@ -534,8 +534,8 @@ public Flux> listUserDefinedFunc * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained user defined functions or an error. */ - public Flux> queryUserDefinedFunctions(String query, - FeedOptions options){ + public Flux> queryUserDefinedFunctions(String query, + FeedOptions options){ return queryUserDefinedFunctions(new SqlQuerySpec(query), options); } @@ -550,11 +550,11 @@ public Flux> queryUserDefinedFun * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained user defined functions or an error. */ - public Flux> queryUserDefinedFunctions(SqlQuerySpec querySpec, - FeedOptions options){ + public Flux> queryUserDefinedFunctions(SqlQuerySpec querySpec, + FeedOptions options){ return database.getDocClientWrapper() .queryUserDefinedFunctions(getLink(),querySpec, options) - .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionSettings.getFromV2Results(response.results()), + .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionProperties.getFromV2Results(response.results()), response.responseHeaders())); } @@ -579,8 +579,8 @@ public CosmosUserDefinedFunction getUserDefinedFunction(String id){ * @param options the request options. * @return an {@link Mono} containing the single resource response with the created trigger or an error. */ - public Mono createTrigger(CosmosTriggerSettings settings, - CosmosRequestOptions options){ + public Mono createTrigger(CosmosTriggerProperties settings, + CosmosRequestOptions options){ Trigger trigger = new Trigger(settings.toJson()); if(options == null){ options = new CosmosRequestOptions(); @@ -601,10 +601,10 @@ public Mono createTrigger(CosmosTriggerSettings settings, * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the read cosmos rigger settings or an error. */ - public Flux> listTriggers(FeedOptions options){ + public Flux> listTriggers(FeedOptions options){ return database.getDocClientWrapper() .readTriggers(getLink(), options) - .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerSettings.getFromV2Results(response.results()), + .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerProperties.getFromV2Results(response.results()), response.responseHeaders())); } @@ -619,7 +619,7 @@ public Flux> listTriggers(FeedOptions option * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained triggers or an error. */ - public Flux> queryTriggers(String query, FeedOptions options){ + public Flux> queryTriggers(String query, FeedOptions options){ return queryTriggers(new SqlQuerySpec(query), options); } @@ -634,11 +634,11 @@ public Flux> queryTriggers(String query, Fee * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained triggers or an error. */ - public Flux> queryTriggers(SqlQuerySpec querySpec, - FeedOptions options){ + public Flux> queryTriggers(SqlQuerySpec querySpec, + FeedOptions options){ return database.getDocClientWrapper() .queryTriggers(getLink(), querySpec, options) - .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerSettings.getFromV2Results(response.results()), + .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerProperties.getFromV2Results(response.results()), response.responseHeaders())); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java index f2d33fd0c612b..e9e9b5c3b36e1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos; -public class CosmosContainerResponse extends CosmosResponse { +public class CosmosContainerResponse extends CosmosResponse { private CosmosContainer container; @@ -31,7 +31,7 @@ public class CosmosContainerResponse extends CosmosResponse delete(CosmosRequestOptions options) { * @param containerSettings the container settings. * @return an {@link Flux} containing the single cosmos container response with the created container or an error. */ - public Mono createContainer(CosmosContainerSettings containerSettings) { + public Mono createContainer(CosmosContainerProperties containerSettings) { validateResource(containerSettings); return createContainer(containerSettings, new CosmosContainerRequestOptions()); } @@ -129,8 +129,8 @@ public Mono createContainer(CosmosContainerSettings con * @param options the cosmos container request options * @return an {@link Flux} containing the cosmos container response with the created container or an error. */ - public Mono createContainer(CosmosContainerSettings containerSettings, - CosmosContainerRequestOptions options) { + public Mono createContainer(CosmosContainerProperties containerSettings, + CosmosContainerRequestOptions options) { return getDocClientWrapper().createCollection(this.getLink(), containerSettings.getV2Collection(), options.toRequestOptions()).map(response -> new CosmosContainerResponse(response, this)) @@ -150,7 +150,7 @@ public Mono createContainer(CosmosContainerSettings con * @return an {@link Flux} containing the cosmos container response with the created container or an error. */ public Mono createContainer(String id, String partitionKeyPath) { - return createContainer(new CosmosContainerSettings(id, partitionKeyPath)); + return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } /** @@ -165,7 +165,7 @@ public Mono createContainer(String id, String partition * @return a {@link Mono} containing the cosmos container response with the created or existing container or * an error. */ - public Mono createContainerIfNotExists(CosmosContainerSettings containerSettings) { + public Mono createContainerIfNotExists(CosmosContainerProperties containerSettings) { CosmosContainer container = getContainer(containerSettings.id()); return createContainerIfNotExistsInternal(containerSettings, container); } @@ -184,11 +184,11 @@ public Mono createContainerIfNotExists(CosmosContainerS */ public Mono createContainerIfNotExists(String id, String partitionKeyPath) { CosmosContainer container = getContainer(id); - return createContainerIfNotExistsInternal(new CosmosContainerSettings(id, partitionKeyPath), container); + return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container); } - private Mono createContainerIfNotExistsInternal(CosmosContainerSettings containerSettings, CosmosContainer container) { + private Mono createContainerIfNotExistsInternal(CosmosContainerProperties containerSettings, CosmosContainer container) { return container.read().onErrorResume(exception -> { if (exception instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) exception; @@ -211,9 +211,9 @@ private Mono createContainerIfNotExistsInternal(CosmosC * @param options {@link FeedOptions} * @return a {@link Flux} containing one or several feed response pages of read containers or an error. */ - public Flux> listContainers(FeedOptions options) { + public Flux> listContainers(FeedOptions options) { return getDocClientWrapper().readCollections(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosContainerSettings.getFromV2Results(response.results()), + .map(response-> BridgeInternal.createFeedResponse(CosmosContainerProperties.getFromV2Results(response.results()), response.responseHeaders())); } @@ -226,7 +226,7 @@ public Flux> listContainers(FeedOptions op * * @return a {@link Flux} containing one or several feed response pages of read containers or an error. */ - public Flux> listContainers() { + public Flux> listContainers() { return listContainers(new FeedOptions()); } @@ -241,7 +241,7 @@ public Flux> listContainers() { * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained containers or an error. */ - public Flux> queryContainers(String query, FeedOptions options){ + public Flux> queryContainers(String query, FeedOptions options){ return queryContainers(new SqlQuerySpec(query), options); } @@ -256,11 +256,11 @@ public Flux> queryContainers(String query, * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained containers or an error. */ - public Flux> queryContainers(SqlQuerySpec querySpec, FeedOptions options){ + public Flux> queryContainers(SqlQuerySpec querySpec, FeedOptions options){ return getDocClientWrapper().queryCollections(getLink(), querySpec, options) .map(response-> BridgeInternal.createFeedResponse( - CosmosContainerSettings.getFromV2Results(response.results()), + CosmosContainerProperties.getFromV2Results(response.results()), response.responseHeaders())); } @@ -275,7 +275,7 @@ public CosmosContainer getContainer(String id) { /** User operations **/ - public Mono createUser(CosmosUserSettings settings) { + public Mono createUser(CosmosUserProperties settings) { return this.createUser(settings, null); } @@ -289,13 +289,13 @@ public Mono createUser(CosmosUserSettings settings) { * @param options the request options * @return an {@link Mono} containing the single resource response with the created cosmos user or an error. */ - public Mono createUser(CosmosUserSettings settings, RequestOptions options){ + public Mono createUser(CosmosUserProperties settings, RequestOptions options){ return getDocClientWrapper().createUser(this.getLink(), settings.getV2User(), options).map(response -> new CosmosUserResponse(response, this)).single(); } - public Mono upsertUser(CosmosUserSettings settings) { + public Mono upsertUser(CosmosUserProperties settings) { return this.upsertUser(settings, null); } @@ -309,13 +309,13 @@ public Mono upsertUser(CosmosUserSettings settings) { * @param options the request options * @return an {@link Mono} containing the single resource response with the upserted user or an error. */ - public Mono upsertUser(CosmosUserSettings settings, RequestOptions options){ + public Mono upsertUser(CosmosUserProperties settings, RequestOptions options){ return getDocClientWrapper().upsertUser(this.getLink(), settings.getV2User(), options).map(response -> new CosmosUserResponse(response, this)).single(); } - public Flux> listUsers() { + public Flux> listUsers() { return listUsers(new FeedOptions()); } @@ -329,14 +329,14 @@ public Flux> listUsers() { * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the read cosmos users or an error. */ - public Flux> listUsers(FeedOptions options){ + public Flux> listUsers(FeedOptions options){ return getDocClientWrapper() .readUsers(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosUserSettings.getFromV2Results(response.results(),this), + .map(response-> BridgeInternal.createFeedResponse(CosmosUserProperties.getFromV2Results(response.results()), response.responseHeaders())); } - public Flux> queryUsers(String query, FeedOptions options){ + public Flux> queryUsers(String query, FeedOptions options){ return queryUsers(new SqlQuerySpec(query), options); } @@ -351,11 +351,11 @@ public Flux> queryUsers(String query, FeedOptio * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained users or an error. */ - public Flux> queryUsers(SqlQuerySpec querySpec, FeedOptions options){ + public Flux> queryUsers(SqlQuerySpec querySpec, FeedOptions options){ return getDocClientWrapper() .queryUsers(getLink(), querySpec, options) .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( - CosmosUserSettings.getFromV2Results(response.results(), this), + CosmosUserProperties.getFromV2Results(response.results()), response.responseHeaders(), response.queryMetrics())); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java index aa37cf5ce3500..1c7cf0374af9f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos; -public class CosmosDatabaseResponse extends CosmosResponse{ +public class CosmosDatabaseResponse extends CosmosResponse{ private CosmosDatabase database; CosmosDatabaseResponse(ResourceResponse response, CosmosClient client) { @@ -30,7 +30,7 @@ public class CosmosDatabaseResponse extends CosmosResponse read(RequestOptions options) { * @param options the request options. * @return an {@link Mono} containing the single resource response with the replaced permission or an error. */ - public Mono replace(CosmosPermissionSettings permissionSettings, RequestOptions options) { + public Mono replace(CosmosPermissionProperties permissionSettings, RequestOptions options) { return cosmosUser.getDatabase() .getDocClientWrapper() diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionSettings.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java similarity index 78% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionSettings.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java index fc826eece1f1f..58a04c27dba39 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionSettings.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java @@ -28,16 +28,16 @@ import java.util.List; import java.util.stream.Collectors; -public class CosmosPermissionSettings extends Resource { +public class CosmosPermissionProperties extends Resource { - public static List getFromV2Results(List results) { - return results.stream().map(permission -> new CosmosPermissionSettings(permission.toJson())).collect(Collectors.toList()); + public static List getFromV2Results(List results) { + return results.stream().map(permission -> new CosmosPermissionProperties(permission.toJson())).collect(Collectors.toList()); } /** * Initialize a permission object. */ - public CosmosPermissionSettings() { + public CosmosPermissionProperties() { super(); } @@ -45,9 +45,9 @@ public CosmosPermissionSettings() { * Sets the id * * @param id the name of the resource. - * @return the cosmos permission settings with id set + * @return the cosmos permission properties with id set */ - public CosmosPermissionSettings id(String id) { + public CosmosPermissionProperties id(String id) { super.id(id); return this; } @@ -57,7 +57,7 @@ public CosmosPermissionSettings id(String id) { * * @param jsonString the json string that represents the permission. */ - public CosmosPermissionSettings(String jsonString) { + CosmosPermissionProperties(String jsonString) { super(jsonString); } @@ -75,7 +75,7 @@ public String resourceLink() { * * @param resourceLink the resource link. */ - public CosmosPermissionSettings resourceLink(String resourceLink) { + public CosmosPermissionProperties resourceLink(String resourceLink) { super.set(Constants.Properties.RESOURCE_LINK, resourceLink); return this; } @@ -95,21 +95,12 @@ public PermissionMode permissionMode() { * * @param permissionMode the permission mode. */ - public CosmosPermissionSettings permissionMode(PermissionMode permissionMode) { + public CosmosPermissionProperties permissionMode(PermissionMode permissionMode) { this.set(Constants.Properties.PERMISSION_MODE, permissionMode.toString().toLowerCase()); return this; } - /** - * Gets the access token granting the defined permission. - * - * @return the access token. - */ - public String token() { - return super.getString(Constants.Properties.TOKEN); - } - //TODO: need value from JsonSerializable // /** // * Gets the resource partition key associated with this permission object. @@ -130,10 +121,10 @@ public String token() { /** * Sets the resource partition key associated with this permission object. * - * @param partitionkey the partition key. + * @param partitionKey the partition key. */ - public CosmosPermissionSettings resourcePartitionKey(PartitionKey partitionkey) { - super.set(Constants.Properties.RESOURCE_PARTITION_KEY, partitionkey.getInternalPartitionKey().toJson()); + public CosmosPermissionProperties resourcePartitionKey(PartitionKey partitionKey) { + super.set(Constants.Properties.RESOURCE_PARTITION_KEY, partitionKey.getInternalPartitionKey().toJson()); return this; } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java index c051939992ded..d1cfccd9f0ece 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos; -public class CosmosPermissionResponse extends CosmosResponse { +public class CosmosPermissionResponse extends CosmosResponse { CosmosPermission permissionClient; CosmosPermissionResponse(ResourceResponse response, CosmosUser cosmosUser) { @@ -30,17 +30,17 @@ public class CosmosPermissionResponse extends CosmosResponse execute(Object[] procedureParams, Req * @param options the request options. * @return an {@link Mono} containing the single resource response with the replaced stored procedure or an error. */ - public Mono replace(CosmosStoredProcedureSettings storedProcedureSettings, + public Mono replace(CosmosStoredProcedureProperties storedProcedureSettings, RequestOptions options) { return cosmosContainer.getDatabase() .getDocClientWrapper() diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java index b547d5f3895e8..f1691c415fe3b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos; -public class CosmosStoredProcedureResponse extends CosmosResponse { +public class CosmosStoredProcedureResponse extends CosmosResponse { private CosmosStoredProcedure storedProcedure; private StoredProcedureResponse storedProcedureResponse; @@ -30,7 +30,7 @@ public class CosmosStoredProcedureResponse extends CosmosResponse response, CosmosContainer cosmosContainer) { super(response); if(response.getResource() != null){ - super.resourceSettings(new CosmosStoredProcedureSettings(response)); + super.resourceSettings(new CosmosStoredProcedureProperties(response)); storedProcedure = new CosmosStoredProcedure(resourceSettings().id(), cosmosContainer); } } @@ -41,10 +41,10 @@ public class CosmosStoredProcedureResponse extends CosmosResponse read(RequestOptions options) { * @param options the request options. * @return an {@link Mono} containing the single resource response with the replaced cosmos trigger or an error. */ - public Mono replace(CosmosTriggerSettings triggerSettings, RequestOptions options) { + public Mono replace(CosmosTriggerProperties triggerSettings, RequestOptions options) { return container.getDatabase() .getDocClientWrapper() .replaceTrigger(new Trigger(triggerSettings.toJson()), options) diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java index e5cac87cae436..c15d0c49181a2 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java @@ -22,27 +22,27 @@ */ package com.azure.data.cosmos; -public class CosmosTriggerResponse extends CosmosResponse { +public class CosmosTriggerResponse extends CosmosResponse { - private CosmosTriggerSettings cosmosTriggerSettings; + private CosmosTriggerProperties cosmosTriggerProperties; private CosmosTrigger cosmosTrigger; CosmosTriggerResponse(ResourceResponse response, CosmosContainer container) { super(response); if(response.getResource() != null) { - super.resourceSettings(new CosmosTriggerSettings(response)); - cosmosTriggerSettings = new CosmosTriggerSettings(response); - cosmosTrigger = new CosmosTrigger(cosmosTriggerSettings.id(), container); + super.resourceSettings(new CosmosTriggerProperties(response)); + cosmosTriggerProperties = new CosmosTriggerProperties(response); + cosmosTrigger = new CosmosTrigger(cosmosTriggerProperties.id(), container); } } /** - * Gets the cosmos trigger settings or null + * Gets the cosmos trigger properties or null * - * @return {@link CosmosTriggerSettings} + * @return {@link CosmosTriggerProperties} */ - public CosmosTriggerSettings settings() { - return cosmosTriggerSettings; + public CosmosTriggerProperties properties() { + return cosmosTriggerProperties; } /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java index 0424c37de31b9..36cafd51b737c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java @@ -37,7 +37,7 @@ public Mono read(RequestOptions options) { * @param options the request options * @return a {@link Mono} containing the single resource response with the replaced user or an error. */ - public Mono replace(CosmosUserSettings userSettings, RequestOptions options) { + public Mono replace(CosmosUserProperties userSettings, RequestOptions options) { return this.database.getDocClientWrapper() .replaceUser(userSettings.getV2User(), options) .map(response -> new CosmosUserResponse(response, database)).single(); @@ -66,7 +66,7 @@ public Mono delete(RequestOptions options) { * @param options the request options. * @return an {@link Mono} containing the single resource response with the created permission or an error. */ - public Mono createPermission(CosmosPermissionSettings permissionSettings, CosmosPermissionsRequestOptions options) { + public Mono createPermission(CosmosPermissionProperties permissionSettings, CosmosPermissionsRequestOptions options) { if(options == null){ options = new CosmosPermissionsRequestOptions(); } @@ -88,7 +88,7 @@ public Mono createPermission(CosmosPermissionSettings * @param options the request options. * @return an {@link Mono} containing the single resource response with the upserted permission or an error. */ - public Mono upsertPermission(CosmosPermissionSettings permissionSettings, CosmosPermissionsRequestOptions options) { + public Mono upsertPermission(CosmosPermissionProperties permissionSettings, CosmosPermissionsRequestOptions options) { Permission permission = permissionSettings.getV2Permissions(); if(options == null){ options = new CosmosPermissionsRequestOptions(); @@ -110,10 +110,10 @@ public Mono upsertPermission(CosmosPermissionSettings * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the read permissions or an error. */ - public Flux> listPermissions(FeedOptions options) { + public Flux> listPermissions(FeedOptions options) { return getDatabase().getDocClientWrapper() .readPermissions(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionSettings.getFromV2Results(response.results()), + .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionProperties.getFromV2Results(response.results()), response.responseHeaders())); } @@ -128,10 +128,10 @@ public Flux> listPermissions(FeedOptions * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the obtained permissions or an error. */ - public Flux> queryPermissions(String query, FeedOptions options) { + public Flux> queryPermissions(String query, FeedOptions options) { return getDatabase().getDocClientWrapper() .queryPermissions(getLink(), query, options) - .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionSettings.getFromV2Results(response.results()), + .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionProperties.getFromV2Results(response.results()), response.responseHeaders())); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java index b17afd20f11fd..6f014fe020c7a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java @@ -63,7 +63,7 @@ public Mono read(RequestOptions options) { * @return an {@link Mono} containing the single resource response with the replaced cosmos user defined function * or an error. */ - public Mono replace(CosmosUserDefinedFunctionSettings udfSettings, + public Mono replace(CosmosUserDefinedFunctionProperties udfSettings, RequestOptions options) { return container.getDatabase() .getDocClientWrapper() diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java index ce58d4c5d5272..d5d578cc925e9 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java @@ -22,17 +22,17 @@ */ package com.azure.data.cosmos; -public class CosmosUserDefinedFunctionResponse extends CosmosResponse { +public class CosmosUserDefinedFunctionResponse extends CosmosResponse { - private CosmosUserDefinedFunctionSettings cosmosUserDefinedFunctionSettings; + private CosmosUserDefinedFunctionProperties cosmosUserDefinedFunctionProperties; private CosmosUserDefinedFunction cosmosUserDefinedFunction; CosmosUserDefinedFunctionResponse(ResourceResponse response, CosmosContainer container) { super(response); if(response.getResource() != null) { - super.resourceSettings(new CosmosUserDefinedFunctionSettings(response)); - cosmosUserDefinedFunctionSettings = new CosmosUserDefinedFunctionSettings(response); - cosmosUserDefinedFunction = new CosmosUserDefinedFunction(cosmosUserDefinedFunctionSettings.id(), container); + super.resourceSettings(new CosmosUserDefinedFunctionProperties(response)); + cosmosUserDefinedFunctionProperties = new CosmosUserDefinedFunctionProperties(response); + cosmosUserDefinedFunction = new CosmosUserDefinedFunction(cosmosUserDefinedFunctionProperties.id(), container); } } @@ -40,8 +40,8 @@ public class CosmosUserDefinedFunctionResponse extends CosmosResponse { +public class CosmosUserResponse extends CosmosResponse { private CosmosUser user; CosmosUserResponse(ResourceResponse response, CosmosDatabase database) { @@ -8,7 +8,7 @@ public class CosmosUserResponse extends CosmosResponse { if(response.getResource() == null){ super.resourceSettings(null); }else{ - super.resourceSettings(new CosmosUserSettings(response)); + super.resourceSettings(new CosmosUserProperties(response)); this.user = new CosmosUser(resourceSettings().id(), database); } } @@ -25,9 +25,9 @@ public CosmosUser user() { /** * Gets the cosmos user settings * - * @return {@link CosmosUserSettings} + * @return {@link CosmosUserProperties} */ - public CosmosUserSettings settings(){ + public CosmosUserProperties settings(){ return resourceSettings(); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java index a76633e5c7df9..c8c8d2cf839dc 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.CosmosDatabaseResponse; @@ -145,7 +145,7 @@ Mono createItem(CosmosContainer containerLink, Object docume * @param options the {@link CosmosContainerRequestOptions} for this request; it can be set as null. * @return an {@link Mono} containing the read container settings. */ - Mono readContainerSettings(CosmosContainer containerLink, CosmosContainerRequestOptions options); + Mono readContainerSettings(CosmosContainer containerLink, CosmosContainerRequestOptions options); /** * @return the Cosmos container client. diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java index b5e584f8c7ae6..c31297d4cec98 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.CosmosDatabaseResponse; @@ -152,9 +152,9 @@ public URI getServiceEndpoint() { } @Override - public Mono readContainerSettings(CosmosContainer containerLink, CosmosContainerRequestOptions options) { + public Mono readContainerSettings(CosmosContainer containerLink, CosmosContainerRequestOptions options) { return containerLink.read(options) - .map(cosmosContainerResponse -> cosmosContainerResponse.settings()); + .map(cosmosContainerResponse -> cosmosContainerResponse.properties()); } @Override diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java index b874bf4261ec6..0fe7ad21152f8 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java @@ -355,10 +355,10 @@ private Mono getLeaseStoreManager() { return this.leaseContextClient.readContainerSettings(this.leaseContextClient.getContainerClient(), null) .flatMap( collectionSettings -> { boolean isPartitioned = - collectionSettings.partitionKey() != null && - collectionSettings.partitionKey().paths() != null && - collectionSettings.partitionKey().paths().size() > 0; - if (!isPartitioned || (collectionSettings.partitionKey().paths().size() != 1 || !collectionSettings.partitionKey().paths().get(0).equals("/id"))) { + collectionSettings.partitionKeyDefinition() != null && + collectionSettings.partitionKeyDefinition().paths() != null && + collectionSettings.partitionKeyDefinition().paths().size() > 0; + if (!isPartitioned || (collectionSettings.partitionKeyDefinition().paths().size() != 1 || !collectionSettings.partitionKeyDefinition().paths().get(0).equals("/id"))) { // throw new IllegalArgumentException("The lease collection, if partitioned, must have partition key equal to id."); return Mono.error(new IllegalArgumentException("The lease collection must have partition key equal to id.")); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java index 855369da1e6e3..6ba222f2311e0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java @@ -24,6 +24,7 @@ import com.azure.data.cosmos.AccessCondition; import com.azure.data.cosmos.AccessConditionType; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosItem; @@ -108,7 +109,7 @@ public Mono acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); CosmosItemProperties containerDocument = new CosmosItemProperties(); containerDocument.id(lockId); - containerDocument.set(com.azure.data.cosmos.internal.Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); + BridgeInternal.setProperty(containerDocument, com.azure.data.cosmos.internal.Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); DocumentServiceLeaseStore self = this; diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosBridgeInternal.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosBridgeInternal.java index f8f8b30832416..033c263328e99 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosBridgeInternal.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosBridgeInternal.java @@ -8,8 +8,8 @@ public static String getLink(CosmosResource resource) { return resource.getLink(); } - public static DocumentCollection toDocumentCollection(CosmosContainerSettings cosmosContainerSettings) { - return new DocumentCollection(cosmosContainerSettings.toJson()); + public static DocumentCollection toDocumentCollection(CosmosContainerProperties cosmosContainerProperties) { + return new DocumentCollection(cosmosContainerProperties.toJson()); } public static AsyncDocumentClient getAsyncDocumentClient(CosmosClient client) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java index 27628ef747527..172cc349a761a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java @@ -91,7 +91,7 @@ private static CosmosDatabaseForTest from(CosmosDatabase db) { } public static CosmosDatabaseForTest create(DatabaseManager client) { - CosmosDatabaseSettings dbDef = new CosmosDatabaseSettings(generateId()); + CosmosDatabaseProperties dbDef = new CosmosDatabaseProperties(generateId()); CosmosDatabase db = client.createDatabase(dbDef).block().database(); CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.from(db); @@ -101,12 +101,12 @@ public static CosmosDatabaseForTest create(DatabaseManager client) { public static void cleanupStaleTestDatabases(DatabaseManager client) { logger.info("Cleaning stale test databases ..."); - List dbs = client.queryDatabases( + List dbs = client.queryDatabases( new SqlQuerySpec("SELECT * FROM c WHERE STARTSWITH(c.id, @PREFIX)", new SqlParameterCollection(new SqlParameter("@PREFIX", CosmosDatabaseForTest.SHARED_DB_ID_PREFIX)))) - .flatMap(page -> Flux.fromIterable(page.results())).collectList().block(); + .flatMap(page -> Flux.fromIterable(page.results())).collectList().block(); - for (CosmosDatabaseSettings db : dbs) { + for (CosmosDatabaseProperties db : dbs) { assertThat(db.id()).startsWith(CosmosDatabaseForTest.SHARED_DB_ID_PREFIX); CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.from(client.getDatabase(db.id())); @@ -123,8 +123,8 @@ private void deleteDatabase(String id) { } public interface DatabaseManager { - Flux> queryDatabases(SqlQuerySpec query); - Mono createDatabase(CosmosDatabaseSettings databaseDefinition); + Flux> queryDatabases(SqlQuerySpec query); + Mono createDatabase(CosmosDatabaseProperties databaseDefinition); CosmosDatabase getDatabase(String id); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java index eefb4fa49401a..b3e8e6b2a714f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java @@ -44,7 +44,6 @@ import org.testng.annotations.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; import java.io.IOException; import java.net.URI; @@ -201,7 +200,7 @@ public void testNonPartitionedCollectionOperations() throws Exception { validateQuerySuccess(queryFlux, queryValidator); String documentCreatedBySprocId = "testDoc"; - CosmosStoredProcedureSettings sproc = new CosmosStoredProcedureSettings( + CosmosStoredProcedureProperties sproc = new CosmosStoredProcedureProperties( "{" + " 'id': '" +UUID.randomUUID().toString() + "'," + " 'body':'" + @@ -265,7 +264,7 @@ public void testNonPartitionedCollectionOperations() throws Exception { public void testMultiPartitionCollectionReadDocumentWithNoPk() throws InterruptedException { String partitionedCollectionId = "PartitionedCollection" + UUID.randomUUID().toString(); String IdOfDocumentWithNoPk = UUID.randomUUID().toString(); - CosmosContainerSettings containerSettings = new CosmosContainerSettings(partitionedCollectionId, "/mypk"); + CosmosContainerProperties containerSettings = new CosmosContainerProperties(partitionedCollectionId, "/mypk"); CosmosContainer createdContainer = createdDatabase.createContainer(containerSettings).block().container(); CosmosItemProperties cosmosItemProperties = new CosmosItemProperties(); cosmosItemProperties.id(IdOfDocumentWithNoPk); diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java index 0080e5ad5a4ee..8145f15a9b85b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java @@ -63,21 +63,21 @@ public void validate(T resourceResponse) { private Resource getResource(T resourceResponse) { if (resourceResponse instanceof CosmosDatabaseResponse) { - return ((CosmosDatabaseResponse)resourceResponse).settings(); + return ((CosmosDatabaseResponse)resourceResponse).properties(); } else if (resourceResponse instanceof CosmosContainerResponse) { - return ((CosmosContainerResponse)resourceResponse).settings(); + return ((CosmosContainerResponse)resourceResponse).properties(); } else if (resourceResponse instanceof CosmosItemResponse) { return ((CosmosItemResponse)resourceResponse).properties(); } else if (resourceResponse instanceof CosmosStoredProcedureResponse) { - return ((CosmosStoredProcedureResponse)resourceResponse).settings(); + return ((CosmosStoredProcedureResponse)resourceResponse).properties(); } else if (resourceResponse instanceof CosmosTriggerResponse) { - return ((CosmosTriggerResponse)resourceResponse).settings(); + return ((CosmosTriggerResponse)resourceResponse).properties(); } else if (resourceResponse instanceof CosmosUserDefinedFunctionResponse) { return ((CosmosUserDefinedFunctionResponse)resourceResponse).settings(); } else if (resourceResponse instanceof CosmosUserResponse) { return ((CosmosUserResponse)resourceResponse).settings(); } else if (resourceResponse instanceof CosmosPermissionResponse) { - return ((CosmosPermissionResponse) resourceResponse).settings(); + return ((CosmosPermissionResponse) resourceResponse).properties(); } return null; } @@ -98,9 +98,9 @@ public Builder indexingMode(IndexingMode mode) { @Override public void validate(CosmosContainerResponse resourceResponse) { - assertThat(resourceResponse.settings()).isNotNull(); - assertThat(resourceResponse.settings().indexingPolicy()).isNotNull(); - assertThat(resourceResponse.settings().indexingPolicy().indexingMode()).isEqualTo(mode); + assertThat(resourceResponse.properties()).isNotNull(); + assertThat(resourceResponse.properties().indexingPolicy()).isNotNull(); + assertThat(resourceResponse.properties().indexingPolicy().indexingMode()).isEqualTo(mode); } }); return this; @@ -122,7 +122,7 @@ public Builder withCompositeIndexes(Collection> comp @Override public void validate(CosmosContainerResponse resourceResponse) { - Iterator> compositeIndexesReadIterator = resourceResponse.settings() + Iterator> compositeIndexesReadIterator = resourceResponse.properties() .indexingPolicy().compositeIndexes().iterator(); Iterator> compositeIndexesWrittenIterator = compositeIndexesWritten.iterator(); @@ -160,7 +160,7 @@ public Builder withSpatialIndexes(Collection spatialIndexes) { @Override public void validate(CosmosContainerResponse resourceResponse) { - Iterator spatialIndexesReadIterator = resourceResponse.settings() + Iterator spatialIndexesReadIterator = resourceResponse.properties() .indexingPolicy().spatialIndexes().iterator(); Iterator spatialIndexesWrittenIterator = spatialIndexes.iterator(); @@ -203,7 +203,7 @@ public Builder withStoredProcedureBody(String storedProcedureBody) { @Override public void validate(CosmosStoredProcedureResponse resourceResponse) { - assertThat(resourceResponse.settings().body()).isEqualTo(storedProcedureBody); + assertThat(resourceResponse.properties().body()).isEqualTo(storedProcedureBody); } }); return this; @@ -226,7 +226,7 @@ public Builder withTriggerBody(String functionBody) { @Override public void validate(CosmosTriggerResponse resourceResponse) { - assertThat(resourceResponse.settings().body()).isEqualTo(functionBody); + assertThat(resourceResponse.properties().body()).isEqualTo(functionBody); } }); return this; @@ -237,8 +237,8 @@ public Builder withTriggerInternals(TriggerType type, TriggerOperation op) { @Override public void validate(CosmosTriggerResponse resourceResponse) { - assertThat(resourceResponse.settings().triggerType()).isEqualTo(type); - assertThat(resourceResponse.settings().triggerOperation()).isEqualTo(op); + assertThat(resourceResponse.properties().triggerType()).isEqualTo(type); + assertThat(resourceResponse.properties().triggerOperation()).isEqualTo(op); } }); return this; @@ -260,7 +260,7 @@ public Builder withPermissionMode(PermissionMode mode) { @Override public void validate(CosmosPermissionResponse resourceResponse) { - assertThat(resourceResponse.settings().permissionMode()).isEqualTo(mode); + assertThat(resourceResponse.properties().permissionMode()).isEqualTo(mode); } }); return this; @@ -272,7 +272,7 @@ public Builder withPermissionResourceLink(String resourceLink) { @Override public void validate(CosmosPermissionResponse resourceResponse) { - assertThat(resourceResponse.settings().resourceLink()).isEqualTo(resourceLink); + assertThat(resourceResponse.properties().resourceLink()).isEqualTo(resourceLink); } }); return this; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java index 7a15af63df499..781afe1662d77 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java @@ -28,8 +28,8 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosContainerRequestOptions; -import com.azure.data.cosmos.CosmosContainerSettings; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.DataType; @@ -78,7 +78,7 @@ public String getCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } - static protected CosmosContainerSettings getCollectionDefinition() { + static protected CosmosContainerProperties getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); @@ -100,7 +100,7 @@ static protected CosmosContainerSettings getCollectionDefinition() { includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings( + CosmosContainerProperties collectionDefinition = new CosmosContainerProperties( UUID.randomUUID().toString(), partitionKeyDef); collectionDefinition.indexingPolicy(indexingPolicy); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java index 2af6909ed5ede..44432fe875a48 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java @@ -27,8 +27,8 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosContainerRequestOptions; -import com.azure.data.cosmos.CosmosContainerSettings; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedOptions; @@ -67,13 +67,13 @@ public String getCollectionLink() { return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } - private static CosmosContainerSettings getSinglePartitionCollectionDefinition() { + private static CosmosContainerProperties getSinglePartitionCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); partitionKeyDef.paths(paths); - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } @@ -176,7 +176,7 @@ public void beforeClass() throws Exception { // for bulk insert and later queries. Offer offer = rxClient.queryOffers( String.format("SELECT * FROM r WHERE r.offerResourceId = '%s'", - createdCollection.read().block().settings().resourceId()) + createdCollection.read().block().properties().resourceId()) , null).take(1).map(FeedResponse::results).single().block().get(0); offer.setThroughput(6000); offer = rxClient.replaceOffer(offer).single().block().getResource(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java index c129312f20eee..1971443a7eec5 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java @@ -27,8 +27,8 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosContainerRequestOptions; -import com.azure.data.cosmos.CosmosContainerSettings; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.SerializationFormattingPolicy; @@ -41,7 +41,6 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; -import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import java.time.Duration; @@ -294,7 +293,7 @@ private CosmosContainer createFeedCollection() { private CosmosContainer createLeaseCollection() { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); options.offerThroughput(400); - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), "/id"); + CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), "/id"); return createCollection(createdDatabase, collectionDefinition, options); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java index 45fa411048c6f..b60f3d1e7622f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java @@ -28,9 +28,9 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.CosmosContainerSettings; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; import com.azure.data.cosmos.CosmosItem; @@ -86,13 +86,13 @@ public Object[][] collectionCrudArgProvider() { }; } - private CosmosContainerSettings getCollectionDefinition(String collectionName) { + private CosmosContainerProperties getCollectionDefinition(String collectionName) { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); partitionKeyDef.paths(paths); - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings( + CosmosContainerProperties collectionDefinition = new CosmosContainerProperties( collectionName, partitionKeyDef); @@ -101,7 +101,7 @@ private CosmosContainerSettings getCollectionDefinition(String collectionName) { @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") public void createCollection(String collectionName) throws InterruptedException { - CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + CosmosContainerProperties collectionDefinition = getCollectionDefinition(collectionName); Mono createObservable = database .createContainer(collectionDefinition); @@ -120,7 +120,7 @@ public void createCollectionWithCompositeIndexAndSpatialSpec() throws Interrupte paths.add("/mypk"); partitionKeyDef.paths(paths); - CosmosContainerSettings collection = new CosmosContainerSettings( + CosmosContainerProperties collection = new CosmosContainerProperties( UUID.randomUUID().toString(), partitionKeyDef); @@ -196,7 +196,7 @@ public void createCollectionWithCompositeIndexAndSpatialSpec() throws Interrupte @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") public void readCollection(String collectionName) throws InterruptedException { - CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + CosmosContainerProperties collectionDefinition = getCollectionDefinition(collectionName); Mono createObservable = database.createContainer(collectionDefinition); CosmosContainer collection = createObservable.block().container(); @@ -221,7 +221,7 @@ public void readCollection_DoesntExist(String collectionName) throws Exception { @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") public void deleteCollection(String collectionName) throws InterruptedException { - CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + CosmosContainerProperties collectionDefinition = getCollectionDefinition(collectionName); Mono createObservable = database.createContainer(collectionDefinition); CosmosContainer collection = createObservable.block().container(); @@ -236,10 +236,10 @@ public void deleteCollection(String collectionName) throws InterruptedException @Test(groups = { "emulator" }, timeOut = TIMEOUT, dataProvider = "collectionCrudArgProvider") public void replaceCollection(String collectionName) throws InterruptedException { // create a collection - CosmosContainerSettings collectionDefinition = getCollectionDefinition(collectionName); + CosmosContainerProperties collectionDefinition = getCollectionDefinition(collectionName); Mono createObservable = database.createContainer(collectionDefinition); CosmosContainer collection = createObservable.block().container(); - CosmosContainerSettings collectionSettings = collection.read().block().settings(); + CosmosContainerProperties collectionSettings = collection.read().block().properties(); // sanity check assertThat(collectionSettings.indexingPolicy().indexingMode()).isEqualTo(IndexingMode.CONSISTENT); @@ -274,7 +274,7 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { paths.add("/mypk"); partitionKeyDef.paths(paths); - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(collectionId, partitionKeyDef); + CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(collectionId, partitionKeyDef); CosmosContainer collection = createCollection(db, collectionDefinition, new CosmosContainerRequestOptions()); CosmosItemProperties document = new CosmosItemProperties(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java index 72244193c26fb..dab43ae26428a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; import com.azure.data.cosmos.FeedOptions; @@ -66,7 +66,7 @@ public void queryCollectionsWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> queryObservable = createdDatabase.queryContainers(query, options); + Flux> queryObservable = createdDatabase.queryContainers(query, options); List expectedCollections = createdCollections.stream() .filter(c -> StringUtils.equals(filterCollectionId, c.id()) ).collect(Collectors.toList()); @@ -75,11 +75,11 @@ public void queryCollectionsWithFilter() throws Exception { int expectedPageSize = (expectedCollections.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedCollections.size()) - .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.read().block().settings().resourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.read().block().properties().resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -93,7 +93,7 @@ public void queryAllCollections() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> queryObservable = createdDatabase.queryContainers(query, options); + Flux> queryObservable = createdDatabase.queryContainers(query, options); List expectedCollections = createdCollections; @@ -101,11 +101,11 @@ public void queryAllCollections() throws Exception { int expectedPageSize = (expectedCollections.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedCollections.size()) - .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.read().block().settings().resourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(expectedCollections.stream().map(d -> d.read().block().properties().resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -118,12 +118,12 @@ public void queryCollections_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdDatabase.queryContainers(query, options); + Flux> queryObservable = createdDatabase.queryContainers(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -139,7 +139,7 @@ public void beforeClass() throws Exception { paths.add("/mypk"); partitionKeyDef.paths(paths); - CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collection = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); createdCollections.add(createCollection(client, databaseId, collection)); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java index dabc68aa942ec..df82cc766a22f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java @@ -26,9 +26,9 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosDatabaseProperties; import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.CosmosDatabaseResponse; -import com.azure.data.cosmos.CosmosDatabaseSettings; import com.azure.data.cosmos.CosmosResponseValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -52,7 +52,7 @@ public DatabaseCrudTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void createDatabase() throws Exception { - CosmosDatabaseSettings databaseDefinition = new CosmosDatabaseSettings(CosmosDatabaseForTest.generateId()); + CosmosDatabaseProperties databaseDefinition = new CosmosDatabaseProperties(CosmosDatabaseForTest.generateId()); databases.add(databaseDefinition.id()); // create the database @@ -66,7 +66,7 @@ public void createDatabase() throws Exception { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void createDatabase_AlreadyExists() throws Exception { - CosmosDatabaseSettings databaseDefinition = new CosmosDatabaseSettings(CosmosDatabaseForTest.generateId()); + CosmosDatabaseProperties databaseDefinition = new CosmosDatabaseProperties(CosmosDatabaseForTest.generateId()); databases.add(databaseDefinition.id()); client.createDatabase(databaseDefinition, new CosmosDatabaseRequestOptions()).block(); @@ -104,7 +104,7 @@ public void readDatabase_DoesntExist() throws Exception { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void deleteDatabase() throws Exception { // create the database - CosmosDatabaseSettings databaseDefinition = new CosmosDatabaseSettings(CosmosDatabaseForTest.generateId()); + CosmosDatabaseProperties databaseDefinition = new CosmosDatabaseProperties(CosmosDatabaseForTest.generateId()); databases.add(databaseDefinition.id()); CosmosDatabase database = client.createDatabase(databaseDefinition, new CosmosDatabaseRequestOptions()).block().database(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java index 5c5028ed38a48..8736cc614fa42 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; -import com.azure.data.cosmos.CosmosDatabaseSettings; +import com.azure.data.cosmos.CosmosDatabaseProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import org.apache.commons.lang3.StringUtils; @@ -62,20 +62,20 @@ public void queryDatabaseWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> queryObservable = client.queryDatabases(query, options); + Flux> queryObservable = client.queryDatabases(query, options); - List expectedDatabases = createdDatabases.stream() - .filter(d -> StringUtils.equals(databaseId1, d.id()) ).map(d -> d.read().block().settings()).collect(Collectors.toList()); + List expectedDatabases = createdDatabases.stream() + .filter(d -> StringUtils.equals(databaseId1, d.id()) ).map(d -> d.read().block().properties()).collect(Collectors.toList()); assertThat(expectedDatabases).isNotEmpty(); int expectedPageSize = (expectedDatabases.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDatabases.size()) .exactlyContainsInAnyOrder(expectedDatabases.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -91,19 +91,19 @@ public void queryAllDatabase() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> queryObservable = client.queryDatabases(query, options); + Flux> queryObservable = client.queryDatabases(query, options); - List expectedDatabases = createdDatabases.stream().map(d -> d.read().block().settings()).collect(Collectors.toList()); + List expectedDatabases = createdDatabases.stream().map(d -> d.read().block().properties()).collect(Collectors.toList()); assertThat(expectedDatabases).isNotEmpty(); int expectedPageSize = (expectedDatabases.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDatabases.size()) .exactlyContainsInAnyOrder(expectedDatabases.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -116,12 +116,12 @@ public void queryDatabases_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = client.queryDatabases(query, options); + Flux> queryObservable = client.queryDatabases(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java index 0e9b48f325bd4..b751066eb5d14 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java @@ -29,9 +29,9 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.CosmosContainerSettings; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; import com.azure.data.cosmos.PartitionKeyDefinition; @@ -67,15 +67,15 @@ public MultiMasterConflictResolutionTest(CosmosClientBuilder clientBuilder) { public void conflictResolutionPolicyCRUD() { // default last writer wins, path _ts - CosmosContainerSettings collectionSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collectionSettings = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); CosmosContainer collection = database.createContainer(collectionSettings, new CosmosContainerRequestOptions()).block().container(); - collectionSettings = collection.read().block().settings(); + collectionSettings = collection.read().block().properties(); assertThat(collectionSettings.conflictResolutionPolicy().mode()).isEqualTo(ConflictResolutionMode.LAST_WRITER_WINS); // LWW without path specified, should default to _ts collectionSettings.conflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy()); - collectionSettings = collection.replace(collectionSettings, null).block().settings(); + collectionSettings = collection.replace(collectionSettings, null).block().properties(); assertThat(collectionSettings.conflictResolutionPolicy().mode()).isEqualTo(ConflictResolutionMode.LAST_WRITER_WINS); assertThat(collectionSettings.conflictResolutionPolicy().conflictResolutionPath()).isEqualTo("/_ts"); @@ -91,7 +91,7 @@ public void conflictResolutionPolicyCRUD() { collectionSettings.conflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy("/a/b")); try { - collectionSettings = collection.replace(collectionSettings, null).block().settings(); + collectionSettings = collection.replace(collectionSettings, null).block().properties(); fail("Expected exception on invalid path."); } catch (Exception e) { @@ -109,7 +109,7 @@ public void conflictResolutionPolicyCRUD() { collectionSettings.conflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy("someText")); try { - collectionSettings = collection.replace(collectionSettings, null).block().settings(); + collectionSettings = collection.replace(collectionSettings, null).block().properties(); fail("Expected exception on invalid path."); } catch (Exception e) { // when (e.StatusCode == HttpStatusCode.BadRequest) @@ -132,14 +132,14 @@ public void conflictResolutionPolicyCRUD() { private void testConflictResolutionPolicyRequiringPath(ConflictResolutionMode conflictResolutionMode, String[] paths, String[] expectedPaths) { for (int i = 0; i < paths.length; i++) { - CosmosContainerSettings collectionSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collectionSettings = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); if (conflictResolutionMode == ConflictResolutionMode.LAST_WRITER_WINS) { collectionSettings.conflictResolutionPolicy(ConflictResolutionPolicy.createLastWriterWinsPolicy(paths[i])); } else { collectionSettings.conflictResolutionPolicy(ConflictResolutionPolicy.createCustomPolicy(paths[i])); } - collectionSettings = database.createContainer(collectionSettings, new CosmosContainerRequestOptions()).block().settings(); + collectionSettings = database.createContainer(collectionSettings, new CosmosContainerRequestOptions()).block().properties(); assertThat(collectionSettings.conflictResolutionPolicy().mode()).isEqualTo(conflictResolutionMode); if (conflictResolutionMode == ConflictResolutionMode.LAST_WRITER_WINS) { @@ -152,7 +152,7 @@ private void testConflictResolutionPolicyRequiringPath(ConflictResolutionMode co @Test(groups = "multi-master", timeOut = TIMEOUT) public void invalidConflictResolutionPolicy_LastWriterWinsWithStoredProc() throws Exception { - CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collection = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); // LWW without path specified, should default to _ts ConflictResolutionPolicy policy = BridgeUtils.createConflictResolutionPolicy(); @@ -174,7 +174,7 @@ public void invalidConflictResolutionPolicy_LastWriterWinsWithStoredProc() throw @Test(groups = "multi-master", timeOut = TIMEOUT) public void invalidConflictResolutionPolicy_CustomWithPath() throws Exception { - CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collection = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); // LWW without path specified, should default to _ts ConflictResolutionPolicy policy = BridgeUtils.createConflictResolutionPolicy(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java index 3e8df4deff1d7..31a662f1d5006 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java @@ -30,7 +30,7 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.FeedOptions; @@ -210,7 +210,7 @@ public void queryDocumentsWithMultiOrder() throws CosmosClientException, Interru feedOptions.enableCrossPartitionQuery(true); boolean[] booleanValues = new boolean[] {true, false}; - CosmosContainerSettings containerSettings = documentCollection.read().block().settings(); + CosmosContainerProperties containerSettings = documentCollection.read().block().properties(); Iterator> compositeIndexesIterator = containerSettings.indexingPolicy().compositeIndexes().iterator(); while (compositeIndexesIterator.hasNext()) { ArrayList compositeIndex = compositeIndexesIterator.next(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java index 661a35e9bc0ed..858a59a8312f6 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java @@ -28,10 +28,10 @@ import com.azure.data.cosmos.CosmosDatabaseForTest; import com.azure.data.cosmos.CosmosPermission; import com.azure.data.cosmos.CosmosPermissionResponse; -import com.azure.data.cosmos.CosmosPermissionSettings; +import com.azure.data.cosmos.CosmosPermissionProperties; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosUser; -import com.azure.data.cosmos.CosmosUserSettings; +import com.azure.data.cosmos.CosmosUserProperties; import com.azure.data.cosmos.PermissionMode; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -60,7 +60,7 @@ public void createPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); //create permission - CosmosPermissionSettings permissionSettings = new CosmosPermissionSettings() + CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .id(UUID.randomUUID().toString()) .permissionMode(PermissionMode.READ) .resourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); @@ -82,7 +82,7 @@ public void readPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); // create permission - CosmosPermissionSettings permissionSettings = new CosmosPermissionSettings() + CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .id(UUID.randomUUID().toString()) .permissionMode(PermissionMode.READ) .resourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); @@ -90,7 +90,7 @@ public void readPermission() throws Exception { .block(); // read Permission - Mono readObservable = readBackPermission.getPermission().read(null); + Mono readObservable = readBackPermission.permission().read(null); // validate permission read CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -108,14 +108,14 @@ public void deletePermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); // create permission - CosmosPermissionSettings permissionSettings = new CosmosPermissionSettings() + CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .id(UUID.randomUUID().toString()) .permissionMode(PermissionMode.READ) .resourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); CosmosPermissionResponse readBackPermission = createdUser.createPermission(permissionSettings, null) .block(); // delete - Mono deleteObservable = readBackPermission.getPermission() + Mono deleteObservable = readBackPermission.permission() .delete(null); // validate delete permission @@ -127,7 +127,7 @@ public void deletePermission() throws Exception { waitIfNeededForReplicasToCatchUp(clientBuilder()); // attempt to read the permission which was deleted - Mono readObservable = readBackPermission.getPermission() + Mono readObservable = readBackPermission.permission() .read( null); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); validateFailure(readObservable, notFoundValidator); @@ -139,15 +139,15 @@ public void upsertPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.id(), getUserDefinition()); // create permission - CosmosPermissionSettings permissionSettings = new CosmosPermissionSettings() + CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .id(UUID.randomUUID().toString()) .permissionMode(PermissionMode.READ) .resourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); CosmosPermissionResponse readBackPermissionResponse = createdUser.createPermission(permissionSettings, null) .block(); - CosmosPermissionSettings readBackPermission = readBackPermissionResponse.settings(); + CosmosPermissionProperties readBackPermission = readBackPermissionResponse.properties(); // read Permission - Mono readObservable = readBackPermissionResponse.getPermission() + Mono readObservable = readBackPermissionResponse.permission() .read( null); // validate permission creation @@ -181,19 +181,19 @@ public void replacePermission() throws Exception { String id = UUID.randomUUID().toString(); // create permission - CosmosPermissionSettings permissionSettings = new CosmosPermissionSettings() + CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .id(id) .permissionMode(PermissionMode.READ) .resourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); CosmosPermissionResponse readBackPermissionResponse = createdUser.createPermission(permissionSettings, null) .block(); // read Permission - Mono readObservable = readBackPermissionResponse.getPermission() + Mono readObservable = readBackPermissionResponse.permission() .read(null); // validate permission creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() - .withId(readBackPermissionResponse.getPermission().id()) + .withId(readBackPermissionResponse.permission().id()) .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() @@ -201,11 +201,11 @@ public void replacePermission() throws Exception { validateSuccess(readObservable, validator); //update permission - CosmosPermissionSettings readBackPermission = readBackPermissionResponse.settings(); + CosmosPermissionProperties readBackPermission = readBackPermissionResponse.properties(); readBackPermission = readBackPermission.permissionMode(PermissionMode.ALL); CosmosPermission cosmosPermission = createdUser.getPermission(id); - Mono updateObservable = readBackPermissionResponse.getPermission() + Mono updateObservable = readBackPermissionResponse.permission() .replace(readBackPermission, null); // validate permission replace @@ -229,8 +229,8 @@ public void afterClass() { safeClose(client); } - private static CosmosUserSettings getUserDefinition() { - return new CosmosUserSettings() + private static CosmosUserProperties getUserDefinition() { + return new CosmosUserProperties() .id(UUID.randomUUID().toString()); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java index 06c488f0721e9..2d3de3cf4ab9f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java @@ -25,8 +25,8 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosContainerRequestOptions; -import com.azure.data.cosmos.CosmosContainerSettings; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; import com.azure.data.cosmos.FeedOptions; @@ -67,15 +67,15 @@ public void readCollections() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdDatabase.listContainers(options); + Flux> feedObservable = createdDatabase.listContainers(options); int expectedPageSize = (createdCollections.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdCollections.size()) - .exactlyContainsInAnyOrder(createdCollections.stream().map(d -> d.read().block().settings().resourceId()).collect(Collectors.toList())) + .exactlyContainsInAnyOrder(createdCollections.stream().map(d -> d.read().block().properties().resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -104,7 +104,7 @@ public CosmosContainer createCollections(CosmosDatabase database) { ArrayList paths = new ArrayList(); paths.add("/mypk"); partitionKeyDef.paths(paths); - CosmosContainerSettings collection = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collection = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); return database.createContainer(collection, new CosmosContainerRequestOptions()).block().container(); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java index 469a9e99686bb..8a2472a4a366f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java @@ -24,8 +24,8 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; +import com.azure.data.cosmos.CosmosDatabaseProperties; import com.azure.data.cosmos.CosmosDatabaseRequestOptions; -import com.azure.data.cosmos.CosmosDatabaseSettings; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import org.testng.annotations.AfterClass; @@ -42,8 +42,8 @@ public class ReadFeedDatabasesTest extends TestSuiteBase { - private List createdDatabases = new ArrayList<>(); - private List allDatabases = new ArrayList<>(); + private List createdDatabases = new ArrayList<>(); + private List allDatabases = new ArrayList<>(); private CosmosClient client; @@ -58,14 +58,14 @@ public void readDatabases() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = client.listDatabases(options); + Flux> feedObservable = client.listDatabases(options); int expectedPageSize = (allDatabases.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(allDatabases.size()) .exactlyContainsInAnyOrder(allDatabases.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -86,9 +86,9 @@ public void beforeClass() throws URISyntaxException { allDatabases.addAll(createdDatabases); } - public CosmosDatabaseSettings createDatabase(CosmosClient client) { - CosmosDatabaseSettings db = new CosmosDatabaseSettings(UUID.randomUUID().toString()); - return client.createDatabase(db, new CosmosDatabaseRequestOptions()).block().settings(); + public CosmosDatabaseProperties createDatabase(CosmosClient client) { + CosmosDatabaseProperties db = new CosmosDatabaseProperties(UUID.randomUUID().toString()); + return client.createDatabase(db, new CosmosDatabaseRequestOptions()).block().properties(); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java index 36b232b376c9d..166d8a773b883 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosDatabaseSettings; +import com.azure.data.cosmos.CosmosDatabaseProperties; import com.azure.data.cosmos.FeedResponse; import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; @@ -52,21 +52,21 @@ public ReadFeedExceptionHandlingTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readFeedException() throws Exception { - ArrayList dbs = new ArrayList(); - dbs.add(new CosmosDatabaseSettings("db1")); - dbs.add(new CosmosDatabaseSettings("db2")); + ArrayList dbs = new ArrayList(); + dbs.add(new CosmosDatabaseProperties("db1")); + dbs.add(new CosmosDatabaseProperties("db2")); - ArrayList> frps = new ArrayList>(); + ArrayList> frps = new ArrayList>(); frps.add(BridgeInternal.createFeedResponse(dbs, null)); frps.add(BridgeInternal.createFeedResponse(dbs, null)); - Flux> response = Flux.merge(Flux.fromIterable(frps)) + Flux> response = Flux.merge(Flux.fromIterable(frps)) .mergeWith(Flux.error(new CosmosClientException(0))) .mergeWith(Flux.fromIterable(frps)); final CosmosClient mockClient = Mockito.spy(client); Mockito.when(mockClient.listDatabases(null)).thenReturn(response); - TestSubscriber> subscriber = new TestSubscriber>(); + TestSubscriber> subscriber = new TestSubscriber>(); mockClient.listDatabases(null).subscribe(subscriber); assertThat(subscriber.valueCount()).isEqualTo(2); assertThat(subscriber.assertNotComplete()); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java index 4dc2d72556455..dd06878843edd 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; -import com.azure.data.cosmos.CosmosStoredProcedureSettings; +import com.azure.data.cosmos.CosmosStoredProcedureProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import org.testng.annotations.AfterClass; @@ -43,7 +43,7 @@ public class ReadFeedStoredProceduresTest extends TestSuiteBase { private CosmosContainer createdCollection; - private List createdStoredProcedures = new ArrayList<>(); + private List createdStoredProcedures = new ArrayList<>(); private CosmosClient client; @@ -58,19 +58,19 @@ public void readStoredProcedures() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdCollection.listStoredProcedures(options); + Flux> feedObservable = createdCollection.listStoredProcedures(options); int expectedPageSize = (createdStoredProcedures.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .totalSize(createdStoredProcedures.size()) .exactlyContainsInAnyOrder(createdStoredProcedures .stream() .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -94,10 +94,10 @@ public void afterClass() { safeClose(client); } - public CosmosStoredProcedureSettings createStoredProcedures(CosmosContainer cosmosContainer) { - CosmosStoredProcedureSettings sproc = new CosmosStoredProcedureSettings(); + public CosmosStoredProcedureProperties createStoredProcedures(CosmosContainer cosmosContainer) { + CosmosStoredProcedureProperties sproc = new CosmosStoredProcedureProperties(); sproc.id(UUID.randomUUID().toString()); sproc.body("function() {var x = 10;}"); - return cosmosContainer.createStoredProcedure(sproc, new CosmosStoredProcedureRequestOptions()).block().settings(); + return cosmosContainer.createStoredProcedure(sproc, new CosmosStoredProcedureRequestOptions()).block().properties(); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java index eeeb32bb095c8..e58e78ae5ddc1 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; -import com.azure.data.cosmos.CosmosTriggerSettings; +import com.azure.data.cosmos.CosmosTriggerProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.TriggerOperation; @@ -45,7 +45,7 @@ public class ReadFeedTriggersTest extends TestSuiteBase { private CosmosContainer createdCollection; - private List createdTriggers = new ArrayList<>(); + private List createdTriggers = new ArrayList<>(); private CosmosClient client; @@ -60,19 +60,19 @@ public void readTriggers() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdCollection.listTriggers(options); + Flux> feedObservable = createdCollection.listTriggers(options); int expectedPageSize = (createdTriggers.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .totalSize(createdTriggers.size()) .exactlyContainsInAnyOrder(createdTriggers .stream() .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -96,12 +96,12 @@ public void afterClass() { safeClose(client); } - public CosmosTriggerSettings createTriggers(CosmosContainer cosmosContainer) { - CosmosTriggerSettings trigger = new CosmosTriggerSettings(); + public CosmosTriggerProperties createTriggers(CosmosContainer cosmosContainer) { + CosmosTriggerProperties trigger = new CosmosTriggerProperties(); trigger.id(UUID.randomUUID().toString()); trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - return cosmosContainer.createTrigger(trigger, new CosmosRequestOptions()).block().settings(); + return cosmosContainer.createTrigger(trigger, new CosmosRequestOptions()).block().properties(); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java index 7f7e1e177d000..9b64e8408f23f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; -import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; +import com.azure.data.cosmos.CosmosUserDefinedFunctionProperties; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; @@ -45,7 +45,7 @@ public class ReadFeedUdfsTest extends TestSuiteBase { private Database createdDatabase; private CosmosContainer createdCollection; - private List createdUserDefinedFunctions = new ArrayList<>(); + private List createdUserDefinedFunctions = new ArrayList<>(); private CosmosClient client; @@ -60,19 +60,19 @@ public void readUserDefinedFunctions() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdCollection.listUserDefinedFunctions(options); + Flux> feedObservable = createdCollection.listUserDefinedFunctions(options); int expectedPageSize = (createdUserDefinedFunctions.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .totalSize(createdUserDefinedFunctions.size()) .exactlyContainsInAnyOrder(createdUserDefinedFunctions .stream() .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -96,8 +96,8 @@ public void afterClass() { safeClose(client); } - public CosmosUserDefinedFunctionSettings createUserDefinedFunctions(CosmosContainer cosmosContainer) { - CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); + public CosmosUserDefinedFunctionProperties createUserDefinedFunctions(CosmosContainer cosmosContainer) { + CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); return cosmosContainer.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().settings(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java index 57e037ff7a423..c3025e76a2ba1 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; -import com.azure.data.cosmos.CosmosUserSettings; +import com.azure.data.cosmos.CosmosUserProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.RequestOptions; @@ -47,7 +47,7 @@ public class ReadFeedUsersTest extends TestSuiteBase { private CosmosDatabase createdDatabase; private CosmosClient client; - private List createdUsers = new ArrayList<>(); + private List createdUsers = new ArrayList<>(); @Factory(dataProvider = "clientBuilders") public ReadFeedUsersTest(CosmosClientBuilder clientBuilder) { @@ -60,15 +60,15 @@ public void readUsers() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdDatabase.listUsers(options); + Flux> feedObservable = createdDatabase.listUsers(options); int expectedPageSize = (createdUsers.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdUsers.size()) .exactlyContainsInAnyOrder(createdUsers.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(feedObservable, validator, FEED_TIMEOUT); @@ -92,8 +92,8 @@ public void afterClass() { safeClose(client); } - public CosmosUserSettings createUsers(CosmosDatabase cosmosDatabase) { - CosmosUserSettings user = new CosmosUserSettings(); + public CosmosUserProperties createUsers(CosmosDatabase cosmosDatabase) { + CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); return cosmosDatabase.createUser(user, new RequestOptions()).block().settings(); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java index 4aa54eb8291d6..96959185d6694 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java @@ -30,7 +30,7 @@ import com.azure.data.cosmos.CosmosStoredProcedure; import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; import com.azure.data.cosmos.CosmosStoredProcedureResponse; -import com.azure.data.cosmos.CosmosStoredProcedureSettings; +import com.azure.data.cosmos.CosmosStoredProcedureProperties; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -54,7 +54,7 @@ public StoredProcedureCrudTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createStoredProcedure() throws Exception { - CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); + CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); @@ -72,7 +72,7 @@ public void createStoredProcedure() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readStoredProcedure() throws Exception { - CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); + CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); CosmosStoredProcedure storedProcedure = container.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); @@ -92,7 +92,7 @@ public void readStoredProcedure() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteStoredProcedure() throws Exception { - CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); + CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java index f1555493f2d0e..e9fe458c42e37 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosStoredProcedureSettings; +import com.azure.data.cosmos.CosmosStoredProcedureProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import org.testng.annotations.AfterClass; @@ -45,7 +45,7 @@ public class StoredProcedureQueryTest extends TestSuiteBase { private CosmosContainer createdCollection; - private List createdStoredProcs = new ArrayList<>(); + private List createdStoredProcs = new ArrayList<>(); private CosmosClient client; @@ -62,18 +62,18 @@ public void queryWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(5); - Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); + Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); - List expectedDocs = createdStoredProcs.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList()); + List expectedDocs = createdStoredProcs.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -86,12 +86,12 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); + Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -104,20 +104,20 @@ public void queryAll() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(3); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); + Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); - List expectedDocs = createdStoredProcs; + List expectedDocs = createdStoredProcs; int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -129,7 +129,7 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); + Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(CosmosClientException.class) @@ -139,9 +139,9 @@ public void invalidQuerySytax() throws Exception { validateQueryFailure(queryObservable, validator); } - public CosmosStoredProcedureSettings createStoredProc(CosmosContainer cosmosContainer) { - CosmosStoredProcedureSettings storedProcedure = getStoredProcedureDef(); - return cosmosContainer.createStoredProcedure(storedProcedure).block().settings(); + public CosmosStoredProcedureProperties createStoredProc(CosmosContainer cosmosContainer) { + CosmosStoredProcedureProperties storedProcedure = getStoredProcedureDef(); + return cosmosContainer.createStoredProcedure(storedProcedure).block().properties(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) @@ -162,8 +162,8 @@ public void afterClass() { safeClose(client); } - private static CosmosStoredProcedureSettings getStoredProcedureDef() { - CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); + private static CosmosStoredProcedureProperties getStoredProcedureDef() { + CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); return storedProcedureDef; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java index 25416f688251a..f548f651c04a8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.rx; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; @@ -29,7 +30,7 @@ import com.azure.data.cosmos.CosmosStoredProcedure; import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; import com.azure.data.cosmos.CosmosStoredProcedureResponse; -import com.azure.data.cosmos.CosmosStoredProcedureSettings; +import com.azure.data.cosmos.CosmosStoredProcedureProperties; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.RequestOptions; import org.testng.annotations.AfterClass; @@ -57,10 +58,10 @@ public StoredProcedureUpsertReplaceTest(CosmosClientBuilder clientBuilder) { public void replaceStoredProcedure() throws Exception { // create a stored procedure - CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings(); + CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); - CosmosStoredProcedureSettings readBackSp = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().settings(); + CosmosStoredProcedureProperties readBackSp = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().properties(); // read stored procedure to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder()); @@ -91,7 +92,7 @@ public void replaceStoredProcedure() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void executeStoredProcedure() throws Exception { // create a stored procedure - CosmosStoredProcedureSettings storedProcedureDef = new CosmosStoredProcedureSettings( + CosmosStoredProcedureProperties storedProcedureDef = BridgeInternal.createCosmosStoredProcedureProperties( "{" + " 'id': '" + UUID.randomUUID().toString() + "'," + " 'body':" + diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index e9bf59a68bff3..531d8d53fc15a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -35,11 +35,11 @@ import com.azure.data.cosmos.CosmosClientTest; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosContainerRequestOptions; -import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; +import com.azure.data.cosmos.CosmosDatabaseProperties; import com.azure.data.cosmos.CosmosDatabaseResponse; -import com.azure.data.cosmos.CosmosDatabaseSettings; import com.azure.data.cosmos.CosmosItem; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemResponse; @@ -47,7 +47,7 @@ import com.azure.data.cosmos.CosmosResponse; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosUser; -import com.azure.data.cosmos.CosmosUserSettings; +import com.azure.data.cosmos.CosmosUserProperties; import com.azure.data.cosmos.DataType; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; @@ -177,12 +177,12 @@ private DatabaseManagerImpl(CosmosClient client) { } @Override - public Flux> queryDatabases(SqlQuerySpec query) { + public Flux> queryDatabases(SqlQuerySpec query) { return client.queryDatabases(query, null); } @Override - public Mono createDatabase(CosmosDatabaseSettings databaseDefinition) { + public Mono createDatabase(CosmosDatabaseProperties databaseDefinition) { return client.createDatabase(databaseDefinition); } @@ -221,10 +221,10 @@ public static void afterSuite() { } protected static void truncateCollection(CosmosContainer cosmosContainer) { - CosmosContainerSettings cosmosContainerSettings = cosmosContainer.read().block().settings(); - String cosmosContainerId = cosmosContainerSettings.id(); + CosmosContainerProperties cosmosContainerProperties = cosmosContainer.read().block().properties(); + String cosmosContainerId = cosmosContainerProperties.id(); logger.info("Truncating collection {} ...", cosmosContainerId); - List paths = cosmosContainerSettings.partitionKey().paths(); + List paths = cosmosContainerProperties.partitionKeyDefinition().paths(); FeedOptions options = new FeedOptions(); options.maxDegreeOfParallelism(-1); options.enableCrossPartitionQuery(true); @@ -319,12 +319,12 @@ protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clien } } - public static CosmosContainer createCollection(CosmosDatabase database, CosmosContainerSettings cosmosContainerSettings, + public static CosmosContainer createCollection(CosmosDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options) { - return database.createContainer(cosmosContainerSettings, options).block().container(); + return database.createContainer(cosmosContainerProperties, options).block().container(); } - private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { + private static CosmosContainerProperties getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes() { final String NUMBER_FIELD = "numberField"; final String STRING_FIELD = "stringField"; final String NUMBER_FIELD_2 = "numberField2"; @@ -343,7 +343,7 @@ private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWith partitionKeyPaths.add("/" + PARTITION_KEY); partitionKeyDefinition.paths(partitionKeyPaths); - CosmosContainerSettings cosmosContainerSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDefinition); + CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDefinition); IndexingPolicy indexingPolicy = new IndexingPolicy(); Collection> compositeIndexes = new ArrayList>(); @@ -432,12 +432,12 @@ private static CosmosContainerSettings getCollectionDefinitionMultiPartitionWith compositeIndexes.add(compositeIndexLongStrings); indexingPolicy.compositeIndexes(compositeIndexes); - cosmosContainerSettings.indexingPolicy(indexingPolicy); + cosmosContainerProperties.indexingPolicy(indexingPolicy); - return cosmosContainerSettings; + return cosmosContainerProperties; } - public static CosmosContainer createCollection(CosmosClient client, String dbId, CosmosContainerSettings collectionDefinition) { + public static CosmosContainer createCollection(CosmosClient client, String dbId, CosmosContainerProperties collectionDefinition) { return client.getDatabase(dbId).createContainer(collectionDefinition).block().container(); } @@ -477,32 +477,32 @@ public void voidBulkInsertBlocking(CosmosContainer cosmosContainer, .block(); } - public static CosmosUser createUser(CosmosClient client, String databaseId, CosmosUserSettings userSettings) { + public static CosmosUser createUser(CosmosClient client, String databaseId, CosmosUserProperties userSettings) { return client.getDatabase(databaseId).read().block().database().createUser(userSettings).block().user(); } - public static CosmosUser safeCreateUser(CosmosClient client, String databaseId, CosmosUserSettings user) { + public static CosmosUser safeCreateUser(CosmosClient client, String databaseId, CosmosUserProperties user) { deleteUserIfExists(client, databaseId, user.id()); return createUser(client, databaseId, user); } - private static CosmosContainer safeCreateCollection(CosmosClient client, String databaseId, CosmosContainerSettings collection, CosmosContainerRequestOptions options) { + private static CosmosContainer safeCreateCollection(CosmosClient client, String databaseId, CosmosContainerProperties collection, CosmosContainerRequestOptions options) { deleteCollectionIfExists(client, databaseId, collection.id()); return createCollection(client.getDatabase(databaseId), collection, options); } - static protected CosmosContainerSettings getCollectionDefinition() { + static protected CosmosContainerProperties getCollectionDefinition() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); paths.add("/mypk"); partitionKeyDef.paths(paths); - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); return collectionDefinition; } - static protected CosmosContainerSettings getCollectionDefinitionWithRangeRangeIndex() { + static protected CosmosContainerProperties getCollectionDefinitionWithRangeRangeIndex() { PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList<>(); paths.add("/mypk"); @@ -523,18 +523,18 @@ static protected CosmosContainerSettings getCollectionDefinitionWithRangeRangeIn includedPaths.add(includedPath); indexingPolicy.setIncludedPaths(includedPaths); - CosmosContainerSettings cosmosContainerSettings = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); - cosmosContainerSettings.indexingPolicy(indexingPolicy); + CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); + cosmosContainerProperties.indexingPolicy(indexingPolicy); - return cosmosContainerSettings; + return cosmosContainerProperties; } public static void deleteCollectionIfExists(CosmosClient client, String databaseId, String collectionId) { CosmosDatabase database = client.getDatabase(databaseId).read().block().database(); - List res = database.queryContainers(String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null) - .flatMap(page -> Flux.fromIterable(page.results())) - .collectList() - .block(); + List res = database.queryContainers(String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null) + .flatMap(page -> Flux.fromIterable(page.results())) + .collectList() + .block(); if (!res.isEmpty()) { deleteCollection(database, collectionId); @@ -582,7 +582,7 @@ public static void deleteDocument(CosmosContainer cosmosContainer, String docume public static void deleteUserIfExists(CosmosClient client, String databaseId, String userId) { CosmosDatabase database = client.getDatabase(databaseId).read().block().database(); - List res = database + List res = database .queryUsers(String.format("SELECT * FROM root r where r.id = '%s'", userId), null) .flatMap(page -> Flux.fromIterable(page.results())) .collectList().block(); @@ -595,25 +595,25 @@ public static void deleteUser(CosmosDatabase database, String userId) { database.getUser(userId).read().block().user().delete(null).block(); } - static private CosmosDatabase safeCreateDatabase(CosmosClient client, CosmosDatabaseSettings databaseSettings) { + static private CosmosDatabase safeCreateDatabase(CosmosClient client, CosmosDatabaseProperties databaseSettings) { safeDeleteDatabase(client.getDatabase(databaseSettings.id())); return client.createDatabase(databaseSettings).block().database(); } static protected CosmosDatabase createDatabase(CosmosClient client, String databaseId) { - CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings(databaseId); + CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); return client.createDatabase(databaseSettings).block().database(); } static protected CosmosDatabase createDatabaseIfNotExists(CosmosClient client, String databaseId) { - List res = client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null) - .flatMap(p -> Flux.fromIterable(p.results())) - .collectList() - .block(); + List res = client.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseId), null) + .flatMap(p -> Flux.fromIterable(p.results())) + .collectList() + .block(); if (res.size() != 0) { return client.getDatabase(databaseId).read().block().database(); } else { - CosmosDatabaseSettings databaseSettings = new CosmosDatabaseSettings(databaseId); + CosmosDatabaseProperties databaseSettings = new CosmosDatabaseProperties(databaseId); return client.createDatabase(databaseSettings).block().database(); } } @@ -629,12 +629,12 @@ static protected void safeDeleteDatabase(CosmosDatabase database) { static protected void safeDeleteAllCollections(CosmosDatabase database) { if (database != null) { - List collections = database.listContainers() - .flatMap(p -> Flux.fromIterable(p.results())) - .collectList() - .block(); + List collections = database.listContainers() + .flatMap(p -> Flux.fromIterable(p.results())) + .collectList() + .block(); - for(CosmosContainerSettings collection: collections) { + for(CosmosContainerProperties collection: collections) { database.getContainer(collection.id()).delete().block(); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java index a2cfa078b19e5..0b88c81b626f4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java @@ -29,8 +29,8 @@ import com.azure.data.cosmos.CosmosResponse; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosTrigger; +import com.azure.data.cosmos.CosmosTriggerProperties; import com.azure.data.cosmos.CosmosTriggerResponse; -import com.azure.data.cosmos.CosmosTriggerSettings; import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; @@ -56,7 +56,7 @@ public TriggerCrudTest(CosmosClientBuilder clientBuilder) { public void createTrigger() throws Exception { // create a trigger - CosmosTriggerSettings trigger = new CosmosTriggerSettings(); + CosmosTriggerProperties trigger = new CosmosTriggerProperties(); trigger.id(UUID.randomUUID().toString()); trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); @@ -77,7 +77,7 @@ public void createTrigger() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readTrigger() throws Exception { // create a trigger - CosmosTriggerSettings trigger = new CosmosTriggerSettings(); + CosmosTriggerProperties trigger = new CosmosTriggerProperties(); trigger.id(UUID.randomUUID().toString()); trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); @@ -101,7 +101,7 @@ public void readTrigger() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteTrigger() throws Exception { // create a trigger - CosmosTriggerSettings trigger = new CosmosTriggerSettings(); + CosmosTriggerProperties trigger = new CosmosTriggerProperties(); trigger.id(UUID.randomUUID().toString()); trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java index f4b7e3b7eb50f..9f499a63ea509 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; -import com.azure.data.cosmos.CosmosTriggerSettings; +import com.azure.data.cosmos.CosmosTriggerProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; @@ -49,7 +49,7 @@ public class TriggerQueryTest extends TestSuiteBase { private CosmosContainer createdCollection; - private static final List createdTriggers = new ArrayList<>(); + private static final List createdTriggers = new ArrayList<>(); private CosmosClient client; @@ -66,9 +66,9 @@ public void queryWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(5); - Flux> queryObservable = createdCollection.queryTriggers(query, options); + Flux> queryObservable = createdCollection.queryTriggers(query, options); - List expectedDocs = createdTriggers + List expectedDocs = createdTriggers .stream() .filter(sp -> filterId.equals(sp.id()) ) .collect(Collectors.toList()); @@ -76,11 +76,11 @@ public void queryWithFilter() throws Exception { int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) .exactlyContainsInAnyOrder(expectedDocs.stream().map(Resource::resourceId).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -93,12 +93,12 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryTriggers(query, options); + Flux> queryObservable = createdCollection.queryTriggers(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -111,22 +111,22 @@ public void queryAll() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(3); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryTriggers(query, options); + Flux> queryObservable = createdCollection.queryTriggers(query, options); createdTriggers.forEach(cosmosTriggerSettings -> logger.info("Created trigger in method: {}", cosmosTriggerSettings.resourceId())); - List expectedDocs = createdTriggers; + List expectedDocs = createdTriggers; int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() .map(Resource::resourceId) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -137,7 +137,7 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryTriggers(query, options); + Flux> queryObservable = createdCollection.queryTriggers(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(CosmosClientException.class) @@ -147,9 +147,9 @@ public void invalidQuerySytax() throws Exception { validateQueryFailure(queryObservable, validator); } - public CosmosTriggerSettings createTrigger(CosmosContainer cosmosContainer) { - CosmosTriggerSettings storedProcedure = getTriggerDef(); - return cosmosContainer.createTrigger(storedProcedure, new CosmosRequestOptions()).block().settings(); + public CosmosTriggerProperties createTrigger(CosmosContainer cosmosContainer) { + CosmosTriggerProperties storedProcedure = getTriggerDef(); + return cosmosContainer.createTrigger(storedProcedure, new CosmosRequestOptions()).block().properties(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) @@ -171,8 +171,8 @@ public void afterClass() { safeClose(client); } - private static CosmosTriggerSettings getTriggerDef() { - CosmosTriggerSettings trigger = new CosmosTriggerSettings(); + private static CosmosTriggerProperties getTriggerDef() { + CosmosTriggerProperties trigger = new CosmosTriggerProperties(); trigger.id(UUID.randomUUID().toString()); trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java index 1b4ab9062182b..7319c383e9906 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java @@ -27,8 +27,8 @@ import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosTriggerProperties; import com.azure.data.cosmos.CosmosTriggerResponse; -import com.azure.data.cosmos.CosmosTriggerSettings; import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; @@ -55,12 +55,12 @@ public TriggerUpsertReplaceTest(CosmosClientBuilder clientBuilder) { public void replaceTrigger() throws Exception { // create a trigger - CosmosTriggerSettings trigger = new CosmosTriggerSettings(); + CosmosTriggerProperties trigger = new CosmosTriggerProperties(); trigger.id(UUID.randomUUID().toString()); trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - CosmosTriggerSettings readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().settings(); + CosmosTriggerProperties readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().properties(); // read trigger to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder()); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java index b97adacc9bd8a..1650eb8fb1bd3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosContainerSettings; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; import com.azure.data.cosmos.CosmosItem; @@ -79,7 +79,7 @@ public void insertWithUniqueIndex() throws Exception { paths.add("/mypk"); partitionKeyDef.paths(paths); - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.paths(ImmutableList.of("/name", "/description")); @@ -135,7 +135,7 @@ public void replaceAndDeleteWithUniqueIndex() throws Exception { paths.add("/mypk"); partitionKeyDef.paths(paths); - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.paths(ImmutableList.of("/name", "/description")); @@ -180,7 +180,7 @@ public void uniqueKeySerializationDeserialization() { paths.add("/mypk"); partitionKeyDef.paths(paths); - CosmosContainerSettings collectionDefinition = new CosmosContainerSettings(UUID.randomUUID().toString(), partitionKeyDef); + CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDef); UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.paths(ImmutableList.of("/name", "/description")); @@ -206,7 +206,7 @@ public void uniqueKeySerializationDeserialization() { CosmosContainer createdCollection = database.createContainer(collectionDefinition).block().container(); - CosmosContainerSettings collection = createdCollection.read().block().settings(); + CosmosContainerProperties collection = createdCollection.read().block().properties(); assertThat(collection.uniqueKeyPolicy()).isNotNull(); assertThat(collection.uniqueKeyPolicy().uniqueKeys()).isNotNull(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java index bce4c3db08865..112b21a97cf95 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java @@ -30,7 +30,7 @@ import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosUser; import com.azure.data.cosmos.CosmosUserResponse; -import com.azure.data.cosmos.CosmosUserSettings; +import com.azure.data.cosmos.CosmosUserProperties; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -55,7 +55,7 @@ public UserCrudTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void createUser() throws Exception { //create user - CosmosUserSettings user = new CosmosUserSettings(); + CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); Mono createObservable = createdDatabase.createUser(user, null); @@ -72,7 +72,7 @@ public void createUser() throws Exception { public void readUser() throws Exception { //create user - CosmosUserSettings user = new CosmosUserSettings(); + CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); CosmosUser readBackUser = createdDatabase.createUser(user, null).block().user(); @@ -92,7 +92,7 @@ public void readUser() throws Exception { @Test(groups = { "emulator" }, timeOut = TIMEOUT) public void deleteUser() throws Exception { //create user - CosmosUserSettings user = new CosmosUserSettings(); + CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); CosmosUser readBackUser = createdDatabase.createUser(user, null).block().user(); @@ -116,7 +116,7 @@ public void deleteUser() throws Exception { public void upsertUser() throws Exception { //create user - CosmosUserSettings user = new CosmosUserSettings(); + CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); Mono upsertObservable = createdDatabase.upsertUser(user, null); @@ -134,10 +134,10 @@ public void upsertUser() throws Exception { public void replaceUser() throws Exception { //create user - CosmosUserSettings user = new CosmosUserSettings(); + CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); - CosmosUserSettings readBackUser = createdDatabase.createUser(user, null).block().settings(); + CosmosUserProperties readBackUser = createdDatabase.createUser(user, null).block().settings(); // read user to validate creation Mono readObservable = createdDatabase.getUser(user.id()).read(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java index 93d2d3748fbe8..0c4794f672393 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java @@ -29,8 +29,8 @@ import com.azure.data.cosmos.CosmosResponse; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosUserDefinedFunction; +import com.azure.data.cosmos.CosmosUserDefinedFunctionProperties; import com.azure.data.cosmos.CosmosUserDefinedFunctionResponse; -import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -52,7 +52,7 @@ public UserDefinedFunctionCrudTest(CosmosClientBuilder clientBuilder) { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createUserDefinedFunction() throws Exception { // create udf - CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); + CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); @@ -70,7 +70,7 @@ public void createUserDefinedFunction() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readUserDefinedFunction() throws Exception { // create a udf - CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); + CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); @@ -91,7 +91,7 @@ public void readUserDefinedFunction() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deleteUserDefinedFunction() throws Exception { // create a udf - CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); + CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java index 9e83d3474fd10..ac77dbf07619c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; -import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; +import com.azure.data.cosmos.CosmosUserDefinedFunctionProperties; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; @@ -48,7 +48,7 @@ public class UserDefinedFunctionQueryTest extends TestSuiteBase { private Database createdDatabase; private CosmosContainer createdCollection; - private List createdUDF = new ArrayList<>(); + private List createdUDF = new ArrayList<>(); private CosmosClient client; @@ -69,18 +69,18 @@ public void queryWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(5); - Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); + Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); - List expectedDocs = createdUDF.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList()); + List expectedDocs = createdUDF.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedDocs.size()) .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -93,12 +93,12 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); + Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -111,20 +111,20 @@ public void queryAll() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(3); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); + Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); - List expectedDocs = createdUDF; + List expectedDocs = createdUDF; int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator + .Builder() .exactlyContainsInAnyOrder(expectedDocs .stream() .map(d -> d.resourceId()) .collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() + .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -135,7 +135,7 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); + Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(CosmosClientException.class) @@ -145,8 +145,8 @@ public void invalidQuerySytax() throws Exception { validateQueryFailure(queryObservable, validator); } - public CosmosUserDefinedFunctionSettings createUserDefinedFunction(CosmosContainer cosmosContainer) { - CosmosUserDefinedFunctionSettings storedProcedure = getUserDefinedFunctionDef(); + public CosmosUserDefinedFunctionProperties createUserDefinedFunction(CosmosContainer cosmosContainer) { + CosmosUserDefinedFunctionProperties storedProcedure = getUserDefinedFunctionDef(); return cosmosContainer.createUserDefinedFunction(storedProcedure, new CosmosRequestOptions()).block().settings(); } @@ -168,8 +168,8 @@ public void afterClass() { safeClose(client); } - private static CosmosUserDefinedFunctionSettings getUserDefinedFunctionDef() { - CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); + private static CosmosUserDefinedFunctionProperties getUserDefinedFunctionDef() { + CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); return udf; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java index 8fcaf50b9228a..ac41c035b9aa8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java @@ -27,8 +27,8 @@ import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosUserDefinedFunctionProperties; import com.azure.data.cosmos.CosmosUserDefinedFunctionResponse; -import com.azure.data.cosmos.CosmosUserDefinedFunctionSettings; import com.azure.data.cosmos.RequestOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -53,11 +53,11 @@ public UserDefinedFunctionUpsertReplaceTest(CosmosClientBuilder clientBuilder) { public void replaceUserDefinedFunction() throws Exception { // create a udf - CosmosUserDefinedFunctionSettings udf = new CosmosUserDefinedFunctionSettings(); + CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); - CosmosUserDefinedFunctionSettings readBackUdf = null; + CosmosUserDefinedFunctionProperties readBackUdf = null; readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().settings(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java index e748b14d95001..7a12767fb2e1b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; -import com.azure.data.cosmos.CosmosUserSettings; +import com.azure.data.cosmos.CosmosUserProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import org.apache.commons.lang3.StringUtils; @@ -47,7 +47,7 @@ public class UserQueryTest extends TestSuiteBase { public final String databaseId = CosmosDatabaseForTest.generateId(); - private List createdUsers = new ArrayList<>(); + private List createdUsers = new ArrayList<>(); private CosmosClient client; private CosmosDatabase createdDatabase; @@ -65,20 +65,20 @@ public void queryUsersWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(5); - Flux> queryObservable = createdDatabase.queryUsers(query, options); + Flux> queryObservable = createdDatabase.queryUsers(query, options); - List expectedUsers = createdUsers.stream() - .filter(c -> StringUtils.equals(filterUserId, c.id()) ).collect(Collectors.toList()); + List expectedUsers = createdUsers.stream() + .filter(c -> StringUtils.equals(filterUserId, c.id()) ).collect(Collectors.toList()); assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -93,19 +93,19 @@ public void queryAllUsers() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); String databaseLink = Utils.getDatabaseNameLink(databaseId); - Flux> queryObservable = createdDatabase.queryUsers(query, options); + Flux> queryObservable = createdDatabase.queryUsers(query, options); - List expectedUsers = createdUsers; + List expectedUsers = createdUsers; assertThat(expectedUsers).isNotEmpty(); int expectedPageSize = (expectedUsers.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(expectedUsers.size()) .exactlyContainsInAnyOrder(expectedUsers.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -117,12 +117,12 @@ public void queryUsers_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); - Flux> queryObservable = createdDatabase.queryUsers(query, options); + Flux> queryObservable = createdDatabase.queryUsers(query, options); - FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) .numberOfPages(1) - .pageSatisfy(0, new FeedResponseValidator.Builder() + .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); validateQuerySuccess(queryObservable, validator); @@ -135,7 +135,7 @@ public void beforeClass() throws Exception { createdDatabase = createDatabase(client, databaseId); for(int i = 0; i < 5; i++) { - CosmosUserSettings user = new CosmosUserSettings(); + CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); createdUsers.add(createUser(client, databaseId, user).read().block().settings()); } From b5806478c434f3ecfc519943cecc7b876b0fc898 Mon Sep 17 00:00:00 2001 From: Christopher Anderson Date: Tue, 25 Jun 2019 23:06:22 -0700 Subject: [PATCH 49/85] Cosmos Resource refactoring (#205) * Remove CosmosResource * Naming and JavaDocs updates * Move Scripts to CosmosScripts object * Add header * Fix JavaDoc build error * Fix up CosmosScripts + tests --- .../com/azure/data/cosmos/CosmosResource.java | 70 -- .../java/com/azure/data/cosmos/Resource.java | 14 + .../data/cosmos/CosmosBridgeInternal.java | 15 +- .../com/azure/data/cosmos/CosmosConflict.java | 91 ++- .../azure/data/cosmos/CosmosContainer.java | 685 ++++++------------ .../com/azure/data/cosmos/CosmosDatabase.java | 400 +++++----- .../com/azure/data/cosmos/CosmosItem.java | 41 +- .../azure/data/cosmos/CosmosPermission.java | 39 +- .../com/azure/data/cosmos/CosmosScripts.java | 315 ++++++++ .../data/cosmos/CosmosStoredProcedure.java | 42 +- .../com/azure/data/cosmos/CosmosTrigger.java | 43 +- .../com/azure/data/cosmos/CosmosUser.java | 47 +- .../cosmos/CosmosUserDefinedFunction.java | 39 +- .../ChangeFeedContextClientImpl.java | 6 +- .../data/cosmos/CosmosPartitionKeyTests.java | 2 +- .../rx/ReadFeedStoredProceduresTest.java | 17 +- .../data/cosmos/rx/ReadFeedTriggersTest.java | 15 +- .../data/cosmos/rx/ReadFeedUdfsTest.java | 24 +- .../cosmos/rx/StoredProcedureCrudTest.java | 6 +- .../cosmos/rx/StoredProcedureQueryTest.java | 45 +- .../rx/StoredProcedureUpsertReplaceTest.java | 47 +- .../azure/data/cosmos/rx/TestSuiteBase.java | 12 +- .../azure/data/cosmos/rx/TriggerCrudTest.java | 6 +- .../data/cosmos/rx/TriggerQueryTest.java | 10 +- .../cosmos/rx/TriggerUpsertReplaceTest.java | 6 +- .../rx/UserDefinedFunctionCrudTest.java | 6 +- .../rx/UserDefinedFunctionQueryTest.java | 10 +- .../UserDefinedFunctionUpsertReplaceTest.java | 6 +- 28 files changed, 1147 insertions(+), 912 deletions(-) delete mode 100644 commons/src/main/java/com/azure/data/cosmos/CosmosResource.java rename sdk/src/{test => main}/java/com/azure/data/cosmos/CosmosBridgeInternal.java (71%) create mode 100644 sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosResource.java b/commons/src/main/java/com/azure/data/cosmos/CosmosResource.java deleted file mode 100644 index a6870a1cc17dd..0000000000000 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosResource.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.azure.data.cosmos; - -import org.apache.commons.lang3.StringUtils; - -public abstract class CosmosResource { - - private String id; - - public CosmosResource(String id) { - this.id = id; - } - - public String id() { - return id; - } - - protected CosmosResource id(String id) { - this.id = id; - return this; - } - - protected abstract String URIPathSegment(); - protected abstract String parentLink(); - - String getLink() { - StringBuilder builder = new StringBuilder(); - builder.append(parentLink()); - builder.append("/"); - builder.append(URIPathSegment()); - builder.append("/"); - builder.append(id()); - return builder.toString(); - } - - protected static void validateResource(Resource resource) { - if (!StringUtils.isEmpty(resource.id())) { - if (resource.id().indexOf('/') != -1 || resource.id().indexOf('\\') != -1 || - resource.id().indexOf('?') != -1 || resource.id().indexOf('#') != -1) { - throw new IllegalArgumentException("Id contains illegal chars."); - } - - if (resource.id().endsWith(" ")) { - throw new IllegalArgumentException("Id ends with a space."); - } - } - } - -} diff --git a/commons/src/main/java/com/azure/data/cosmos/Resource.java b/commons/src/main/java/com/azure/data/cosmos/Resource.java index dd2f445afcbdb..2ae4fe9d600f2 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Resource.java +++ b/commons/src/main/java/com/azure/data/cosmos/Resource.java @@ -26,6 +26,7 @@ import com.azure.data.cosmos.internal.Constants; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.commons.lang3.StringUtils; import java.time.Instant; import java.time.OffsetDateTime; @@ -37,6 +38,19 @@ public class Resource extends JsonSerializable { private String altLink; + static void validateResource(Resource resource) { + if (!StringUtils.isEmpty(resource.id())) { + if (resource.id().indexOf('/') != -1 || resource.id().indexOf('\\') != -1 || + resource.id().indexOf('?') != -1 || resource.id().indexOf('#') != -1) { + throw new IllegalArgumentException("Id contains illegal chars."); + } + + if (resource.id().endsWith(" ")) { + throw new IllegalArgumentException("Id ends with a space."); + } + } + } + /** * Copy constructor. * diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosBridgeInternal.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java similarity index 71% rename from sdk/src/test/java/com/azure/data/cosmos/CosmosBridgeInternal.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java index 033c263328e99..dc1f84bbdd4fb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosBridgeInternal.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java @@ -2,11 +2,10 @@ import reactor.core.publisher.Mono; +/** + * DO NOT USE. For internal use only by the SDK. These methods might break at any time. No support will be provided. + */ public class CosmosBridgeInternal { - - public static String getLink(CosmosResource resource) { - return resource.getLink(); - } public static DocumentCollection toDocumentCollection(CosmosContainerProperties cosmosContainerProperties) { return new DocumentCollection(cosmosContainerProperties.toJson()); @@ -27,4 +26,12 @@ public static CosmosContainer getCosmosContainerWithNewClient(CosmosContainer co public static Mono getDatabaseAccount(CosmosClient client) { return client.getDatabaseAccount(); } + + public static AsyncDocumentClient getContextClient(CosmosDatabase database) { + return database.getClient().getContextClient(); + } + + public static AsyncDocumentClient getContextClient(CosmosContainer container) { + return container.getDatabase().getClient().getContextClient(); + } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java index 03499f248ee43..c3cee03b24cf0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java @@ -26,72 +26,101 @@ import static com.azure.data.cosmos.internal.Paths.CONFLICTS_PATH_SEGMENT; -public class CosmosConflict extends CosmosResource { +/** + * Read and delete conflicts + */ +public class CosmosConflict { private CosmosContainer container; + private String id; /** * Constructor - * @param id the conflict id + * + * @param id the conflict id * @param container the container */ CosmosConflict(String id, CosmosContainer container) { - super(id); + this.id = id; this.container = container; } + /** + * Get the id of the {@link CosmosConflict} + * + * @return the id of the {@link CosmosConflict} + */ + public String id() { + return id; + } + + /** + * Set the id of the {@link CosmosConflict} + * + * @param id the id of the {@link CosmosConflict} + * @return the same {@link CosmosConflict} that had the id set + */ + CosmosConflict id(String id) { + this.id = id; + return this; + } + /** * Reads a conflict. *

- * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the read conflict. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single resource response with the read + * conflict. In case of failure the {@link Mono} will error. * - * @param options the request options. - * @return a {@link Mono} containing the single resource response with the read conflict or an error. + * @param options the request options. + * @return a {@link Mono} containing the single resource response with the read + * conflict or an error. */ - public Mono read(CosmosConflictRequestOptions options){ - if(options == null){ + public Mono read(CosmosConflictRequestOptions options) { + if (options == null) { options = new CosmosConflictRequestOptions(); } RequestOptions requestOptions = options.toRequestOptions(); - return this.container.getDatabase() - .getDocClientWrapper() - .readConflict(getLink(), requestOptions) - .map(response -> new CosmosConflictResponse(response, container)) - .single(); + return this.container.getDatabase().getDocClientWrapper().readConflict(getLink(), requestOptions) + .map(response -> new CosmosConflictResponse(response, container)).single(); } /** * Reads all conflicts in a document collection. *

- * After subscription the operation will be performed. - * The {@link Mono} will contain one or several feed response pages of the read conflicts. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} will + * contain one or several feed response pages of the read conflicts. In case of + * failure the {@link Mono} will error. * - * @param options the feed options. - * @return an {@link Mono} containing one or several feed response pages of the read conflicts or an error. + * @param options the feed options. + * @return an {@link Mono} containing one or several feed response pages of the + * read conflicts or an error. */ - public Mono delete(CosmosConflictRequestOptions options){ - if(options == null){ + public Mono delete(CosmosConflictRequestOptions options) { + if (options == null) { options = new CosmosConflictRequestOptions(); } RequestOptions requestOptions = options.toRequestOptions(); - return this.container.getDatabase() - .getDocClientWrapper() - .deleteConflict(getLink(), requestOptions) - .map(response -> new CosmosConflictResponse(response, container)) - .single(); + return this.container.getDatabase().getDocClientWrapper().deleteConflict(getLink(), requestOptions) + .map(response -> new CosmosConflictResponse(response, container)).single(); } - @Override - protected String URIPathSegment() { + String URIPathSegment() { return CONFLICTS_PATH_SEGMENT; } - @Override - protected String parentLink() { + String parentLink() { return this.container.getLink(); } + + String getLink() { + StringBuilder builder = new StringBuilder(); + builder.append(parentLink()); + builder.append("/"); + builder.append(URIPathSegment()); + builder.append("/"); + builder.append(id()); + return builder.toString(); + } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index b9b585873e339..ff95bb54c206c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -27,17 +27,41 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -public class CosmosContainer extends CosmosResource { +import static com.azure.data.cosmos.Resource.validateResource; + +public class CosmosContainer { private CosmosDatabase database; + private String id; + private CosmosScripts scripts; CosmosContainer(String id, CosmosDatabase database) { - super(id); + this.id = id; this.database = database; } + /** + * Get the id of the {@link CosmosContainer} + * + * @return the id of the {@link CosmosContainer} + */ + public String id() { + return id; + } + + /** + * Set the id of the {@link CosmosContainer} + * + * @param id the id of the {@link CosmosContainer} + * @return the same {@link CosmosContainer} that had the id set + */ + CosmosContainer id(String id) { + this.id = id; + return this; + } + AsyncDocumentClient getContextClient() { - if(this.database == null || this.database.getClient() == null) { + if (this.database == null || this.database.getClient() == null) { return null; } @@ -50,8 +74,8 @@ AsyncDocumentClient getContextClient() { * @param cosmosContainer the container client. * @return the context client. */ - public static AsyncDocumentClient getContextClient(CosmosContainer cosmosContainer) { - if(cosmosContainer == null) { + static AsyncDocumentClient getContextClient(CosmosContainer cosmosContainer) { + if (cosmosContainer == null) { return null; } @@ -65,7 +89,7 @@ public static AsyncDocumentClient getContextClient(CosmosContainer cosmosContain * @return the self link. */ public static String getSelfLink(CosmosContainer cosmosContainer) { - if(cosmosContainer == null) { + if (cosmosContainer == null) { return null; } @@ -75,12 +99,12 @@ public static String getSelfLink(CosmosContainer cosmosContainer) { /** * Reads the document container * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos container response with the read - * container. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single cosmos container response with + * the read container. In case of failure the {@link Mono} will error. * - * @return an {@link Mono} containing the single cosmos container response with the read container or an error. + * @return an {@link Mono} containing the single cosmos container response with + * the read container or an error. */ public Mono read() { return read(new CosmosContainerRequestOptions()); @@ -89,12 +113,13 @@ public Mono read() { /** * Reads the document container by the container link. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos container response with the read container. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single cosmos container response with + * the read container. In case of failure the {@link Mono} will error. * - * @param options The cosmos container request options. - * @return an {@link Mono} containing the single cosmos container response with the read container or an error. + * @param options The cosmos container request options. + * @return an {@link Mono} containing the single cosmos container response with + * the read container or an error. */ public Mono read(CosmosContainerRequestOptions options) { if (options == null) { @@ -107,31 +132,31 @@ public Mono read(CosmosContainerRequestOptions options) /** * Deletes the item container * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos container response for the deleted database. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single cosmos container response for the + * deleted database. In case of failure the {@link Mono} will error. * - * @param options the request options. - * @return an {@link Mono} containing the single cosmos container response for the deleted database or an error. + * @param options the request options. + * @return an {@link Mono} containing the single cosmos container response for + * the deleted database or an error. */ public Mono delete(CosmosContainerRequestOptions options) { if (options == null) { options = new CosmosContainerRequestOptions(); } - return database.getDocClientWrapper() - .deleteCollection(getLink(), options.toRequestOptions()) - .map(response -> new CosmosContainerResponse(response, database)) - .single(); + return database.getDocClientWrapper().deleteCollection(getLink(), options.toRequestOptions()) + .map(response -> new CosmosContainerResponse(response, database)).single(); } /** * Deletes the item container * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos container response for the deleted container. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single cosmos container response for the + * deleted container. In case of failure the {@link Mono} will error. * - * @return an {@link Mono} containing the single cosmos container response for the deleted container or an error. + * @return an {@link Mono} containing the single cosmos container response for + * the deleted container or an error. */ public Mono delete() { return delete(new CosmosContainerRequestOptions()); @@ -140,24 +165,25 @@ public Mono delete() { /** * Replaces a document container. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos container response with the replaced document container. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single cosmos container response with + * the replaced document container. In case of failure the {@link Mono} will + * error. * * @param containerSettings the item container settings - * @param options the cosmos container request options. - * @return an {@link Mono} containing the single cosmos container response with the replaced document container or an error. + * @param options the cosmos container request options. + * @return an {@link Mono} containing the single cosmos container response with + * the replaced document container or an error. */ public Mono replace(CosmosContainerProperties containerSettings, - CosmosContainerRequestOptions options) { + CosmosContainerRequestOptions options) { validateResource(containerSettings); - if(options == null){ + if (options == null) { options = new CosmosContainerRequestOptions(); } return database.getDocClientWrapper() - .replaceCollection(containerSettings.getV2Collection(),options.toRequestOptions()) - .map(response -> new CosmosContainerResponse(response, database)) - .single(); + .replaceCollection(containerSettings.getV2Collection(), options.toRequestOptions()) + .map(response -> new CosmosContainerResponse(response, database)).single(); } /* CosmosItem operations */ @@ -165,42 +191,46 @@ public Mono replace(CosmosContainerProperties container /** * Creates a cosmos item. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the created cosmos item. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single resource response with the + * created cosmos item. In case of failure the {@link Mono} will error. * * @param item the cosmos item represented as a POJO or cosmos item object. - * @return an {@link Mono} containing the single resource response with the created cosmos item or an error. + * @return an {@link Mono} containing the single resource response with the + * created cosmos item or an error. */ - public Mono createItem(Object item){ + public Mono createItem(Object item) { return createItem(item, new CosmosItemRequestOptions()); } /** * Creates a cosmos item. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the created cosmos item. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single resource response with the + * created cosmos item. In case of failure the {@link Mono} will error. * - * @param item the cosmos item represented as a POJO or cosmos item object. + * @param item the cosmos item represented as a POJO or cosmos item + * object. * @param partitionKey the partition key - * @return an {@link Mono} containing the single resource response with the created cosmos item or an error. + * @return an {@link Mono} containing the single resource response with the + * created cosmos item or an error. */ - public Mono createItem(Object item, Object partitionKey){ + public Mono createItem(Object item, Object partitionKey) { return createItem(item, new CosmosItemRequestOptions(partitionKey)); } /** * Creates a cosmos item. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the created cosmos item. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single resource response with the + * created cosmos item. In case of failure the {@link Mono} will error. * - * @param item the cosmos item represented as a POJO or cosmos item object. - * @param options the request options. - * @return an {@link Mono} containing the single resource response with the created cosmos item or an error. + * @param item the cosmos item represented as a POJO or cosmos item object. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the + * created cosmos item or an error. */ public Mono createItem(Object item, CosmosItemRequestOptions options) { if (options == null) { @@ -208,25 +238,20 @@ public Mono createItem(Object item, CosmosItemRequestOptions } RequestOptions requestOptions = options.toRequestOptions(); return database.getDocClientWrapper() - .createDocument(getLink(), - CosmosItemProperties.fromObject(item), - requestOptions, - true) - .map(response -> new CosmosItemResponse(response, - requestOptions.getPartitionKey(), - this)) - .single(); + .createDocument(getLink(), CosmosItemProperties.fromObject(item), requestOptions, true) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), this)).single(); } /** * Upserts an item. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the upserted item. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single resource response with the + * upserted item. In case of failure the {@link Mono} will error. * - * @param item the item represented as a POJO or Item object to upsert. - * @return an {@link Mono} containing the single resource response with the upserted document or an error. + * @param item the item represented as a POJO or Item object to upsert. + * @return an {@link Mono} containing the single resource response with the + * upserted document or an error. */ public Mono upsertItem(Object item) { return upsertItem(item, new CosmosItemRequestOptions()); @@ -235,13 +260,14 @@ public Mono upsertItem(Object item) { /** * Upserts an item. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the upserted item. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single resource response with the + * upserted item. In case of failure the {@link Mono} will error. * - * @param item the item represented as a POJO or Item object to upsert. - * @param partitionKey the partitionKey to be used. - * @return an {@link Mono} containing the single resource response with the upserted document or an error. + * @param item the item represented as a POJO or Item object to upsert. + * @param partitionKey the partitionKey to be used. + * @return an {@link Mono} containing the single resource response with the + * upserted document or an error. */ public Mono upsertItem(Object item, Object partitionKey) { return upsertItem(item, new CosmosItemRequestOptions(partitionKey)); @@ -250,40 +276,35 @@ public Mono upsertItem(Object item, Object partitionKey) { /** * Upserts a cosmos item. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the upserted item. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single resource response with the + * upserted item. In case of failure the {@link Mono} will error. * - * @param item the item represented as a POJO or Item object to upsert. - * @param options the request options. - * @return an {@link Mono} containing the single resource response with the upserted document or an error. + * @param item the item represented as a POJO or Item object to upsert. + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the + * upserted document or an error. */ - public Mono upsertItem(Object item, CosmosItemRequestOptions options){ + public Mono upsertItem(Object item, CosmosItemRequestOptions options) { if (options == null) { options = new CosmosItemRequestOptions(); } RequestOptions requestOptions = options.toRequestOptions(); - - return this.getDatabase() - .getDocClientWrapper() - .upsertDocument(this.getLink(), - CosmosItemProperties.fromObject(item), - options.toRequestOptions(), - true) - .map(response -> new CosmosItemResponse(response, - requestOptions.getPartitionKey(), - this)) - .single(); + + return this.getDatabase().getDocClientWrapper() + .upsertDocument(this.getLink(), CosmosItemProperties.fromObject(item), options.toRequestOptions(), true) + .map(response -> new CosmosItemResponse(response, requestOptions.getPartitionKey(), this)).single(); } /** * Reads all cosmos items in the container. * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the read cosmos items. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the read cosmos items. In case of + * failure the {@link Flux} will error. * - * @return an {@link Flux} containing one or several feed response pages of the read cosmos items or an error. + * @return an {@link Flux} containing one or several feed response pages of the + * read cosmos items or an error. */ public Flux> listItems() { return listItems(new FeedOptions()); @@ -292,73 +313,70 @@ public Flux> listItems() { /** * Reads all cosmos items in a container. * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the read cosmos items. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the read cosmos items. In case of + * failure the {@link Flux} will error. * - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the read cosmos items or an error. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the + * read cosmos items or an error. */ public Flux> listItems(FeedOptions options) { - return getDatabase().getDocClientWrapper() - .readDocuments(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosItemProperties.getFromV2Results(response.results()), - response.responseHeaders())); + return getDatabase().getDocClientWrapper().readDocuments(getLink(), options).map( + response -> BridgeInternal.createFeedResponse(CosmosItemProperties.getFromV2Results(response.results()), + response.responseHeaders())); } /** * Query for documents in a items in a container * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the obtained items. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained items. In case of + * failure the {@link Flux} will error. * - * @param query the query. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. + * @param query the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the + * obtained items or an error. */ - public Flux> queryItems(String query, FeedOptions options){ + public Flux> queryItems(String query, FeedOptions options) { return queryItems(new SqlQuerySpec(query), options); } /** * Query for documents in a items in a container * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the obtained items. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained items. In case of + * failure the {@link Flux} will error. * - * @param querySpec the SQL query specification. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the + * obtained items or an error. */ - public Flux> queryItems(SqlQuerySpec querySpec, FeedOptions options){ - return getDatabase() - .getDocClientWrapper() - .queryDocuments(getLink(), querySpec, options) - .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( - CosmosItemProperties.getFromV2Results(response.results()), - response.responseHeaders(), - response.queryMetrics())); + public Flux> queryItems(SqlQuerySpec querySpec, FeedOptions options) { + return getDatabase().getDocClientWrapper().queryDocuments(getLink(), querySpec, options) + .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( + CosmosItemProperties.getFromV2Results(response.results()), response.responseHeaders(), + response.queryMetrics())); } /** * Query for documents in a items in a container * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the obtained items. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained items. In case of + * failure the {@link Flux} will error. * - * @param changeFeedOptions the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained items or an error. + * @param changeFeedOptions the feed options. + * @return an {@link Flux} containing one or several feed response pages of the + * obtained items or an error. */ - public Flux> queryChangeFeedItems(ChangeFeedOptions changeFeedOptions){ - return getDatabase() - .getDocClientWrapper() - .queryDocumentChangeFeed(getLink(), changeFeedOptions) - .map(response-> new FeedResponse( - CosmosItemProperties.getFromV2Results(response.results()), - response.responseHeaders(), false)); + public Flux> queryChangeFeedItems(ChangeFeedOptions changeFeedOptions) { + return getDatabase().getDocClientWrapper().queryDocumentChangeFeed(getLink(), changeFeedOptions) + .map(response -> new FeedResponse( + CosmosItemProperties.getFromV2Results(response.results()), response.responseHeaders(), false)); } /** @@ -368,300 +386,28 @@ public Flux> queryChangeFeedItems(ChangeFeedO * @param partitionKey the partition key * @return a cosmos item */ - public CosmosItem getItem(String id, Object partitionKey){ + public CosmosItem getItem(String id, Object partitionKey) { return new CosmosItem(id, partitionKey, this); } - /* CosmosStoredProcedure operations */ - - /** - * Creates a cosmos stored procedure. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos stored procedure response with the - * created cosmos stored procedure. - * In case of failure the {@link Mono} will error. - * - * @param settings the cosmos stored procedure settings. - * @return an {@link Mono} containing the single cosmos stored procedure resource response or an error. - */ - public Mono createStoredProcedure(CosmosStoredProcedureProperties settings){ - return this.createStoredProcedure(settings, new CosmosStoredProcedureRequestOptions()); - } - - /** - * Creates a cosmos stored procedure. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos stored procedure response with the - * created cosmos stored procedure. - * In case of failure the {@link Mono} will error. - * - * @param settings the cosmos stored procedure settings. - * @param options the stored procedure request options. - * @return an {@link Mono} containing the single cosmos stored procedure resource response or an error. - */ - public Mono createStoredProcedure(CosmosStoredProcedureProperties settings, - CosmosStoredProcedureRequestOptions options){ - if(options == null){ - options = new CosmosStoredProcedureRequestOptions(); - } - StoredProcedure sProc = new StoredProcedure(); - sProc.id(settings.id()); - sProc.setBody(settings.body()); - return database.getDocClientWrapper() - .createStoredProcedure(getLink(), sProc, options.toRequestOptions()) - .map(response -> new CosmosStoredProcedureResponse(response, this)) - .single(); - } - - /** - * Reads all cosmos stored procedures in a container. - * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the read cosmos stored procedure settings. - * In case of failure the {@link Flux} will error. - * - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the read cosmos stored procedures - * settings or an error. - */ - public Flux> listStoredProcedures(FeedOptions options){ - return database.getDocClientWrapper() - .readStoredProcedures(getLink(), options) - .map(response -> BridgeInternal.createFeedResponse(CosmosStoredProcedureProperties.getFromV2Results(response.results()), - response.responseHeaders())); - } - - /** - * Query for stored procedures in a container. - * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the obtained stored procedures. - * In case of failure the {@link Flux} will error. - * - * @param query the the query. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained stored procedures or - * an error. - */ - public Flux> queryStoredProcedures(String query, - FeedOptions options){ - return queryStoredProcedures(new SqlQuerySpec(query), options); - } - - /** - * Query for stored procedures in a container. - * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the obtained stored procedures. - * In case of failure the {@link Flux} will error. - * - * @param querySpec the SQL query specification. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained stored procedures or - * an error. - */ - public Flux> queryStoredProcedures(SqlQuerySpec querySpec, - FeedOptions options){ - return database.getDocClientWrapper() - .queryStoredProcedures(getLink(), querySpec,options) - .map(response -> BridgeInternal.createFeedResponse( CosmosStoredProcedureProperties.getFromV2Results(response.results()), - response.responseHeaders())); - } - - /** - * Gets a CosmosStoredProcedure object without making a service call - * @param id id of the stored procedure - * @return a cosmos stored procedure - */ - public CosmosStoredProcedure getStoredProcedure(String id){ - return new CosmosStoredProcedure(id, this); - } - - - /* UDF Operations */ - - /** - * Creates a cosmos user defined function. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos user defined function response. - * In case of failure the {@link Mono} will error. - * - * @param settings the cosmos user defined function settings - * @param options the cosmos request options. - * @return an {@link Mono} containing the single resource response with the created user defined function or an error. - */ - public Mono createUserDefinedFunction(CosmosUserDefinedFunctionProperties settings, - CosmosRequestOptions options){ - UserDefinedFunction udf = new UserDefinedFunction(); - udf.id(settings.id()); - udf.setBody(settings.body()); - if(options == null){ - options = new CosmosRequestOptions(); - } - return database.getDocClientWrapper() - .createUserDefinedFunction(getLink(), udf, options.toRequestOptions()) - .map(response -> new CosmosUserDefinedFunctionResponse(response, this)).single(); - } - - /** - * Reads all cosmos user defined functions in the container - * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the read user defined functions. - * In case of failure the {@link Flux} will error. - * - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the read user defined functions or an error. - */ - public Flux> listUserDefinedFunctions(FeedOptions options){ - return database.getDocClientWrapper() - .readUserDefinedFunctions(getLink(), options) - .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionProperties.getFromV2Results(response.results()), - response.responseHeaders())); - } - - /** - * Query for user defined functions in the container. - * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the obtained user defined functions. - * In case of failure the {@link Flux} will error. - * - * @param query the query. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained user defined functions or an error. - */ - public Flux> queryUserDefinedFunctions(String query, - FeedOptions options){ - return queryUserDefinedFunctions(new SqlQuerySpec(query), options); - } - - /** - * Query for user defined functions in the container. - * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the obtained user defined functions. - * In case of failure the {@link Flux} will error. - * - * @param querySpec the SQL query specification. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained user defined functions or an error. - */ - public Flux> queryUserDefinedFunctions(SqlQuerySpec querySpec, - FeedOptions options){ - return database.getDocClientWrapper() - .queryUserDefinedFunctions(getLink(),querySpec, options) - .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionProperties.getFromV2Results(response.results()), - response.responseHeaders())); - } - - /** - * Gets a CosmosUserDefinedFunction object without making a service call - * @param id id of the user defined function - * @return a cosmos user defined function - */ - public CosmosUserDefinedFunction getUserDefinedFunction(String id){ - return new CosmosUserDefinedFunction(id, this); - } - - /* Trigger Operations */ - /** - * Creates a Cosmos trigger. - * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos trigger response - * In case of failure the {@link Mono} will error. - * - * @param settings the cosmos trigger settings - * @param options the request options. - * @return an {@link Mono} containing the single resource response with the created trigger or an error. - */ - public Mono createTrigger(CosmosTriggerProperties settings, - CosmosRequestOptions options){ - Trigger trigger = new Trigger(settings.toJson()); - if(options == null){ - options = new CosmosRequestOptions(); + public CosmosScripts getScripts() { + if (this.scripts == null) { + this.scripts = new CosmosScripts(this); } - return database.getDocClientWrapper() - .createTrigger(getLink(), trigger,options.toRequestOptions()) - .map(response -> new CosmosTriggerResponse(response, this)) - .single(); - } - - /** - * Reads all triggers in a container - * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the read cosmos trigger settings. - * In case of failure the {@link Flux} will error. - * - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the read cosmos rigger settings or an error. - */ - public Flux> listTriggers(FeedOptions options){ - return database.getDocClientWrapper() - .readTriggers(getLink(), options) - .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerProperties.getFromV2Results(response.results()), - response.responseHeaders())); - } - - /** - * Query for triggers in the container - * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the obtained triggers. - * In case of failure the {@link Flux} will error. - * - * @param query the query. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained triggers or an error. - */ - public Flux> queryTriggers(String query, FeedOptions options){ - return queryTriggers(new SqlQuerySpec(query), options); - } - - /** - * Query for triggers in the container - * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the obtained triggers. - * In case of failure the {@link Flux} will error. - * - * @param querySpec the SQL query specification. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained triggers or an error. - */ - public Flux> queryTriggers(SqlQuerySpec querySpec, - FeedOptions options){ - return database.getDocClientWrapper() - .queryTriggers(getLink(), querySpec, options) - .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerProperties.getFromV2Results(response.results()), - response.responseHeaders())); - } - - /** - * Gets a CosmosTrigger object without making a service call - * @param id id of the cosmos trigger - * @return a cosmos trigger - */ - public CosmosTrigger getTrigger(String id){ - return new CosmosTrigger(id, this); + return this.scripts; } /** * Lists all the conflicts in the container * * @param options the feed options - * @return a {@link Flux} containing one or several feed response pages of the obtained conflicts or an error. + * @return a {@link Flux} containing one or several feed response pages of the + * obtained conflicts or an error. */ public Flux> listConflicts(FeedOptions options) { - return database.getDocClientWrapper() - .readConflicts(getLink(), options) - .map(response -> BridgeInternal.createFeedResponse(CosmosConflictProperties.getFromV2Results(response.results()), - response.responseHeaders())); + return database.getDocClientWrapper().readConflicts(getLink(), options) + .map(response -> BridgeInternal.createFeedResponse( + CosmosConflictProperties.getFromV2Results(response.results()), response.responseHeaders())); } /** @@ -669,21 +415,22 @@ public Flux> listConflicts(FeedOptions op * * @param query the query * @param options the feed options - * @return a {@link Flux} containing one or several feed response pages of the obtained conflicts or an error. + * @return a {@link Flux} containing one or several feed response pages of the + * obtained conflicts or an error. */ public Flux> queryConflicts(String query, FeedOptions options) { - return database.getDocClientWrapper() - .queryConflicts(getLink(), query, options) - .map(response -> BridgeInternal.createFeedResponse(CosmosConflictProperties.getFromV2Results(response.results()), - response.responseHeaders())); + return database.getDocClientWrapper().queryConflicts(getLink(), query, options) + .map(response -> BridgeInternal.createFeedResponse( + CosmosConflictProperties.getFromV2Results(response.results()), response.responseHeaders())); } /** * Gets a CosmosConflict object without making a service call + * * @param id id of the cosmos conflict * @return a cosmos conflict */ - public CosmosTrigger getConflict(String id){ + public CosmosTrigger getConflict(String id) { return new CosmosTrigger(id, this); } @@ -692,51 +439,41 @@ public CosmosTrigger getConflict(String id){ * * @return a {@link Mono} containing throughput or an error. */ - public Mono readProvisionedThroughput(){ - return this.read() - .flatMap(cosmosContainerResponse -> - database.getDocClientWrapper() - .queryOffers("select * from c where c.offerResourceId = '" + - cosmosContainerResponse.resourceSettings().resourceId() - + "'", new FeedOptions()).single()) - .flatMap(offerFeedResponse -> { - if(offerFeedResponse.results().isEmpty()){ - return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, - "No offers found for the resource")); - } - return database.getDocClientWrapper() - .readOffer(offerFeedResponse.results() - .get(0) - .selfLink()).single(); - }) - .map(cosmosOfferResponse -> cosmosOfferResponse - .getResource() - .getThroughput()); + public Mono readProvisionedThroughput() { + return this.read().flatMap(cosmosContainerResponse -> database.getDocClientWrapper() + .queryOffers("select * from c where c.offerResourceId = '" + + cosmosContainerResponse.resourceSettings().resourceId() + "'", new FeedOptions()) + .single()).flatMap(offerFeedResponse -> { + if (offerFeedResponse.results().isEmpty()) { + return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + "No offers found for the resource")); + } + return database.getDocClientWrapper().readOffer(offerFeedResponse.results().get(0).selfLink()) + .single(); + }).map(cosmosOfferResponse -> cosmosOfferResponse.getResource().getThroughput()); } /** - * Sets throughput provisioned for a container in measurement of Requests-per-Unit in the Azure Cosmos service. + * Sets throughput provisioned for a container in measurement of + * Requests-per-Unit in the Azure Cosmos service. * - * @param requestUnitsPerSecond the cosmos container throughput, expressed in Request Units per second + * @param requestUnitsPerSecond the cosmos container throughput, expressed in + * Request Units per second * @return a {@link Mono} containing throughput or an error. */ - public Mono replaceProvisionedThroughputAsync(int requestUnitsPerSecond){ - return this.read() - .flatMap(cosmosContainerResponse -> - database.getDocClientWrapper() - .queryOffers("select * from c where c.offerResourceId = '" + - cosmosContainerResponse.resourceSettings().resourceId() - + "'", new FeedOptions()).single()) - .flatMap(offerFeedResponse -> { - if(offerFeedResponse.results().isEmpty()){ - return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, - "No offers found for the resource")); - } - Offer offer = offerFeedResponse.results().get(0); - offer.setThroughput(requestUnitsPerSecond); - return database.getDocClientWrapper() - .replaceOffer(offer).single(); - }).map(offerResourceResponse -> offerResourceResponse.getResource().getThroughput()); + public Mono replaceProvisionedThroughput(int requestUnitsPerSecond) { + return this.read().flatMap(cosmosContainerResponse -> database.getDocClientWrapper() + .queryOffers("select * from c where c.offerResourceId = '" + + cosmosContainerResponse.resourceSettings().resourceId() + "'", new FeedOptions()) + .single()).flatMap(offerFeedResponse -> { + if (offerFeedResponse.results().isEmpty()) { + return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + "No offers found for the resource")); + } + Offer offer = offerFeedResponse.results().get(0); + offer.setThroughput(requestUnitsPerSecond); + return database.getDocClientWrapper().replaceOffer(offer).single(); + }).map(offerResourceResponse -> offerResourceResponse.getResource().getThroughput()); } /** @@ -748,14 +485,22 @@ public CosmosDatabase getDatabase() { return database; } - @Override - protected String URIPathSegment() { + String URIPathSegment() { return Paths.COLLECTIONS_PATH_SEGMENT; } - @Override - protected String parentLink() { + String parentLink() { return database.getLink(); } + String getLink() { + StringBuilder builder = new StringBuilder(); + builder.append(parentLink()); + builder.append("/"); + builder.append(URIPathSegment()); + builder.append("/"); + builder.append(id()); + return builder.toString(); + } + } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java index ff2385ffc5e5f..f561d4dbb06c3 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java @@ -28,53 +28,76 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import static com.azure.data.cosmos.Resource.validateResource; + /** - * Cosmos Database + * Perform read and delete databases, update database throughput, and perform operations on child resources */ -public class CosmosDatabase extends CosmosResource { +public class CosmosDatabase { private CosmosClient client; + private String id; CosmosDatabase(String id, CosmosClient client) { - super(id); + this.id = id; this.client = client; } + /** + * Get the id of the CosmosDatabase + * + * @return the id of the CosmosDatabase + */ + public String id() { + return id; + } + + /** + * Set the id of the CosmosDatabase + * + * @param id the id of the CosmosDatabase + * @return the same CosmosConflict that had the id set + */ + CosmosDatabase id(String id) { + this.id = id; + return this; + } + /** * Reads a database. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single cosmos database respone with the read database. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single cosmos database respone with the + * read database. In case of failure the {@link Mono} will error. * - * @return an {@link Mono} containing the single cosmos database respone with the read database or an error. + * @return an {@link Mono} containing the single cosmos database respone with + * the read database or an error. */ - public Mono read(){ + public Mono read() { return read(new CosmosDatabaseRequestOptions()); } /** * Reads a database. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos cosmos database respone with the read database. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos cosmos database respone with the + * read database. In case of failure the {@link Mono} will error. * - * @param options the request options. - * @return an {@link Mono} containing the single cosmos database response with the read database or an error. + * @param options the request options. + * @return an {@link Mono} containing the single cosmos database response with + * the read database or an error. */ public Mono read(CosmosDatabaseRequestOptions options) { - return getDocClientWrapper().readDatabase(getLink(), - options.toRequestOptions()) - .map(response -> new CosmosDatabaseResponse(response, getClient())) - .single(); + return getDocClientWrapper().readDatabase(getLink(), options.toRequestOptions()) + .map(response -> new CosmosDatabaseResponse(response, getClient())).single(); } /** * Deletes a database. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos database response with the deleted database. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos database response with the + * deleted database. In case of failure the {@link Mono} will error. * * @return an {@link Mono} containing the single cosmos database response */ @@ -85,18 +108,16 @@ public Mono delete() { /** * Deletes a database. *

- * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos database response with the deleted database. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos database response with the + * deleted database. In case of failure the {@link Mono} will error. * * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ public Mono delete(CosmosRequestOptions options) { - return getDocClientWrapper() - .deleteDatabase(getLink(), options.toRequestOptions()) - .map(response -> new CosmosDatabaseResponse(response, getClient())) - .single(); + return getDocClientWrapper().deleteDatabase(getLink(), options.toRequestOptions()) + .map(response -> new CosmosDatabaseResponse(response, getClient())).single(); } /* CosmosContainer operations */ @@ -104,13 +125,13 @@ public Mono delete(CosmosRequestOptions options) { /** * Creates a document container. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos container response with the created - * collection. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos container response with the + * created collection. In case of failure the {@link Mono} will error. * - * @param containerSettings the container settings. - * @return an {@link Flux} containing the single cosmos container response with the created container or an error. + * @param containerSettings the container settings. + * @return an {@link Flux} containing the single cosmos container response with + * the created container or an error. */ public Mono createContainer(CosmosContainerProperties containerSettings) { validateResource(containerSettings); @@ -120,34 +141,33 @@ public Mono createContainer(CosmosContainerProperties c /** * Creates a document container. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos container response with the created - * collection. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos container response with the + * created collection. In case of failure the {@link Mono} will error. * - * @param containerSettings the containerSettings. - * @param options the cosmos container request options - * @return an {@link Flux} containing the cosmos container response with the created container or an error. + * @param containerSettings the containerSettings. + * @param options the cosmos container request options + * @return an {@link Flux} containing the cosmos container response with the + * created container or an error. */ public Mono createContainer(CosmosContainerProperties containerSettings, - CosmosContainerRequestOptions options) { - return getDocClientWrapper().createCollection(this.getLink(), - containerSettings.getV2Collection(), options.toRequestOptions()).map(response -> - new CosmosContainerResponse(response, this)) - .single(); + CosmosContainerRequestOptions options) { + return getDocClientWrapper() + .createCollection(this.getLink(), containerSettings.getV2Collection(), options.toRequestOptions()) + .map(response -> new CosmosContainerResponse(response, this)).single(); } /** * Creates a document container. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos container response with the created - * collection. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos container response with the + * created collection. In case of failure the {@link Mono} will error. * - * @param id the cosmos container id + * @param id the cosmos container id * @param partitionKeyPath the partition key path - * @return an {@link Flux} containing the cosmos container response with the created container or an error. + * @return an {@link Flux} containing the cosmos container response with the + * created container or an error. */ public Mono createContainer(String id, String partitionKeyPath) { return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); @@ -156,14 +176,14 @@ public Mono createContainer(String id, String partition /** * Creates a document container if it does not exist on the service. *

- * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos container response with the created - * or existing collection. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos container response with the + * created or existing collection. In case of failure the {@link Mono} will + * error. * * @param containerSettings the container settings - * @return a {@link Mono} containing the cosmos container response with the created or existing container or - * an error. + * @return a {@link Mono} containing the cosmos container response with the + * created or existing container or an error. */ public Mono createContainerIfNotExists(CosmosContainerProperties containerSettings) { CosmosContainer container = getContainer(containerSettings.id()); @@ -173,22 +193,22 @@ public Mono createContainerIfNotExists(CosmosContainerP /** * Creates a document container if it does not exist on the service. * - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a cosmos container response with the created - * collection. - * In case of failure the {@link Mono} will error. + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos container response with the + * created collection. In case of failure the {@link Mono} will error. * - * @param id the cosmos container id + * @param id the cosmos container id * @param partitionKeyPath the partition key path - * @return an {@link Flux} containing the cosmos container response with the created container or an error. + * @return an {@link Flux} containing the cosmos container response with the + * created container or an error. */ public Mono createContainerIfNotExists(String id, String partitionKeyPath) { CosmosContainer container = getContainer(id); return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container); } - - private Mono createContainerIfNotExistsInternal(CosmosContainerProperties containerSettings, CosmosContainer container) { + private Mono createContainerIfNotExistsInternal( + CosmosContainerProperties containerSettings, CosmosContainer container) { return container.read().onErrorResume(exception -> { if (exception instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) exception; @@ -200,31 +220,32 @@ private Mono createContainerIfNotExistsInternal(CosmosC }); } - /** * Reads all cosmos containers. * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the read containers. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the read containers. In case of + * failure the {@link Flux} will error. * * @param options {@link FeedOptions} - * @return a {@link Flux} containing one or several feed response pages of read containers or an error. + * @return a {@link Flux} containing one or several feed response pages of read + * containers or an error. */ public Flux> listContainers(FeedOptions options) { return getDocClientWrapper().readCollections(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosContainerProperties.getFromV2Results(response.results()), - response.responseHeaders())); + .map(response -> BridgeInternal.createFeedResponse( + CosmosContainerProperties.getFromV2Results(response.results()), response.responseHeaders())); } /** * Reads all cosmos containers. * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the read containers. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the read containers. In case of + * failure the {@link Flux} will error. * - * @return a {@link Flux} containing one or several feed response pages of read containers or an error. + * @return a {@link Flux} containing one or several feed response pages of read + * containers or an error. */ public Flux> listContainers() { return listContainers(new FeedOptions()); @@ -233,39 +254,40 @@ public Flux> listContainers() { /** * Query for cosmos containers in a cosmos database. * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the obtained containers. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained containers. In case of + * failure the {@link Flux} will error. * - * @param query the query. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained containers or an error. + * @param query the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the + * obtained containers or an error. */ - public Flux> queryContainers(String query, FeedOptions options){ + public Flux> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } /** * Query for cosmos containers in a cosmos database. * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the obtained containers. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained containers. In case of + * failure the {@link Flux} will error. * - * @param querySpec the SQL query specification. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained containers or an error. + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the + * obtained containers or an error. */ - public Flux> queryContainers(SqlQuerySpec querySpec, FeedOptions options){ - return getDocClientWrapper().queryCollections(getLink(), querySpec, - options) - .map(response-> BridgeInternal.createFeedResponse( - CosmosContainerProperties.getFromV2Results(response.results()), - response.responseHeaders())); + public Flux> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { + return getDocClientWrapper().queryCollections(getLink(), querySpec, options) + .map(response -> BridgeInternal.createFeedResponse( + CosmosContainerProperties.getFromV2Results(response.results()), response.responseHeaders())); } /** * Gets a CosmosContainer object without making a service call + * * @param id id of the container * @return Cosmos Container */ @@ -275,10 +297,6 @@ public CosmosContainer getContainer(String id) { /** User operations **/ - public Mono createUser(CosmosUserProperties settings) { - return this.createUser(settings, null); - } - /** * Creates a user * After subscription the operation will be performed. @@ -286,33 +304,58 @@ public Mono createUser(CosmosUserProperties settings) { * In case of failure the {@link Mono} will error. * * @param settings the cosmos user settings - * @param options the request options * @return an {@link Mono} containing the single resource response with the created cosmos user or an error. */ - public Mono createUser(CosmosUserProperties settings, RequestOptions options){ - return getDocClientWrapper().createUser(this.getLink(), - settings.getV2User(), options).map(response -> - new CosmosUserResponse(response, this)).single(); + public Mono createUser(CosmosUserProperties settings) { + return this.createUser(settings, null); } + /** + * Creates a user After subscription the operation will be performed. The + * {@link Mono} upon successful completion will contain a single resource + * response with the created user. In case of failure the {@link Mono} will + * error. + * + * @param settings the cosmos user settings + * @param options the request options + * @return an {@link Mono} containing the single resource response with the + * created cosmos user or an error. + */ + public Mono createUser(CosmosUserProperties settings, RequestOptions options) { + return getDocClientWrapper().createUser(this.getLink(), settings.getV2User(), options) + .map(response -> new CosmosUserResponse(response, this)).single(); + } + + /** + * Upsert a user. Upsert will create a new user if it doesn't exist, or replace + * the existing one if it does. After subscription the operation will be + * performed. The {@link Mono} upon successful completion will contain a single + * resource response with the created user. In case of failure the {@link Mono} + * will error. + * + * @param settings the cosmos user settings + * @return an {@link Mono} containing the single resource response with the + * upserted user or an error. + */ public Mono upsertUser(CosmosUserProperties settings) { return this.upsertUser(settings, null); } /** - * Upsert a user - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the created user. - * In case of failure the {@link Mono} will error. + * Upsert a user. Upsert will create a new user if it doesn't exist, or replace + * the existing one if it does. After subscription the operation will be + * performed. The {@link Mono} upon successful completion will contain a single + * resource response with the created user. In case of failure the {@link Mono} + * will error. * * @param settings the cosmos user settings - * @param options the request options - * @return an {@link Mono} containing the single resource response with the upserted user or an error. + * @param options the request options + * @return an {@link Mono} containing the single resource response with the + * upserted user or an error. */ - public Mono upsertUser(CosmosUserProperties settings, RequestOptions options){ - return getDocClientWrapper().upsertUser(this.getLink(), - settings.getV2User(), options).map(response -> - new CosmosUserResponse(response, this)).single(); + public Mono upsertUser(CosmosUserProperties settings, RequestOptions options) { + return getDocClientWrapper().upsertUser(this.getLink(), settings.getV2User(), options) + .map(response -> new CosmosUserResponse(response, this)).single(); } public Flux> listUsers() { @@ -322,41 +365,40 @@ public Flux> listUsers() { /** * Reads all cosmos users in a database. * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the read cosmos users. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the read cosmos users. In case of + * failure the {@link Flux} will error. * - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the read cosmos users or an error. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the + * read cosmos users or an error. */ - public Flux> listUsers(FeedOptions options){ - return getDocClientWrapper() - .readUsers(getLink(), options) - .map(response-> BridgeInternal.createFeedResponse(CosmosUserProperties.getFromV2Results(response.results()), - response.responseHeaders())); + public Flux> listUsers(FeedOptions options) { + return getDocClientWrapper().readUsers(getLink(), options).map(response -> BridgeInternal.createFeedResponse( + CosmosUserProperties.getFromV2Results(response.results()), response.responseHeaders())); } - public Flux> queryUsers(String query, FeedOptions options){ + public Flux> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } /** * Query for cosmos users in a database. * - * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response of the obtained users. - * In case of failure the {@link Flux} will error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained users. In case of + * failure the {@link Flux} will error. * - * @param querySpec the SQL query specification. - * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the obtained users or an error. + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the + * obtained users or an error. */ - public Flux> queryUsers(SqlQuerySpec querySpec, FeedOptions options){ - return getDocClientWrapper() - .queryUsers(getLink(), querySpec, options) - .map(response-> BridgeInternal.createFeedResponseWithQueryMetrics( - CosmosUserProperties.getFromV2Results(response.results()), - response.responseHeaders(), response.queryMetrics())); + public Flux> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { + return getDocClientWrapper().queryUsers(getLink(), querySpec, options) + .map(response -> BridgeInternal.createFeedResponseWithQueryMetrics( + CosmosUserProperties.getFromV2Results(response.results()), response.responseHeaders(), + response.queryMetrics())); } public CosmosUser getUser(String id) { @@ -368,67 +410,65 @@ public CosmosUser getUser(String id) { * * @return a {@link Mono} containing throughput or an error. */ - public Mono readProvisionedThroughput(){ - return this.read() - .flatMap(cosmosDatabaseResponse -> - getDocClientWrapper().queryOffers("select * from c where c.offerResourceId = '" + - cosmosDatabaseResponse.resourceSettings().resourceId() - + "'", new FeedOptions()).single() - .flatMap(offerFeedResponse -> { - if(offerFeedResponse.results().isEmpty()){ - return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, - "No offers found for the resource")); - } - return getDocClientWrapper() - .readOffer(offerFeedResponse.results() - .get(0) - .selfLink()).single(); - }) - .map(cosmosContainerResponse1 -> cosmosContainerResponse1 - .getResource() - .getThroughput())); + public Mono readProvisionedThroughput() { + return this.read().flatMap(cosmosDatabaseResponse -> getDocClientWrapper() + .queryOffers("select * from c where c.offerResourceId = '" + + cosmosDatabaseResponse.resourceSettings().resourceId() + "'", new FeedOptions()) + .single().flatMap(offerFeedResponse -> { + if (offerFeedResponse.results().isEmpty()) { + return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + "No offers found for the resource")); + } + return getDocClientWrapper().readOffer(offerFeedResponse.results().get(0).selfLink()).single(); + }).map(cosmosContainerResponse1 -> cosmosContainerResponse1.getResource().getThroughput())); } /** - * Sets throughput provisioned for a container in measurement of Requests-per-Unit in the Azure Cosmos service. + * Sets throughput provisioned for a container in measurement of + * Requests-per-Unit in the Azure Cosmos service. * - * @param requestUnitsPerSecond the cosmos container throughput, expressed in Request Units per second + * @param requestUnitsPerSecond the cosmos container throughput, expressed in + * Request Units per second * @return a {@link Mono} containing throughput or an error. */ - public Mono replaceProvisionedThroughputAsync(int requestUnitsPerSecond){ - return this.read() - .flatMap(cosmosDatabaseResponse -> - this.getDocClientWrapper() - .queryOffers("select * from c where c.offerResourceId = '" + - cosmosDatabaseResponse.resourceSettings().resourceId() - + "'", new FeedOptions()).single() - .flatMap(offerFeedResponse -> { - if(offerFeedResponse.results().isEmpty()){ - return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, - "No offers found for the resource")); - } - Offer offer = offerFeedResponse.results().get(0); - offer.setThroughput(requestUnitsPerSecond); - return this.getDocClientWrapper() - .replaceOffer(offer).single(); - }).map(offerResourceResponse -> offerResourceResponse.getResource().getThroughput())); + public Mono replaceProvisionedThroughput(int requestUnitsPerSecond) { + return this.read().flatMap(cosmosDatabaseResponse -> this.getDocClientWrapper() + .queryOffers("select * from c where c.offerResourceId = '" + + cosmosDatabaseResponse.resourceSettings().resourceId() + "'", new FeedOptions()) + .single().flatMap(offerFeedResponse -> { + if (offerFeedResponse.results().isEmpty()) { + return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + "No offers found for the resource")); + } + Offer offer = offerFeedResponse.results().get(0); + offer.setThroughput(requestUnitsPerSecond); + return this.getDocClientWrapper().replaceOffer(offer).single(); + }).map(offerResourceResponse -> offerResourceResponse.getResource().getThroughput())); } CosmosClient getClient() { return client; } - AsyncDocumentClient getDocClientWrapper(){ + AsyncDocumentClient getDocClientWrapper() { return client.getDocClientWrapper(); } - @Override - protected String URIPathSegment() { + String URIPathSegment() { return Paths.DATABASES_PATH_SEGMENT; } - @Override - protected String parentLink() { + String parentLink() { return StringUtils.EMPTY; } + + String getLink() { + StringBuilder builder = new StringBuilder(); + builder.append(parentLink()); + builder.append("/"); + builder.append(URIPathSegment()); + builder.append("/"); + builder.append(id()); + return builder.toString(); + } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java index 38877be0371a0..ad29bb8fc5d5c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java @@ -25,16 +25,35 @@ import com.azure.data.cosmos.internal.Paths; import reactor.core.publisher.Mono; -public class CosmosItem extends CosmosResource{ +public class CosmosItem { private Object partitionKey; private CosmosContainer container; + private String id; - CosmosItem(String id, Object partitionKey, CosmosContainer container) { - super(id); + CosmosItem(String id, Object partitionKey, CosmosContainer container) { + this.id = id; this.partitionKey = partitionKey; this.container = container; } + /** + * Get the id of the {@link CosmosItem} + * @return the id of the {@link CosmosItem} + */ + public String id() { + return id; + } + + /** + * Set the id of the {@link CosmosItem} + * @param id the id of the {@link CosmosItem} + * @return the same {@link CosmosItem} that had the id set + */ + CosmosItem id(String id) { + this.id = id; + return this; + } + /** * Reads an item. * @@ -145,13 +164,21 @@ void setContainer(CosmosContainer container) { this.container = container; } - @Override - protected String URIPathSegment() { + String URIPathSegment() { return Paths.DOCUMENTS_PATH_SEGMENT; } - @Override - protected String parentLink() { + String parentLink() { return this.container.getLink(); } + + String getLink() { + StringBuilder builder = new StringBuilder(); + builder.append(parentLink()); + builder.append("/"); + builder.append(URIPathSegment()); + builder.append("/"); + builder.append(id()); + return builder.toString(); + } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java index 3c3f1aa64091c..2ee8bb553a29e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java @@ -25,15 +25,34 @@ import com.azure.data.cosmos.internal.Paths; import reactor.core.publisher.Mono; -public class CosmosPermission extends CosmosResource{ +public class CosmosPermission { private final CosmosUser cosmosUser; + private String id; CosmosPermission(String id, CosmosUser user){ - super(id); + this.id = id; this.cosmosUser = user; } + /** + * Get the id of the {@link CosmosPermission} + * @return the id of the {@link CosmosPermission} + */ + public String id() { + return id; + } + + /** + * Set the id of the {@link CosmosPermission} + * @param id the id of the {@link CosmosPermission} + * @return the same {@link CosmosPermission} that had the id set + */ + CosmosPermission id(String id) { + this.id = id; + return this; + } + /** * Reads a permission. *

@@ -94,13 +113,21 @@ public Mono delete(CosmosPermissionsRequestOptions opt .single(); } - @Override - protected String URIPathSegment() { + String URIPathSegment() { return Paths.PERMISSIONS_PATH_SEGMENT; } - @Override - protected String parentLink() { + String parentLink() { return cosmosUser.getLink(); } + + String getLink() { + StringBuilder builder = new StringBuilder(); + builder.append(parentLink()); + builder.append("/"); + builder.append(URIPathSegment()); + builder.append("/"); + builder.append(id()); + return builder.toString(); + } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java new file mode 100644 index 0000000000000..7a2f9927f42e4 --- /dev/null +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java @@ -0,0 +1,315 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +public class CosmosScripts { + private final CosmosContainer container; + private final CosmosDatabase database; + + CosmosScripts(CosmosContainer container) { + this.container = container; + this.database = container.getDatabase(); + } + /* CosmosStoredProcedure operations */ + + /** + * Creates a cosmos stored procedure. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos stored procedure response with the + * created cosmos stored procedure. + * In case of failure the {@link Mono} will error. + * + * @param properties the cosmos stored procedure properties. + * @return an {@link Mono} containing the single cosmos stored procedure resource response or an error. + */ + public Mono createStoredProcedure(CosmosStoredProcedureProperties properties){ + return this.createStoredProcedure(properties, new CosmosStoredProcedureRequestOptions()); + } + + /** + * Creates a cosmos stored procedure. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos stored procedure response with the + * created cosmos stored procedure. + * In case of failure the {@link Mono} will error. + * + * @param properties the cosmos stored procedure properties. + * @param options the stored procedure request options. + * @return an {@link Mono} containing the single cosmos stored procedure resource response or an error. + */ + public Mono createStoredProcedure(CosmosStoredProcedureProperties properties, + CosmosStoredProcedureRequestOptions options){ + if(options == null){ + options = new CosmosStoredProcedureRequestOptions(); + } + StoredProcedure sProc = new StoredProcedure(); + sProc.id(properties.id()); + sProc.setBody(properties.body()); + return database.getDocClientWrapper() + .createStoredProcedure(container.getLink(), sProc, options.toRequestOptions()) + .map(response -> new CosmosStoredProcedureResponse(response, this.container)) + .single(); + } + + /** + * Reads all cosmos stored procedures in a container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the read cosmos stored procedure settings. + * In case of failure the {@link Flux} will error. + * + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the read cosmos stored procedures + * settings or an error. + */ + public Flux> listStoredProcedures(FeedOptions options){ + return database.getDocClientWrapper() + .readStoredProcedures(container.getLink(), options) + .map(response -> BridgeInternal.createFeedResponse(CosmosStoredProcedureProperties.getFromV2Results(response.results()), + response.responseHeaders())); + } + + /** + * Query for stored procedures in a container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained stored procedures. + * In case of failure the {@link Flux} will error. + * + * @param query the the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained stored procedures or + * an error. + */ + public Flux> queryStoredProcedures(String query, + FeedOptions options){ + return queryStoredProcedures(new SqlQuerySpec(query), options); + } + + /** + * Query for stored procedures in a container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained stored procedures. + * In case of failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained stored procedures or + * an error. + */ + public Flux> queryStoredProcedures(SqlQuerySpec querySpec, + FeedOptions options){ + return database.getDocClientWrapper() + .queryStoredProcedures(container.getLink(), querySpec,options) + .map(response -> BridgeInternal.createFeedResponse( CosmosStoredProcedureProperties.getFromV2Results(response.results()), + response.responseHeaders())); + } + + /** + * Gets a CosmosStoredProcedure object without making a service call + * @param id id of the stored procedure + * @return a cosmos stored procedure + */ + public CosmosStoredProcedure getStoredProcedure(String id){ + return new CosmosStoredProcedure(id, this.container); + } + + + /* UDF Operations */ + + /** + * Creates a cosmos user defined function. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single cosmos user defined function response. + * In case of failure the {@link Mono} will error. + * + * @param properties the cosmos user defined function properties + * @param options the cosmos request options. + * @return an {@link Mono} containing the single resource response with the created user defined function or an error. + */ + public Mono createUserDefinedFunction(CosmosUserDefinedFunctionProperties properties, + CosmosRequestOptions options){ + UserDefinedFunction udf = new UserDefinedFunction(); + udf.id(properties.id()); + udf.setBody(properties.body()); + if(options == null){ + options = new CosmosRequestOptions(); + } + return database.getDocClientWrapper() + .createUserDefinedFunction(container.getLink(), udf, options.toRequestOptions()) + .map(response -> new CosmosUserDefinedFunctionResponse(response, this.container)).single(); + } + + /** + * Reads all cosmos user defined functions in the container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the read user defined functions. + * In case of failure the {@link Flux} will error. + * + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the read user defined functions or an error. + */ + public Flux> listUserDefinedFunctions(FeedOptions options){ + return database.getDocClientWrapper() + .readUserDefinedFunctions(container.getLink(), options) + .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionProperties.getFromV2Results(response.results()), + response.responseHeaders())); + } + + /** + * Query for user defined functions in the container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained user defined functions. + * In case of failure the {@link Flux} will error. + * + * @param query the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained user defined functions or an error. + */ + public Flux> queryUserDefinedFunctions(String query, + FeedOptions options){ + return queryUserDefinedFunctions(new SqlQuerySpec(query), options); + } + + /** + * Query for user defined functions in the container. + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained user defined functions. + * In case of failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained user defined functions or an error. + */ + public Flux> queryUserDefinedFunctions(SqlQuerySpec querySpec, + FeedOptions options){ + return database.getDocClientWrapper() + .queryUserDefinedFunctions(container.getLink(),querySpec, options) + .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionProperties.getFromV2Results(response.results()), + response.responseHeaders())); + } + + /** + * Gets a CosmosUserDefinedFunction object without making a service call + * @param id id of the user defined function + * @return a cosmos user defined function + */ + public CosmosUserDefinedFunction getUserDefinedFunction(String id){ + return new CosmosUserDefinedFunction(id, this.container); + } + + /* Trigger Operations */ + /** + * Creates a Cosmos trigger. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a cosmos trigger response + * In case of failure the {@link Mono} will error. + * + * @param properties the cosmos trigger properties + * @param options the request options. + * @return an {@link Mono} containing the single resource response with the created trigger or an error. + */ + public Mono createTrigger(CosmosTriggerProperties properties, + CosmosRequestOptions options){ + Trigger trigger = new Trigger(properties.toJson()); + if(options == null){ + options = new CosmosRequestOptions(); + } + return database.getDocClientWrapper() + .createTrigger(container.getLink(), trigger,options.toRequestOptions()) + .map(response -> new CosmosTriggerResponse(response, this.container)) + .single(); + } + + /** + * Reads all triggers in a container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the read cosmos trigger settings. + * In case of failure the {@link Flux} will error. + * + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the read cosmos rigger settings or an error. + */ + public Flux> listTriggers(FeedOptions options){ + return database.getDocClientWrapper() + .readTriggers(container.getLink(), options) + .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerProperties.getFromV2Results(response.results()), + response.responseHeaders())); + } + + /** + * Query for triggers in the container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained triggers. + * In case of failure the {@link Flux} will error. + * + * @param query the query. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained triggers or an error. + */ + public Flux> queryTriggers(String query, FeedOptions options){ + return queryTriggers(new SqlQuerySpec(query), options); + } + + /** + * Query for triggers in the container + * + * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained triggers. + * In case of failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @param options the feed options. + * @return an {@link Flux} containing one or several feed response pages of the obtained triggers or an error. + */ + public Flux> queryTriggers(SqlQuerySpec querySpec, + FeedOptions options){ + return database.getDocClientWrapper() + .queryTriggers(container.getLink(), querySpec, options) + .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerProperties.getFromV2Results(response.results()), + response.responseHeaders())); + } + + /** + * Gets a CosmosTrigger object without making a service call + * @param id id of the cosmos trigger + * @return a cosmos trigger + */ + public CosmosTrigger getTrigger(String id){ + return new CosmosTrigger(id, this.container); + } + +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java index 31c96fb7060de..a5e8d2a83b37d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java @@ -25,23 +25,32 @@ import com.azure.data.cosmos.internal.Paths; import reactor.core.publisher.Mono; -public class CosmosStoredProcedure extends CosmosResource { +public class CosmosStoredProcedure { private CosmosContainer cosmosContainer; + private String id; CosmosStoredProcedure(String id, CosmosContainer cosmosContainer) { - super(id); + this.id = id; this.cosmosContainer = cosmosContainer; } - @Override - protected String URIPathSegment() { - return Paths.STORED_PROCEDURES_PATH_SEGMENT; + /** + * Get the id of the {@link CosmosStoredProcedure} + * @return the id of the {@link CosmosStoredProcedure} + */ + public String id() { + return id; } - @Override - protected String parentLink() { - return cosmosContainer.getLink(); + /** + * Set the id of the {@link CosmosStoredProcedure} + * @param id the id of the {@link CosmosStoredProcedure} + * @return the same {@link CosmosStoredProcedure} that had the id set + */ + CosmosStoredProcedure id(String id) { + this.id = id; + return this; } /** @@ -117,4 +126,21 @@ public Mono replace(CosmosStoredProcedureProperti .single(); } + String URIPathSegment() { + return Paths.STORED_PROCEDURES_PATH_SEGMENT; + } + + String parentLink() { + return cosmosContainer.getLink(); + } + + String getLink() { + StringBuilder builder = new StringBuilder(); + builder.append(parentLink()); + builder.append("/"); + builder.append(URIPathSegment()); + builder.append("/"); + builder.append(id()); + return builder.toString(); + } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java index dde52f6a8457b..48c4afcb1b8ba 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java @@ -25,23 +25,32 @@ import com.azure.data.cosmos.internal.Paths; import reactor.core.publisher.Mono; -public class CosmosTrigger extends CosmosResource { +public class CosmosTrigger { private CosmosContainer container; + private String id; CosmosTrigger(String id, CosmosContainer container) { - super(id); + this.id = id; this.container = container; } - @Override - protected String URIPathSegment() { - return Paths.TRIGGERS_PATH_SEGMENT; + /** + * Get the id of the {@link CosmosTrigger} + * @return the id of the {@link CosmosTrigger} + */ + public String id() { + return id; } - @Override - protected String parentLink() { - return container.getLink(); + /** + * Set the id of the {@link CosmosTrigger} + * @param id the id of the {@link CosmosTrigger} + * @return the same {@link CosmosTrigger} that had the id set + */ + CosmosTrigger id(String id) { + this.id = id; + return this; } /** @@ -100,4 +109,22 @@ public Mono delete(CosmosRequestOptions options) { .single(); } + String URIPathSegment() { + return Paths.TRIGGERS_PATH_SEGMENT; + } + + String parentLink() { + return container.getLink(); + } + + String getLink() { + StringBuilder builder = new StringBuilder(); + builder.append(parentLink()); + builder.append("/"); + builder.append(URIPathSegment()); + builder.append("/"); + builder.append(id()); + return builder.toString(); + } + } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java index 36cafd51b737c..62d7977eff7b1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java @@ -4,13 +4,33 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -public class CosmosUser extends CosmosResource { +public class CosmosUser { CosmosDatabase database; + private String id; + CosmosUser(String id, CosmosDatabase database) { - super(id); + this.id = id; this.database = database; } + /** + * Get the id of the {@link CosmosUser} + * @return the id of the {@link CosmosUser} + */ + public String id() { + return id; + } + + /** + * Set the id of the {@link CosmosUser} + * @param id the id of the {@link CosmosUser} + * @return the same {@link CosmosUser} that had the id set + */ + CosmosUser id(String id) { + this.id = id; + return this; + } + /** * Reads a cosmos user * @return an {@link Mono} containing the single cosmos user response with the read user or an error. @@ -143,17 +163,30 @@ public Flux> queryPermissions(String qu public CosmosPermission getPermission(String id){ return new CosmosPermission(id, this); } - - @Override - protected String URIPathSegment() { + + String URIPathSegment() { return Paths.USERS_PATH_SEGMENT; } - @Override - protected String parentLink() { + String parentLink() { return database.getLink() ; } + String getLink() { + StringBuilder builder = new StringBuilder(); + builder.append(parentLink()); + builder.append("/"); + builder.append(URIPathSegment()); + builder.append("/"); + builder.append(id()); + return builder.toString(); + } + + /** + * Gets the parent Database + * + * @return the (@link CosmosDatabase) + */ public CosmosDatabase getDatabase() { return database; } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java index 6f014fe020c7a..f0f6295d6a748 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java @@ -25,15 +25,34 @@ import com.azure.data.cosmos.internal.Paths; import reactor.core.publisher.Mono; -public class CosmosUserDefinedFunction extends CosmosResource { +public class CosmosUserDefinedFunction { private CosmosContainer container; + private String id; CosmosUserDefinedFunction(String id, CosmosContainer container) { - super(id); + this.id = id; this.container = container; } + /** + * Get the id of the {@link CosmosUserDefinedFunction} + * @return the id of the {@link CosmosUserDefinedFunction} + */ + public String id() { + return id; + } + + /** + * Set the id of the {@link CosmosUserDefinedFunction} + * @param id the id of the {@link CosmosUserDefinedFunction} + * @return the same {@link CosmosUserDefinedFunction} that had the id set + */ + CosmosUserDefinedFunction id(String id) { + this.id = id; + return this; + } + /** * READ a user defined function. *

@@ -92,13 +111,21 @@ public Mono delete(CosmosRequestOptions options) { .single(); } - @Override - protected String URIPathSegment() { + String URIPathSegment() { return Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT; } - @Override - protected String parentLink() { + String parentLink() { return container.getLink(); } + + String getLink() { + StringBuilder builder = new StringBuilder(); + builder.append(parentLink()); + builder.append("/"); + builder.append(URIPathSegment()); + builder.append("/"); + builder.append(id()); + return builder.toString(); + } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java index c31297d4cec98..af0eb8f9c21dd 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java @@ -47,6 +47,8 @@ import java.net.URI; +import static com.azure.data.cosmos.CosmosBridgeInternal.getContextClient; + /** * Implementation for ChangeFeedDocumentClient. */ @@ -66,7 +68,7 @@ public ChangeFeedContextClientImpl(CosmosContainer cosmosContainer) } this.cosmosContainer = cosmosContainer; - this.documentClient = CosmosContainer.getContextClient(cosmosContainer); + this.documentClient = getContextClient(cosmosContainer); this.rxScheduler = Schedulers.elastic(); } @@ -82,7 +84,7 @@ public ChangeFeedContextClientImpl(CosmosContainer cosmosContainer, Scheduler rx } this.cosmosContainer = cosmosContainer; - this.documentClient = CosmosContainer.getContextClient(cosmosContainer); + this.documentClient = getContextClient(cosmosContainer); this.rxScheduler = rxScheduler; } diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java index b3e8e6b2a714f..25a3081572adf 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java @@ -214,7 +214,7 @@ public void testNonPartitionedCollectionOperations() throws Exception { " });" + "}'" + "}"); - CosmosStoredProcedure createdSproc = createdContainer.createStoredProcedure(sproc).block().storedProcedure(); + CosmosStoredProcedure createdSproc = createdContainer.getScripts().createStoredProcedure(sproc).block().storedProcedure(); // Partiton Key value same as what is specified in the stored procedure body RequestOptions options = new RequestOptions(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java index dd06878843edd..dde5f00e8de37 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java @@ -58,17 +58,15 @@ public void readStoredProcedures() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdCollection.listStoredProcedures(options); + Flux> feedObservable = createdCollection.getScripts() + .listStoredProcedures(options); int expectedPageSize = (createdStoredProcedures.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdStoredProcedures.size()) - .exactlyContainsInAnyOrder(createdStoredProcedures - .stream() - .map(d -> d.resourceId()) - .collect(Collectors.toList())) + .exactlyContainsInAnyOrder( + createdStoredProcedures.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -82,7 +80,7 @@ public void beforeClass() { createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); - for(int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { createdStoredProcedures.add(createStoredProcedures(createdCollection)); } @@ -98,6 +96,7 @@ public CosmosStoredProcedureProperties createStoredProcedures(CosmosContainer co CosmosStoredProcedureProperties sproc = new CosmosStoredProcedureProperties(); sproc.id(UUID.randomUUID().toString()); sproc.body("function() {var x = 10;}"); - return cosmosContainer.createStoredProcedure(sproc, new CosmosStoredProcedureRequestOptions()).block().properties(); + return cosmosContainer.getScripts().createStoredProcedure(sproc, new CosmosStoredProcedureRequestOptions()) + .block().properties(); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java index e58e78ae5ddc1..3c9a9b4865d11 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java @@ -60,17 +60,14 @@ public void readTriggers() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdCollection.listTriggers(options); + Flux> feedObservable = createdCollection.getScripts().listTriggers(options); int expectedPageSize = (createdTriggers.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdTriggers.size()) - .exactlyContainsInAnyOrder(createdTriggers - .stream() - .map(d -> d.resourceId()) - .collect(Collectors.toList())) + .exactlyContainsInAnyOrder( + createdTriggers.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -84,7 +81,7 @@ public void beforeClass() { createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); - for(int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { this.createdTriggers.add(this.createTriggers(createdCollection)); } @@ -102,6 +99,6 @@ public CosmosTriggerProperties createTriggers(CosmosContainer cosmosContainer) { trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - return cosmosContainer.createTrigger(trigger, new CosmosRequestOptions()).block().properties(); + return cosmosContainer.getScripts().createTrigger(trigger, new CosmosRequestOptions()).block().properties(); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java index 9b64e8408f23f..1d4ec7b797092 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java @@ -60,17 +60,16 @@ public void readUserDefinedFunctions() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdCollection.listUserDefinedFunctions(options); + Flux> feedObservable = createdCollection.getScripts() + .listUserDefinedFunctions(options); - int expectedPageSize = (createdUserDefinedFunctions.size() + options.maxItemCount() - 1) / options.maxItemCount(); + int expectedPageSize = (createdUserDefinedFunctions.size() + options.maxItemCount() - 1) + / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdUserDefinedFunctions.size()) - .exactlyContainsInAnyOrder(createdUserDefinedFunctions - .stream() - .map(d -> d.resourceId()) - .collect(Collectors.toList())) + .exactlyContainsInAnyOrder( + createdUserDefinedFunctions.stream().map(d -> d.resourceId()).collect(Collectors.toList())) .numberOfPages(expectedPageSize) .allPagesSatisfy(new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) @@ -84,7 +83,7 @@ public void beforeClass() { createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); - for(int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { createdUserDefinedFunctions.add(createUserDefinedFunctions(createdCollection)); } @@ -98,9 +97,10 @@ public void afterClass() { public CosmosUserDefinedFunctionProperties createUserDefinedFunctions(CosmosContainer cosmosContainer) { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); - udf.id(UUID.randomUUID().toString()); - udf.body("function() {var x = 10;}"); - return cosmosContainer.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().settings(); + udf.id(UUID.randomUUID().toString()); + udf.body("function() {var x = 10;}"); + return cosmosContainer.getScripts().createUserDefinedFunction(udf, new CosmosRequestOptions()).block() + .settings(); } private String getCollectionLink() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java index 96959185d6694..377d08c486c0d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java @@ -58,7 +58,7 @@ public void createStoredProcedure() throws Exception { storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); - Mono createObservable = container.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()); + Mono createObservable = container.getScripts().createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder() .withId(storedProcedureDef.id()) @@ -75,7 +75,7 @@ public void readStoredProcedure() throws Exception { CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); - CosmosStoredProcedure storedProcedure = container.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); + CosmosStoredProcedure storedProcedure = container.getScripts().createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); waitIfNeededForReplicasToCatchUp(clientBuilder()); Mono readObservable = storedProcedure.read(null); @@ -96,7 +96,7 @@ public void deleteStoredProcedure() throws Exception { storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); - CosmosStoredProcedure storedProcedure = this.container.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); + CosmosStoredProcedure storedProcedure = this.container.getScripts().createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); Mono deleteObservable = storedProcedure.delete(new CosmosStoredProcedureRequestOptions()); CosmosResponseValidator validator = new CosmosResponseValidator.Builder<>() diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java index e9fe458c42e37..34c2fdde55c31 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java @@ -62,9 +62,11 @@ public void queryWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(5); - Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); + Flux> queryObservable = createdCollection.getScripts() + .queryStoredProcedures(query, options); - List expectedDocs = createdStoredProcs.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList()); + List expectedDocs = createdStoredProcs.stream() + .filter(sp -> filterId.equals(sp.id())).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); @@ -86,11 +88,11 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); + Flux> queryObservable = createdCollection.getScripts() + .queryStoredProcedures(query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() - .containsExactly(new ArrayList<>()) - .numberOfPages(1) + .containsExactly(new ArrayList<>()).numberOfPages(1) .pageSatisfy(0, new FeedResponseValidator.Builder() .requestChargeGreaterThanOrEqualTo(1.0).build()) .build(); @@ -104,22 +106,19 @@ public void queryAll() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(3); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); + Flux> queryObservable = createdCollection.getScripts() + .queryStoredProcedures(query, options); List expectedDocs = createdStoredProcs; int expectedPageSize = (expectedDocs.size() + options.maxItemCount() - 1) / options.maxItemCount(); - FeedResponseListValidator validator = new FeedResponseListValidator - .Builder() - .exactlyContainsInAnyOrder(expectedDocs - .stream() - .map(d -> d.resourceId()) - .collect(Collectors.toList())) - .numberOfPages(expectedPageSize) - .allPagesSatisfy(new FeedResponseValidator.Builder() - .requestChargeGreaterThanOrEqualTo(1.0).build()) - .build(); + FeedResponseListValidator validator = new FeedResponseListValidator.Builder() + .exactlyContainsInAnyOrder(expectedDocs.stream().map(d -> d.resourceId()).collect(Collectors.toList())) + .numberOfPages(expectedPageSize) + .allPagesSatisfy(new FeedResponseValidator.Builder() + .requestChargeGreaterThanOrEqualTo(1.0).build()) + .build(); validateQuerySuccess(queryObservable, validator); } @@ -129,19 +128,17 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryStoredProcedures(query, options); + Flux> queryObservable = createdCollection.getScripts() + .queryStoredProcedures(query, options); - FailureValidator validator = new FailureValidator.Builder() - .instanceOf(CosmosClientException.class) - .statusCode(400) - .notNullActivityId() - .build(); + FailureValidator validator = new FailureValidator.Builder().instanceOf(CosmosClientException.class) + .statusCode(400).notNullActivityId().build(); validateQueryFailure(queryObservable, validator); } public CosmosStoredProcedureProperties createStoredProc(CosmosContainer cosmosContainer) { CosmosStoredProcedureProperties storedProcedure = getStoredProcedureDef(); - return cosmosContainer.createStoredProcedure(storedProcedure).block().properties(); + return cosmosContainer.getScripts().createStoredProcedure(storedProcedure).block().properties(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) @@ -150,7 +147,7 @@ public void beforeClass() throws Exception { createdCollection = getSharedMultiPartitionCosmosContainer(client); truncateCollection(createdCollection); - for(int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) { createdStoredProcs.add(createStoredProc(createdCollection)); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java index f548f651c04a8..1ccaea396ca1c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java @@ -61,52 +61,45 @@ public void replaceStoredProcedure() throws Exception { CosmosStoredProcedureProperties storedProcedureDef = new CosmosStoredProcedureProperties(); storedProcedureDef.id(UUID.randomUUID().toString()); storedProcedureDef.body("function() {var x = 10;}"); - CosmosStoredProcedureProperties readBackSp = createdCollection.createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block().properties(); + CosmosStoredProcedureProperties readBackSp = createdCollection.getScripts() + .createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block() + .properties(); // read stored procedure to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder()); - Mono readObservable = createdCollection.getStoredProcedure(readBackSp.id()).read(null); + Mono readObservable = createdCollection.getScripts() + .getStoredProcedure(readBackSp.id()).read(null); // validate stored procedure creation CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() - .withId(readBackSp.id()) - .withStoredProcedureBody("function() {var x = 10;}") - .notNullEtag() - .build(); + .withId(readBackSp.id()).withStoredProcedureBody("function() {var x = 10;}").notNullEtag().build(); validateSuccess(readObservable, validatorForRead); - - //update stored procedure + + // update stored procedure readBackSp.body("function() {var x = 11;}"); - Mono replaceObservable = createdCollection.getStoredProcedure(readBackSp.id()).replace(readBackSp, new RequestOptions()); + Mono replaceObservable = createdCollection.getScripts() + .getStoredProcedure(readBackSp.id()).replace(readBackSp, new RequestOptions()); - //validate stored procedure replace + // validate stored procedure replace CosmosResponseValidator validatorForReplace = new CosmosResponseValidator.Builder() - .withId(readBackSp.id()) - .withStoredProcedureBody("function() {var x = 11;}") - .notNullEtag() - .build(); - validateSuccess(replaceObservable, validatorForReplace); + .withId(readBackSp.id()).withStoredProcedureBody("function() {var x = 11;}").notNullEtag().build(); + validateSuccess(replaceObservable, validatorForReplace); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void executeStoredProcedure() throws Exception { // create a stored procedure - CosmosStoredProcedureProperties storedProcedureDef = BridgeInternal.createCosmosStoredProcedureProperties( - "{" + - " 'id': '" + UUID.randomUUID().toString() + "'," + - " 'body':" + - " 'function () {" + - " for (var i = 0; i < 10; i++) {" + - " getContext().getResponse().appendValue(\"Body\", i);" + - " }" + - " }'" + - "}"); + CosmosStoredProcedureProperties storedProcedureDef = BridgeInternal + .createCosmosStoredProcedureProperties("{" + " 'id': '" + UUID.randomUUID().toString() + "'," + + " 'body':" + " 'function () {" + " for (var i = 0; i < 10; i++) {" + + " getContext().getResponse().appendValue(\"Body\", i);" + " }" + " }'" + "}"); CosmosStoredProcedure storedProcedure = null; - storedProcedure = createdCollection.createStoredProcedure(storedProcedureDef, - new CosmosStoredProcedureRequestOptions()).block().storedProcedure(); + storedProcedure = createdCollection.getScripts() + .createStoredProcedure(storedProcedureDef, new CosmosStoredProcedureRequestOptions()).block() + .storedProcedure(); String result = null; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index 531d8d53fc15a..e9796ded07bc8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -250,7 +250,7 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { }).then().block(); logger.info("Truncating collection {} triggers ...", cosmosContainerId); - cosmosContainer.queryTriggers("SELECT * FROM root", options) + cosmosContainer.getScripts().queryTriggers("SELECT * FROM root", options) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(trigger -> { @@ -261,12 +261,12 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { // requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getTrigger(trigger.id()).delete(requestOptions); + return cosmosContainer.getScripts().getTrigger(trigger.id()).delete(requestOptions); }).then().block(); logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); - cosmosContainer.queryStoredProcedures("SELECT * FROM root", options) + cosmosContainer.getScripts().queryStoredProcedures("SELECT * FROM root", options) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(storedProcedure -> { @@ -277,12 +277,12 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { // requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getStoredProcedure(storedProcedure.id()).delete(requestOptions); + return cosmosContainer.getScripts().getStoredProcedure(storedProcedure.id()).delete(requestOptions); }).then().block(); logger.info("Truncating collection {} udfs ...", cosmosContainerId); - cosmosContainer.queryUserDefinedFunctions("SELECT * FROM root", options) + cosmosContainer.getScripts().queryUserDefinedFunctions("SELECT * FROM root", options) .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(udf -> { @@ -293,7 +293,7 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { // requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getUserDefinedFunction(udf.id()).delete(requestOptions); + return cosmosContainer.getScripts().getUserDefinedFunction(udf.id()).delete(requestOptions); }).then().block(); logger.info("Finished truncating collection {}.", cosmosContainerId); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java index 0b88c81b626f4..c7d9077791516 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java @@ -62,7 +62,7 @@ public void createTrigger() throws Exception { trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - Mono createObservable = createdCollection.createTrigger(trigger, new CosmosRequestOptions()); + Mono createObservable = createdCollection.getScripts().createTrigger(trigger, new CosmosRequestOptions()); // validate trigger creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -82,7 +82,7 @@ public void readTrigger() throws Exception { trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - CosmosTrigger readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().trigger(); + CosmosTrigger readBackTrigger = createdCollection.getScripts().createTrigger(trigger, new CosmosRequestOptions()).block().trigger(); // read trigger waitIfNeededForReplicasToCatchUp(clientBuilder()); @@ -106,7 +106,7 @@ public void deleteTrigger() throws Exception { trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - CosmosTrigger readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().trigger(); + CosmosTrigger readBackTrigger = createdCollection.getScripts().createTrigger(trigger, new CosmosRequestOptions()).block().trigger(); // delete trigger Mono deleteObservable = readBackTrigger.delete(new CosmosRequestOptions()); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java index 9f499a63ea509..50856df0e9cf2 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java @@ -66,7 +66,7 @@ public void queryWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(5); - Flux> queryObservable = createdCollection.queryTriggers(query, options); + Flux> queryObservable = createdCollection.getScripts().queryTriggers(query, options); List expectedDocs = createdTriggers .stream() @@ -93,7 +93,7 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryTriggers(query, options); + Flux> queryObservable = createdCollection.getScripts().queryTriggers(query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) @@ -111,7 +111,7 @@ public void queryAll() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(3); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryTriggers(query, options); + Flux> queryObservable = createdCollection.getScripts().queryTriggers(query, options); createdTriggers.forEach(cosmosTriggerSettings -> logger.info("Created trigger in method: {}", cosmosTriggerSettings.resourceId())); @@ -137,7 +137,7 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryTriggers(query, options); + Flux> queryObservable = createdCollection.getScripts().queryTriggers(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(CosmosClientException.class) @@ -149,7 +149,7 @@ public void invalidQuerySytax() throws Exception { public CosmosTriggerProperties createTrigger(CosmosContainer cosmosContainer) { CosmosTriggerProperties storedProcedure = getTriggerDef(); - return cosmosContainer.createTrigger(storedProcedure, new CosmosRequestOptions()).block().properties(); + return cosmosContainer.getScripts().createTrigger(storedProcedure, new CosmosRequestOptions()).block().properties(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java index 7319c383e9906..8994d2f724a61 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java @@ -60,11 +60,11 @@ public void replaceTrigger() throws Exception { trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - CosmosTriggerProperties readBackTrigger = createdCollection.createTrigger(trigger, new CosmosRequestOptions()).block().properties(); + CosmosTriggerProperties readBackTrigger = createdCollection.getScripts().createTrigger(trigger, new CosmosRequestOptions()).block().properties(); // read trigger to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder()); - Mono readObservable = createdCollection.getTrigger(readBackTrigger.id()).read(new RequestOptions()); + Mono readObservable = createdCollection.getScripts().getTrigger(readBackTrigger.id()).read(new RequestOptions()); // validate trigger creation CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() @@ -78,7 +78,7 @@ public void replaceTrigger() throws Exception { //update trigger readBackTrigger.body("function() {var x = 11;}"); - Mono updateObservable = createdCollection.getTrigger(readBackTrigger.id()).replace(readBackTrigger, new RequestOptions()); + Mono updateObservable = createdCollection.getScripts().getTrigger(readBackTrigger.id()).replace(readBackTrigger, new RequestOptions()); // validate trigger replace CosmosResponseValidator validatorForUpdate = new CosmosResponseValidator.Builder() diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java index 0c4794f672393..f3dcf66396ca1 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java @@ -56,7 +56,7 @@ public void createUserDefinedFunction() throws Exception { udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); - Mono createObservable = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()); + Mono createObservable = createdCollection.getScripts().createUserDefinedFunction(udf, new CosmosRequestOptions()); // validate udf creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -73,7 +73,7 @@ public void readUserDefinedFunction() throws Exception { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); - CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); + CosmosUserDefinedFunction readBackUdf = createdCollection.getScripts().createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); // read udf waitIfNeededForReplicasToCatchUp(clientBuilder()); @@ -94,7 +94,7 @@ public void deleteUserDefinedFunction() throws Exception { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); - CosmosUserDefinedFunction readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); + CosmosUserDefinedFunction readBackUdf = createdCollection.getScripts().createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); // delete udf Mono deleteObservable = readBackUdf.delete(new CosmosRequestOptions()); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java index ac77dbf07619c..85548455060e0 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java @@ -69,7 +69,7 @@ public void queryWithFilter() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(5); - Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); + Flux> queryObservable = createdCollection.getScripts().queryUserDefinedFunctions(query, options); List expectedDocs = createdUDF.stream().filter(sp -> filterId.equals(sp.id()) ).collect(Collectors.toList()); assertThat(expectedDocs).isNotEmpty(); @@ -93,7 +93,7 @@ public void query_NoResults() throws Exception { String query = "SELECT * from root r where r.id = '2'"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); + Flux> queryObservable = createdCollection.getScripts().queryUserDefinedFunctions(query, options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .containsExactly(new ArrayList<>()) @@ -111,7 +111,7 @@ public void queryAll() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(3); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); + Flux> queryObservable = createdCollection.getScripts().queryUserDefinedFunctions(query, options); List expectedDocs = createdUDF; @@ -135,7 +135,7 @@ public void invalidQuerySytax() throws Exception { String query = "I am an invalid query"; FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.queryUserDefinedFunctions(query, options); + Flux> queryObservable = createdCollection.getScripts().queryUserDefinedFunctions(query, options); FailureValidator validator = new FailureValidator.Builder() .instanceOf(CosmosClientException.class) @@ -147,7 +147,7 @@ public void invalidQuerySytax() throws Exception { public CosmosUserDefinedFunctionProperties createUserDefinedFunction(CosmosContainer cosmosContainer) { CosmosUserDefinedFunctionProperties storedProcedure = getUserDefinedFunctionDef(); - return cosmosContainer.createUserDefinedFunction(storedProcedure, new CosmosRequestOptions()).block().settings(); + return cosmosContainer.getScripts().createUserDefinedFunction(storedProcedure, new CosmosRequestOptions()).block().settings(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java index ac41c035b9aa8..0f8ae18382ec9 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java @@ -59,11 +59,11 @@ public void replaceUserDefinedFunction() throws Exception { CosmosUserDefinedFunctionProperties readBackUdf = null; - readBackUdf = createdCollection.createUserDefinedFunction(udf, new CosmosRequestOptions()).block().settings(); + readBackUdf = createdCollection.getScripts().createUserDefinedFunction(udf, new CosmosRequestOptions()).block().settings(); // read udf to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder()); - Mono readObservable = createdCollection.getUserDefinedFunction(readBackUdf.id()).read(new RequestOptions()); + Mono readObservable = createdCollection.getScripts().getUserDefinedFunction(readBackUdf.id()).read(new RequestOptions()); // validate udf creation CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() @@ -76,7 +76,7 @@ public void replaceUserDefinedFunction() throws Exception { //update udf readBackUdf.body("function() {var x = 11;}"); - Mono replaceObservable = createdCollection.getUserDefinedFunction(readBackUdf.id()).replace(readBackUdf, new RequestOptions()); + Mono replaceObservable = createdCollection.getScripts().getUserDefinedFunction(readBackUdf.id()).replace(readBackUdf, new RequestOptions()); //validate udf replace CosmosResponseValidator validatorForReplace = new CosmosResponseValidator.Builder() From 5c6781c3800b0f873a919c357841465505980a16 Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Wed, 26 Jun 2019 19:29:00 -0700 Subject: [PATCH 50/85] Moved old types to internal package and other changes (#209) * Collection to list changes, moved old types to internal, pom file change to exclude BridgeInternal and CosmosBridgeInternal * Fix build issues with scripts * fix partition key bug * JsonSerializable handle private constructors * Add test coverage IndexingPolicy deserialization * Remove Collection in favor of List * Code Review changes, excluded all BridgeInternal from API docs * Fixed constructor scope --- .../data/cosmos/benchmark/AsyncBenchmark.java | 2 +- .../cosmos/benchmark/AsyncMixedBenchmark.java | 6 +- .../cosmos/benchmark/AsyncQueryBenchmark.java | 2 +- .../AsyncQuerySinglePartitionMultiple.java | 2 +- .../cosmos/benchmark/AsyncReadBenchmark.java | 6 +- .../cosmos/benchmark/AsyncWriteBenchmark.java | 2 +- .../cosmos/benchmark/ReadMyWriteWorkflow.java | 6 +- .../ReadMyWritesConsistencyTest.java | 5 +- .../azure/data/cosmos/benchmark/Utils.java | 2 +- .../data/cosmos/benchmark/WorkflowTest.java | 5 +- .../azure/data/cosmos/DatabaseForTest.java | 1 + .../data/cosmos/rx/FailureValidator.java | 6 +- .../cosmos/rx/FeedResponseListValidator.java | 6 +- .../cosmos/rx/ResourceResponseValidator.java | 14 ++-- .../com/azure/data/cosmos/BridgeInternal.java | 29 +++++--- .../azure/data/cosmos/ChangeFeedOptions.java | 2 + .../data/cosmos/ConflictResolutionMode.java | 1 + .../data/cosmos/ConflictResolutionPolicy.java | 1 + .../azure/data/cosmos/ConnectionPolicy.java | 2 + .../data/cosmos/CosmosClientException.java | 32 ++++----- .../cosmos/CosmosContainerProperties.java | 1 + .../cosmos/CosmosContainerRequestOptions.java | 2 + .../data/cosmos/CosmosDatabaseProperties.java | 2 + .../cosmos/CosmosDatabaseRequestOptions.java | 2 + .../cosmos/{Error.java => CosmosError.java} | 12 ++-- .../data/cosmos/CosmosItemRequestOptions.java | 3 + .../data/cosmos/CosmosRequestOptions.java | 2 + .../com/azure/data/cosmos/CosmosResponse.java | 3 + .../CosmosStoredProcedureProperties.java | 2 + .../CosmosStoredProcedureRequestOptions.java | 3 + .../data/cosmos/CosmosTriggerProperties.java | 2 + .../CosmosUserDefinedFunctionProperties.java | 2 + .../data/cosmos/CosmosUserProperties.java | 2 + .../azure/data/cosmos/DatabaseAccount.java | 1 + .../azure/data/cosmos/FeedOptionsBase.java | 2 + .../com/azure/data/cosmos/FeedResponse.java | 2 + .../com/azure/data/cosmos/IndexingPolicy.java | 36 +++++----- .../azure/data/cosmos/JsonSerializable.java | 15 +++- .../com/azure/data/cosmos/MediaOptions.java | 68 ------------------- .../com/azure/data/cosmos/MediaResponse.java | 65 ------------------ .../data/cosmos/PartitionKeyDefinition.java | 2 +- .../com/azure/data/cosmos/RangeIndex.java | 2 +- .../java/com/azure/data/cosmos/Resource.java | 2 +- .../com/azure/data/cosmos/SpatialIndex.java | 6 +- .../com/azure/data/cosmos/SpatialSpec.java | 11 +-- .../java/com/azure/data/cosmos/UniqueKey.java | 9 +-- .../azure/data/cosmos/UniqueKeyPolicy.java | 9 +-- .../directconnectivity/GoneException.java | 10 +-- .../RequestTimeoutException.java | 6 +- .../cosmos/internal/BadRequestException.java | 6 +- .../DocumentServiceRequestContext.java | 1 - .../InternalServerErrorException.java | 6 +- .../cosmos/{ => internal}/MediaReadMode.java | 2 +- .../data/cosmos/{ => internal}/Offer.java | 18 ++--- .../cosmos/{ => internal}/PartitionKey.java | 9 ++- .../{ => internal}/PartitionKeyRange.java | 13 ++-- .../data/cosmos/internal/PathsHelper.java | 6 -- .../cosmos/{ => internal}/Permission.java | 14 ++-- .../cosmos/{ => internal}/QueryMetrics.java | 10 +-- .../{ => internal}/QueryMetricsConstants.java | 2 +- .../{ => internal}/QueryMetricsUtils.java | 4 +- .../{ => internal}/QueryPreparationTimes.java | 2 +- .../{ => internal}/ReplicationPolicy.java | 9 +-- .../cosmos/{ => internal}/RequestOptions.java | 6 +- .../{ => internal}/ResourceResponse.java | 6 +- .../{ => internal}/RuntimeExecutionTimes.java | 2 +- .../internal/RxDocumentServiceRequest.java | 1 - .../internal/RxDocumentServiceResponse.java | 7 -- .../{ => internal}/StoredProcedure.java | 7 +- .../StoredProcedureResponse.java | 9 +-- .../data/cosmos/{ => internal}/Trigger.java | 13 ++-- .../data/cosmos/{ => internal}/User.java | 4 +- .../{ => internal}/UserDefinedFunction.java | 7 +- .../query/metrics/QueryMetricsWriter.java | 6 +- .../cosmos/CosmosClientExceptionTest.java | 4 +- .../data/cosmos/DocumentCollectionTests.java | 21 ++++++ .../com/azure/data/cosmos/PermissionTest.java | 2 + .../directconnectivity/AddressResolver.java | 2 +- .../directconnectivity/ConflictException.java | 10 +-- .../ForbiddenException.java | 6 +- .../GatewayAddressCache.java | 2 +- .../GatewayServiceConfigurationReader.java | 2 +- .../directconnectivity/HttpClientUtils.java | 7 +- .../directconnectivity/LockedException.java | 6 +- .../MethodNotAllowedException.java | 6 +- .../PartitionKeyRangeGoneException.java | 6 +- .../PreconditionFailedException.java | 6 +- .../RequestEntityTooLargeException.java | 6 +- .../RequestRateTooLargeException.java | 6 +- .../RetryWithException.java | 6 +- .../ServiceUnavailableException.java | 6 +- .../UnauthorizedException.java | 6 +- .../rntbd/RntbdContextException.java | 10 +-- .../rntbd/RntbdRequestManager.java | 48 ++++++------- .../data/cosmos/PartitionKeyHashingTests.java | 1 + .../AddressResolverTest.java | 4 +- .../AddressSelectorWrapper.java | 2 +- .../ConsistencyReaderTest.java | 2 +- .../GatewayServiceConfiguratorReaderMock.java | 2 +- .../directconnectivity/PartitionKeyTest.java | 8 +-- .../directconnectivity/QuorumReaderTest.java | 2 +- ...catedResourceClientPartitionSplitTest.java | 2 +- .../StoreReaderDotNetTest.java | 4 +- .../directconnectivity/StoreReaderTest.java | 2 +- .../rx/examples/multimaster/Helpers.java | 2 +- .../multimaster/samples/ConflictWorker.java | 6 +- .../examples/CollectionCRUDAsyncAPITest.java | 6 +- .../rx/examples/DatabaseCRUDAsyncAPITest.java | 2 +- .../rx/examples/DocumentCRUDAsyncAPITest.java | 6 +- .../examples/DocumentQueryAsyncAPITest.java | 2 +- .../rx/examples/OfferCRUDAsyncAPITest.java | 6 +- .../examples/StoredProcedureAsyncAPITest.java | 11 ++- .../cosmos/rx/examples/TokenResolverTest.java | 10 +-- .../rx/examples/UniqueIndexAsyncAPITest.java | 6 +- .../azure/data/cosmos/rx/examples/Utils.java | 2 +- .../cosmos/internal/IRoutingMapProvider.java | 1 - .../internal/InvalidPartitionException.java | 6 +- .../cosmos/internal/NotFoundException.java | 6 +- .../PartitionIsMigratingException.java | 6 +- .../PartitionKeyMismatchRetryPolicy.java | 1 - ...PartitionKeyRangeIsSplittingException.java | 6 +- .../cosmos/internal/RxGatewayStoreModel.java | 14 ++-- .../caches/IPartitionKeyRangeCache.java | 2 +- ...ggregateDocumentQueryExecutionContext.java | 2 +- .../DefaultDocumentQueryExecutionContext.java | 4 +- .../internal/query/DocumentProducer.java | 6 +- .../DocumentQueryExecutionContextBase.java | 2 +- .../DocumentQueryExecutionContextFactory.java | 4 +- .../query/OrderByDocumentProducer.java | 4 +- .../OrderByDocumentQueryExecutionContext.java | 5 +- .../cosmos/internal/query/OrderByUtils.java | 2 +- ...ParallelDocumentQueryExecutionContext.java | 2 +- ...llelDocumentQueryExecutionContextBase.java | 2 +- ...ipelinedDocumentQueryExecutionContext.java | 2 +- .../ProxyDocumentQueryExecutionContext.java | 2 +- .../query/orderbyquery/OrderByRowResult.java | 2 +- .../routing/CollectionRoutingMap.java | 2 +- .../routing/InMemoryCollectionRoutingMap.java | 2 +- .../internal/routing/RoutingMapProvider.java | 2 +- .../routing/RoutingMapProviderHelper.java | 2 +- .../azure/data/cosmos/GatewayTestUtils.java | 2 + .../cosmos/internal/SessionContainerTest.java | 1 - .../InMemoryCollectionRoutingMapTest.java | 2 +- .../routing/RoutingMapProviderHelperTest.java | 2 +- pom.xml | 1 + .../data/cosmos/AsyncDocumentClient.java | 14 +++- .../com/azure/data/cosmos/CosmosClient.java | 1 + .../data/cosmos/CosmosClientBuilder.java | 1 + .../com/azure/data/cosmos/CosmosConflict.java | 1 + .../cosmos/CosmosConflictRequestOptions.java | 2 + .../data/cosmos/CosmosConflictResponse.java | 2 + .../azure/data/cosmos/CosmosContainer.java | 5 ++ .../data/cosmos/CosmosContainerResponse.java | 2 + .../com/azure/data/cosmos/CosmosDatabase.java | 2 + .../data/cosmos/CosmosDatabaseResponse.java | 2 + .../com/azure/data/cosmos/CosmosItem.java | 1 + .../azure/data/cosmos/CosmosItemResponse.java | 3 + .../azure/data/cosmos/CosmosPermission.java | 1 + .../cosmos/CosmosPermissionProperties.java | 2 + .../data/cosmos/CosmosPermissionResponse.java | 3 + .../CosmosPermissionsRequestOptions.java | 2 + .../com/azure/data/cosmos/CosmosScripts.java | 3 + .../data/cosmos/CosmosStoredProcedure.java | 2 + .../cosmos/CosmosStoredProcedureResponse.java | 4 ++ .../com/azure/data/cosmos/CosmosTrigger.java | 2 + .../data/cosmos/CosmosTriggerResponse.java | 3 + .../com/azure/data/cosmos/CosmosUser.java | 2 + .../cosmos/CosmosUserDefinedFunction.java | 2 + .../CosmosUserDefinedFunctionResponse.java | 3 + .../azure/data/cosmos/CosmosUserResponse.java | 3 + .../cosmos/internal/RxDocumentClientImpl.java | 31 --------- .../caches/RxPartitionKeyRangeCache.java | 2 +- .../changefeed/ChangeFeedContextClient.java | 2 +- .../ChangeFeedContextClientImpl.java | 2 +- .../PartitionSynchronizerImpl.java | 2 +- ...edByIdCollectionRequestOptionsFactory.java | 2 +- .../GlobalAddressResolver.java | 2 +- .../data/cosmos/CosmosPartitionKeyTests.java | 2 + .../data/cosmos/CosmosResponseValidator.java | 6 +- .../DCDocumentCrudTest.java | 10 +-- .../GatewayAddressCacheTest.java | 2 +- .../cosmos/internal/ConsistencyTests1.java | 4 -- .../cosmos/internal/ConsistencyTests2.java | 2 - .../cosmos/internal/ConsistencyTestsBase.java | 4 -- .../DocumentQuerySpyWireContentTest.java | 1 - .../cosmos/internal/NetworkFailureTest.java | 1 - .../internal/RetryCreateDocumentTest.java | 9 ++- .../cosmos/internal/RetryThrottleTest.java | 1 - .../data/cosmos/internal/SessionTest.java | 2 - .../cosmos/internal/StoreHeaderTests.java | 1 - .../data/cosmos/internal/TestSuiteBase.java | 8 +-- .../GlobalAddressResolverTest.java | 2 +- .../internal/query/DocumentProducerTest.java | 6 +- .../rx/BackPressureCrossPartitionTest.java | 2 +- .../data/cosmos/rx/BackPressureTest.java | 2 +- .../azure/data/cosmos/rx/ChangeFeedTest.java | 6 +- .../data/cosmos/rx/CollectionCrudTest.java | 9 +-- .../data/cosmos/rx/DocumentCrudTest.java | 3 +- .../cosmos/rx/MultiOrderByQueryTests.java | 18 ++--- .../azure/data/cosmos/rx/OfferQueryTest.java | 2 +- .../data/cosmos/rx/OfferReadReplaceTest.java | 4 +- .../cosmos/rx/OrderbyDocumentQueryTest.java | 2 +- .../cosmos/rx/ParallelDocumentQueryTest.java | 2 +- .../data/cosmos/rx/PermissionQueryTest.java | 4 +- .../data/cosmos/rx/ReadFeedOffersTest.java | 2 +- .../cosmos/rx/ReadFeedPermissionsTest.java | 4 +- .../data/cosmos/rx/ReadFeedPkrTests.java | 2 +- .../data/cosmos/rx/ReadFeedUsersTest.java | 2 +- .../data/cosmos/rx/ResourceTokenTest.java | 10 +-- .../rx/StoredProcedureUpsertReplaceTest.java | 4 +- .../azure/data/cosmos/rx/TestSuiteBase.java | 6 +- .../data/cosmos/rx/TokenResolverTest.java | 14 ++-- .../azure/data/cosmos/rx/TopQueryTests.java | 2 +- .../azure/data/cosmos/rx/TriggerCrudTest.java | 2 +- .../cosmos/rx/TriggerUpsertReplaceTest.java | 2 +- .../azure/data/cosmos/rx/UniqueIndexTest.java | 9 +-- .../UserDefinedFunctionUpsertReplaceTest.java | 2 +- 217 files changed, 598 insertions(+), 628 deletions(-) rename commons/src/main/java/com/azure/data/cosmos/{Error.java => CosmosError.java} (93%) delete mode 100644 commons/src/main/java/com/azure/data/cosmos/MediaOptions.java delete mode 100644 commons/src/main/java/com/azure/data/cosmos/MediaResponse.java rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/MediaReadMode.java (97%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/Offer.java (86%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/PartitionKey.java (92%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/PartitionKeyRange.java (91%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/Permission.java (87%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/QueryMetrics.java (96%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/QueryMetricsConstants.java (99%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/QueryMetricsUtils.java (99%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/QueryPreparationTimes.java (99%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/ReplicationPolicy.java (89%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/RequestOptions.java (98%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/ResourceResponse.java (98%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/RuntimeExecutionTimes.java (99%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/StoredProcedure.java (92%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/StoredProcedureResponse.java (95%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/Trigger.java (88%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/User.java (96%) rename commons/src/main/java/com/azure/data/cosmos/{ => internal}/UserDefinedFunction.java (91%) diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java index 25bead6c5a87f..d0121bf048b3f 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.benchmark.Configuration.Operation; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.Meter; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java index a3512b879f9ee..80a75565751d8 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java @@ -26,9 +26,9 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.ResourceResponse; import org.apache.commons.lang3.RandomStringUtils; import reactor.core.publisher.BaseSubscriber; import reactor.core.publisher.Flux; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java index 50132efdabc7c..71cdd6e428924 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import reactor.core.publisher.BaseSubscriber; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java index 665e55877a572..e89278149bb3a 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import reactor.core.publisher.BaseSubscriber; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java index 90882abef8fb4..1f2ec84bc2e65 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java @@ -24,9 +24,9 @@ package com.azure.data.cosmos.benchmark; import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.ResourceResponse; import com.codahale.metrics.Timer; import org.reactivestreams.Subscription; import reactor.core.publisher.BaseSubscriber; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java index 9e08fe86fa10d..c3e69cf140a80 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.ResourceResponse; import com.codahale.metrics.Timer; import org.apache.commons.lang3.RandomStringUtils; import org.reactivestreams.Subscription; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java index f24fe611c51ed..306edfd9f8657 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java @@ -26,9 +26,9 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.SqlParameter; import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java index fb23deca93f1f..8636a48a2bb67 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.rx.TestConfigurations; import com.beust.jcommander.JCommander; import com.google.common.base.CaseFormat; @@ -50,6 +50,7 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -172,7 +173,7 @@ DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { paths.add("/mypk"); partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection includedPaths = new ArrayList<>(); + List includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); includedPath.path("/*"); Collection indexes = new ArrayList<>(); diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java index 37d69d31b833b..8c3822b47cea1 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java @@ -53,7 +53,7 @@ import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.rx.TestConfigurations; diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java index b1dddd6165b77..da8396f10c132 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.rx.TestConfigurations; import com.beust.jcommander.JCommander; import org.apache.commons.lang3.StringUtils; @@ -43,6 +43,7 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; @@ -324,7 +325,7 @@ DocumentCollection getCollectionDefinitionWithRangeRangeIndex() { paths.add("/mypk"); partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection includedPaths = new ArrayList<>(); + List includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); includedPath.path("/*"); Collection indexes = new ArrayList<>(); diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java index 75d9cd02065e4..b0bae44f957cc 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.ResourceResponse; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java index 2d2d1556a0712..f7a1ff3b40af8 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; @@ -133,13 +133,13 @@ public void validate(Throwable t) { return this; } - public Builder error(Error error) { + public Builder error(CosmosError cosmosError) { validators.add(new FailureValidator() { @Override public void validate(Throwable t) { assertThat(t).isNotNull(); assertThat(t).isInstanceOf(CosmosClientException.class); - assertThat(((CosmosClientException) t).error().toJson()).isEqualTo(error.toJson()); + assertThat(((CosmosClientException) t).error().toJson()).isEqualTo(cosmosError.toJson()); } }); return this; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java index 05e1178f05088..152b4e9ac1cbf 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.fasterxml.jackson.databind.node.ArrayNode; @@ -240,8 +240,8 @@ public void validate(List> feedList) { return this; } - public Builder withOrderedResults(ArrayList expectedOrderedList, - ArrayList compositeIndex) { + public Builder withOrderedResults(List expectedOrderedList, + List compositeIndex) { validators.add(new FeedResponseListValidator() { @Override public void validate(List> feedList) { diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java index bfdf71c732766..a3d61ec42d33e 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java @@ -26,18 +26,18 @@ import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.IndexingMode; -import com.azure.data.cosmos.Offer; -import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.internal.Offer; +import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.SpatialSpec; import com.azure.data.cosmos.SpatialType; -import com.azure.data.cosmos.StoredProcedure; -import com.azure.data.cosmos.Trigger; +import com.azure.data.cosmos.internal.StoredProcedure; +import com.azure.data.cosmos.internal.Trigger; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; -import com.azure.data.cosmos.UserDefinedFunction; +import com.azure.data.cosmos.internal.UserDefinedFunction; import org.assertj.core.api.Condition; import java.time.Instant; @@ -300,7 +300,7 @@ public Builder withCompositeIndexes(Collection> comp @Override public void validate(ResourceResponse resourceResponse) { - Iterator> compositeIndexesReadIterator = resourceResponse.getResource() + Iterator> compositeIndexesReadIterator = resourceResponse.getResource() .getIndexingPolicy().compositeIndexes().iterator(); Iterator> compositeIndexesWrittenIterator = compositeIndexesWritten.iterator(); diff --git a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java index 8464e9314bb80..c1aa19da4b966 100644 --- a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java @@ -24,10 +24,16 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.QueryMetrics; +import com.azure.data.cosmos.internal.ReplicationPolicy; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.internal.StoredProcedureResponse; import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -47,8 +53,12 @@ **/ public class BridgeInternal { - public static Error createError(ObjectNode objectNode) { - return new Error(objectNode); + public static CosmosError createCosmosError(ObjectNode objectNode) { + return new CosmosError(objectNode); + } + + public static CosmosError createCosmosError(String jsonString) { + return new CosmosError(jsonString); } public static Document documentFromObject(Object document, ObjectMapper mapper) { @@ -56,15 +66,10 @@ public static Document documentFromObject(Object document, ObjectMapper mapper) } public static ResourceResponse toResourceResponse(RxDocumentServiceResponse response, - Class cls) { + Class cls) { return new ResourceResponse(response, cls); } - public static MediaResponse toMediaResponse(RxDocumentServiceResponse response, - boolean willBuffer) { - return new MediaResponse(response, willBuffer); - } - public static FeedResponse toFeedResponsePage(RxDocumentServiceResponse response, Class cls) { return new FeedResponse(response.getQueryResponse(cls), response.getResponseHeaders()); @@ -300,6 +305,10 @@ public static void setProperty(JsonSerializable jsonSerializable, String pro jsonSerializable.set(propertyName, value); } + public static ObjectNode getObject(JsonSerializable jsonSerializable, String propertyName) { + return jsonSerializable.getObject(propertyName); + } + public static void remove(JsonSerializable jsonSerializable, String propertyName) { jsonSerializable.remove(propertyName); } @@ -307,4 +316,8 @@ public static void remove(JsonSerializable jsonSerializable, String propertyName public static CosmosStoredProcedureProperties createCosmosStoredProcedureProperties(String jsonString) { return new CosmosStoredProcedureProperties(jsonString); } + + public static Object getValue(JsonNode value) { + return JsonSerializable.getValue(value); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java b/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java index 3ee76d9d52103..baf1f3b0dfbb7 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.PartitionKeyRange; + import java.time.OffsetDateTime; /** diff --git a/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java index 769b976ffc65f..d3e058d70e671 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.StoredProcedure; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; diff --git a/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java index b02cd87ef8eaa..4737e0b6520c3 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java @@ -2,6 +2,7 @@ import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.StoredProcedure; import com.azure.data.cosmos.internal.Strings; diff --git a/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java b/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java index a1fcc1e996992..d5279ed904f76 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.MediaReadMode; + import java.net.InetSocketAddress; import java.util.Collections; import java.util.List; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java b/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java index 2d0aa6184d5f9..2d20054c4faaf 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java @@ -54,7 +54,7 @@ public class CosmosClientException extends Exception { private final Map responseHeaders; private ClientSideRequestStatistics clientSideRequestStatistics; - private Error error; + private CosmosError cosmosError; long lsn; String partitionKeyRangeId; @@ -85,8 +85,8 @@ public CosmosClientException(int statusCode) { */ public CosmosClientException(int statusCode, String errorMessage) { this(statusCode, errorMessage, null, null); - this.error = new Error(); - error.set(Constants.Properties.MESSAGE, errorMessage); + this.cosmosError = new CosmosError(); + cosmosError.set(Constants.Properties.MESSAGE, errorMessage); } /** @@ -103,11 +103,11 @@ public CosmosClientException(int statusCode, Exception innerException) { * Creates a new instance of the CosmosClientException class. * * @param statusCode the http status code of the response. - * @param errorResource the error resource object. + * @param cosmosErrorResource the error resource object. * @param responseHeaders the response headers. */ - public CosmosClientException(int statusCode, Error errorResource, Map responseHeaders) { - this(/* resourceAddress */ null, statusCode, errorResource, responseHeaders); + public CosmosClientException(int statusCode, CosmosError cosmosErrorResource, Map responseHeaders) { + this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } /** @@ -115,14 +115,14 @@ public CosmosClientException(int statusCode, Error errorResource, Map responseHeaders) { - this(statusCode, errorResource == null ? null : errorResource.getMessage(), responseHeaders, null); + public CosmosClientException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map responseHeaders) { + this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; - this.error = errorResource; + this.cosmosError = cosmosErrorResource; } /** @@ -195,8 +195,8 @@ public int subStatusCode() { * * @return the error. */ - public Error error() { - return this.error; + public CosmosError error() { + return this.cosmosError; } /** @@ -262,17 +262,17 @@ public CosmosClientException clientSideRequestStatistics(ClientSideRequestStatis @Override public String toString() { - return getClass().getSimpleName() + "{" + "error=" + error + ", resourceAddress='" + resourceAddress + '\'' + return getClass().getSimpleName() + "{" + "error=" + cosmosError + ", resourceAddress='" + resourceAddress + '\'' + ", statusCode=" + statusCode + ", message=" + getMessage() + ", causeInfo=" + causeInfo() + ", responseHeaders=" + responseHeaders + ", requestHeaders=" + requestHeaders + '}'; } String innerErrorMessage() { String innerErrorMessage = super.getMessage(); - if (error != null) { - innerErrorMessage = error.getMessage(); + if (cosmosError != null) { + innerErrorMessage = cosmosError.getMessage(); if (innerErrorMessage == null) { - innerErrorMessage = String.valueOf(error.get("Errors")); + innerErrorMessage = String.valueOf(cosmosError.get("Errors")); } } return innerErrorMessage; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java index 3f31a96b8755b..885885680571e 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.ResourceResponse; import java.util.ArrayList; import java.util.List; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java index 5b0f7f2145e37..df5592b1a459a 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java @@ -22,6 +22,8 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.RequestOptions; + /** * Encapsulates options that can be specified for a request issued to cosmos container. */ diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java b/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java index 00600ed0670de..e6043e96d604a 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java @@ -22,6 +22,8 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.ResourceResponse; + import java.util.List; import java.util.stream.Collectors; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java index d1586f31e21ac..e87fb7e685809 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java @@ -22,6 +22,8 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.RequestOptions; + /** * Encapsulates options that can be specified for a request issued to cosmos database. */ diff --git a/commons/src/main/java/com/azure/data/cosmos/Error.java b/commons/src/main/java/com/azure/data/cosmos/CosmosError.java similarity index 93% rename from commons/src/main/java/com/azure/data/cosmos/Error.java rename to commons/src/main/java/com/azure/data/cosmos/CosmosError.java index 76610706b9915..15f0351df0912 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Error.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosError.java @@ -29,11 +29,11 @@ /** * Encapsulates error related details in the Azure Cosmos DB database service. */ -public class Error extends Resource { +public class CosmosError extends Resource { /** * Initialize a new instance of the Error object. */ - public Error() { + public CosmosError() { super(); } @@ -42,7 +42,7 @@ public Error() { * * @param objectNode the {@link ObjectNode} that represents the error. */ - Error(ObjectNode objectNode) { + CosmosError(ObjectNode objectNode) { super(objectNode); } @@ -51,7 +51,7 @@ public Error() { * * @param jsonString the jsonString that represents the error. */ - public Error(String jsonString) { + CosmosError(String jsonString) { super(jsonString); } @@ -61,7 +61,7 @@ public Error(String jsonString) { * @param errorCode the error code. * @param message the error message. */ - public Error(String errorCode, String message) { + public CosmosError(String errorCode, String message) { this(errorCode, message, null); } @@ -75,7 +75,7 @@ public Error(String errorCode, String message) { * @param additionalErrorInfo * additional error info. */ - public Error(String errorCode, String message, String additionalErrorInfo) { + public CosmosError(String errorCode, String message, String additionalErrorInfo) { super(); this.setCode(errorCode); this.setMessage(message); diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java index e633a6200bba2..f844c1808bc96 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java @@ -22,6 +22,9 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.RequestOptions; + import java.util.List; /** diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java index df280140e774b..7a12fa4374f2e 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java @@ -22,6 +22,8 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.RequestOptions; + /** * Encapsulates options that can be specified for a request */ diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosResponse.java b/commons/src/main/java/com/azure/data/cosmos/CosmosResponse.java index 4ba731c3abe7f..b34b756da4f5f 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosResponse.java @@ -22,6 +22,9 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.StoredProcedureResponse; + import java.time.Duration; import java.util.Map; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java index 28547fbc392e4..609216373e4fd 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.StoredProcedure; import java.util.List; import java.util.stream.Collectors; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java index b8a29b4a60097..1f1c618c634a5 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java @@ -22,6 +22,9 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.RequestOptions; + /** * Encapsulates options that can be specified for a request issued to cosmos stored procedure. */ diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java b/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java index 51c4580e1f880..a0d8fa4cbd540 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.Trigger; import org.apache.commons.lang3.StringUtils; import java.util.List; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java b/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java index 1e9c5f49f462f..9296a0b59f007 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.UserDefinedFunction; import java.util.List; import java.util.stream.Collectors; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java b/commons/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java index 2dd56aadb690f..fbd14bf1f37db 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java @@ -1,6 +1,8 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.User; import java.util.List; import java.util.stream.Collectors; diff --git a/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java b/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java index 7d89e56a4a77e..74fc5d89f8b45 100644 --- a/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java +++ b/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.ReplicationPolicy; import com.azure.data.cosmos.internal.Utils; import com.fasterxml.jackson.core.type.TypeReference; import org.apache.commons.lang3.ObjectUtils; diff --git a/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java b/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java index 63d9f3ac59d8f..dbcd58e15dc88 100644 --- a/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java +++ b/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.PartitionKey; + import java.util.Map; /** diff --git a/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java b/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java index ecbb7ca536314..fbb08ab6d238b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java @@ -25,6 +25,8 @@ import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.QueryMetrics; +import com.azure.data.cosmos.internal.QueryMetricsConstants; import org.apache.commons.lang3.StringUtils; import java.util.HashMap; diff --git a/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java b/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java index 863ce0b5d13fd..588d7297b1f9b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java @@ -29,7 +29,7 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; +import java.util.List; /** * Represents the indexing policy configuration for a collection in the Azure Cosmos DB database service. @@ -38,10 +38,10 @@ public final class IndexingPolicy extends JsonSerializable { private static final String DEFAULT_PATH = "/*"; - private Collection includedPaths; - private Collection excludedPaths; - private Collection> compositeIndexes; - private Collection spatialIndexes; + private List includedPaths; + private List excludedPaths; + private List> compositeIndexes; + private List spatialIndexes; /** * Constructor. @@ -95,7 +95,7 @@ public IndexingPolicy(Index[] defaultIndexOverrides) { * * @param jsonString the json string that represents the indexing policy. */ - public IndexingPolicy(String jsonString) { + IndexingPolicy(String jsonString) { super(jsonString); } @@ -156,9 +156,9 @@ public IndexingPolicy indexingMode(IndexingMode indexingMode) { * * @return the included paths. */ - public Collection includedPaths() { + public List includedPaths() { if (this.includedPaths == null) { - this.includedPaths = super.getCollection(Constants.Properties.INCLUDED_PATHS, IncludedPath.class); + this.includedPaths = super.getList(Constants.Properties.INCLUDED_PATHS, IncludedPath.class); if (this.includedPaths == null) { this.includedPaths = new ArrayList(); @@ -168,7 +168,7 @@ public Collection includedPaths() { return this.includedPaths; } - public void setIncludedPaths(Collection includedPaths) { + public void setIncludedPaths(List includedPaths) { this.includedPaths = includedPaths; } @@ -177,9 +177,9 @@ public void setIncludedPaths(Collection includedPaths) { * * @return the excluded paths. */ - public Collection excludedPaths() { + public List excludedPaths() { if (this.excludedPaths == null) { - this.excludedPaths = super.getCollection(Constants.Properties.EXCLUDED_PATHS, ExcludedPath.class); + this.excludedPaths = super.getList(Constants.Properties.EXCLUDED_PATHS, ExcludedPath.class); if (this.excludedPaths == null) { this.excludedPaths = new ArrayList(); @@ -189,7 +189,7 @@ public Collection excludedPaths() { return this.excludedPaths; } - public IndexingPolicy excludedPaths(Collection excludedPaths) { + public IndexingPolicy excludedPaths(List excludedPaths) { this.excludedPaths = excludedPaths; return this; } @@ -199,9 +199,9 @@ public IndexingPolicy excludedPaths(Collection excludedPaths) { * * @return the composite indexes. */ - public Collection> compositeIndexes() { + public List> compositeIndexes() { if (this.compositeIndexes == null) { - this.compositeIndexes = new ArrayList>(); + this.compositeIndexes = new ArrayList<>(); ArrayNode compositeIndexes = (ArrayNode) super.get(Constants.Properties.COMPOSITE_INDEXES); for (int i = 0; i < compositeIndexes.size(); i ++) { ArrayNode compositeIndex = (ArrayNode) compositeIndexes.get(i); @@ -223,7 +223,7 @@ public Collection> compositeIndexes() { * @param compositeIndexes the composite indexes. * @return the Indexing Policy. */ - public IndexingPolicy compositeIndexes(Collection> compositeIndexes) { + public IndexingPolicy compositeIndexes(List> compositeIndexes) { this.compositeIndexes = compositeIndexes; super.set(Constants.Properties.COMPOSITE_INDEXES, this.compositeIndexes); return this; @@ -234,9 +234,9 @@ public IndexingPolicy compositeIndexes(Collection> comp * * @return the spatial indexes. */ - public Collection spatialIndexes() { + public List spatialIndexes() { if (this.spatialIndexes == null) { - this.spatialIndexes = super.getCollection(Constants.Properties.SPATIAL_INDEXES, SpatialSpec.class); + this.spatialIndexes = super.getList(Constants.Properties.SPATIAL_INDEXES, SpatialSpec.class); if (this.spatialIndexes == null) { this.spatialIndexes = new ArrayList(); @@ -252,7 +252,7 @@ public Collection spatialIndexes() { * @param spatialIndexes the spatial indexes. * @return the Indexing Policy. */ - public IndexingPolicy spatialIndexes(Collection spatialIndexes) { + public IndexingPolicy spatialIndexes(List spatialIndexes) { this.spatialIndexes = spatialIndexes; super.set(Constants.Properties.SPATIAL_INDEXES, this.spatialIndexes); return this; diff --git a/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java b/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java index c33c169e5cd14..9432602324e6b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java +++ b/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java @@ -34,6 +34,7 @@ import org.slf4j.LoggerFactory; import java.io.IOException; +import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; @@ -103,7 +104,7 @@ private static void checkForValidPOJO(Class c) { } } - Logger getLogger() { + public Logger getLogger() { return logger; } @@ -309,7 +310,11 @@ public T getObject(String propertyName, Class c, boolean ... convertFromC } } else if (JsonSerializable.class.isAssignableFrom(c)) { try { - return c.getConstructor(String.class).newInstance(toJson(jsonObj)); + Constructor constructor = c.getDeclaredConstructor(String.class); + if(Modifier.isPrivate(constructor.getModifiers())) { + constructor.setAccessible(true); + } + return constructor.newInstance(toJson(jsonObj)); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException("Failed to instantiate class object.", e); @@ -376,7 +381,11 @@ public List getList(String propertyName, Class c, boolean ... convertF } else if (isJsonSerializable) { // JsonSerializable try { - result.add(c.getConstructor(String.class).newInstance(toJson(n))); + Constructor constructor = c.getDeclaredConstructor(String.class); + if(Modifier.isPrivate(constructor.getModifiers())) { + constructor.setAccessible(true); + } + result.add(constructor.newInstance(toJson(n))); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new IllegalStateException("Failed to instantiate class object.", e); diff --git a/commons/src/main/java/com/azure/data/cosmos/MediaOptions.java b/commons/src/main/java/com/azure/data/cosmos/MediaOptions.java deleted file mode 100644 index 1a627fd2c7fb3..0000000000000 --- a/commons/src/main/java/com/azure/data/cosmos/MediaOptions.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.azure.data.cosmos; - -/** - * Options used with attachment content (aka media) creation in the Azure Cosmos DB database service. - */ -public final class MediaOptions { - private String slug; - private String contentType; - - /** - * Gets the HTTP Slug header value. - * - * @return the slug. - */ - public String getSlug() { - return this.slug; - } - - /** - * Sets the HTTP Slug header value. - * - * @param slug the slug. - */ - public void setSlug(String slug) { - this.slug = slug; - } - - /** - * Gets the HTTP ContentType header value. - * - * @return the content type. - */ - public String getContentType() { - return this.contentType; - } - - /** - * Sets the HTTP ContentType header value. - * - * @param contentType the content type. - */ - public void setContentType(String contentType) { - this.contentType = contentType; - } -} diff --git a/commons/src/main/java/com/azure/data/cosmos/MediaResponse.java b/commons/src/main/java/com/azure/data/cosmos/MediaResponse.java deleted file mode 100644 index fa9202c4ddc31..0000000000000 --- a/commons/src/main/java/com/azure/data/cosmos/MediaResponse.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.azure.data.cosmos; - -import com.azure.data.cosmos.internal.RxDocumentServiceResponse; - -import java.io.BufferedInputStream; -import java.io.InputStream; -import java.util.Map; - -/** - * Response associated with retrieving attachment content in the Azure Cosmos DB database service. - */ -public final class MediaResponse { - private InputStream media = null; - private Map responseHeaders = null; - - MediaResponse(RxDocumentServiceResponse response, boolean willBuffer) { - this.media = response.getContentStream(); - if (willBuffer) { - this.media = new BufferedInputStream(this.media); - } - - this.responseHeaders = response.getResponseHeaders(); - } - - /** - * Gets the attachment content stream. - * - * @return the attachment content stream. - */ - public InputStream getMedia() { - return this.media; - } - - /** - * Gets the headers associated with the response. - * - * @return the response headers. - */ - public Map getResponseHeaders() { - return this.responseHeaders; - } -} diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java index 90adb0df636d3..b35ae9eb6562f 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java +++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java @@ -54,7 +54,7 @@ public PartitionKeyDefinition() { * * @param jsonString the JSON string that represents the partition key definition. */ - public PartitionKeyDefinition(String jsonString) { + PartitionKeyDefinition(String jsonString) { super(jsonString); } diff --git a/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java b/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java index ca295e247ec04..a27b4ca0fa583 100644 --- a/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java +++ b/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java @@ -73,7 +73,7 @@ public RangeIndex(DataType dataType, int precision) { * * @param jsonString the json string that represents the index. */ - public RangeIndex(String jsonString) { + RangeIndex(String jsonString) { super(jsonString, IndexKind.RANGE); if (this.dataType() == null) { throw new IllegalArgumentException("The jsonString doesn't contain a valid 'dataType'."); diff --git a/commons/src/main/java/com/azure/data/cosmos/Resource.java b/commons/src/main/java/com/azure/data/cosmos/Resource.java index 2ae4fe9d600f2..99ad792972083 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Resource.java +++ b/commons/src/main/java/com/azure/data/cosmos/Resource.java @@ -117,7 +117,7 @@ public String id() { * @param id the name of the resource. * @return the resource. */ - Resource id(String id) { + public Resource id(String id) { super.set(Constants.Properties.ID, id); return this; } diff --git a/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java b/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java index 31a37369c8b4a..77bb0fa3b6b6a 100644 --- a/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java +++ b/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java @@ -29,7 +29,7 @@ /** * Represents a spatial index in the Azure Cosmos DB database service. */ -public final class SpatialIndex extends Index { +final class SpatialIndex extends Index { /** * Initializes a new instance of the SpatialIndex class. @@ -45,7 +45,7 @@ public final class SpatialIndex extends Index { * * @param dataType specifies the target data type for the index path specification. */ - public SpatialIndex(DataType dataType) { + SpatialIndex(DataType dataType) { super(IndexKind.SPATIAL); this.dataType(dataType); } @@ -55,7 +55,7 @@ public SpatialIndex(DataType dataType) { * * @param jsonString the json string that represents the index. */ - public SpatialIndex(String jsonString) { + SpatialIndex(String jsonString) { super(jsonString, IndexKind.SPATIAL); if (this.dataType() == null) { throw new IllegalArgumentException("The jsonString doesn't contain a valid 'dataType'."); diff --git a/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java b/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java index a3a7be4699673..6c20175b6511b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java +++ b/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java @@ -27,10 +27,11 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.List; public class SpatialSpec extends JsonSerializable { - private Collection spatialTypes; + private List spatialTypes; /** * Constructor. @@ -44,7 +45,7 @@ public SpatialSpec() { * * @param jsonString the json string that represents the included path. */ - public SpatialSpec(String jsonString) { + SpatialSpec(String jsonString) { super(jsonString); } @@ -74,9 +75,9 @@ public SpatialSpec path(String path) { * * @return the collection of spatial types. */ - public Collection spatialTypes() { + public List spatialTypes() { if (this.spatialTypes == null) { - this.spatialTypes = super.getCollection(Constants.Properties.TYPES, SpatialType.class, true); + this.spatialTypes = super.getList(Constants.Properties.TYPES, SpatialType.class, true); if (this.spatialTypes == null) { this.spatialTypes = new ArrayList(); @@ -92,7 +93,7 @@ public Collection spatialTypes() { * @param spatialTypes the collection of spatial types. * @return the SpatialSpec. */ - public SpatialSpec spatialTypes(Collection spatialTypes) { + public SpatialSpec spatialTypes(List spatialTypes) { this.spatialTypes = spatialTypes; Collection spatialTypeNames = new ArrayList(); for (SpatialType spatialType : this.spatialTypes) { diff --git a/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java b/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java index d1159cc315957..1b33988b52dd5 100644 --- a/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java +++ b/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java @@ -26,6 +26,7 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.List; /** * Represents a unique key on that enforces uniqueness constraint on documents in the collection in the Azure Cosmos DB service. @@ -36,13 +37,13 @@ * @see UniqueKeyPolicy */ public class UniqueKey extends JsonSerializable { - private Collection paths; + private List paths; public UniqueKey() { super(); } - public UniqueKey(String jsonString) { + UniqueKey(String jsonString) { super(jsonString); } @@ -56,7 +57,7 @@ public UniqueKey(String jsonString) { */ public Collection paths() { if (this.paths == null) { - this.paths = super.getCollection(Constants.Properties.PATHS, String.class); + this.paths = super.getList(Constants.Properties.PATHS, String.class); if (this.paths == null) { this.paths = new ArrayList(); @@ -76,7 +77,7 @@ public Collection paths() { * @param paths the unique paths. * @return the Unique Key. */ - public UniqueKey paths(Collection paths) { + public UniqueKey paths(List paths) { this.paths = paths; return this; } diff --git a/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java b/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java index 20a160be66211..4435493c6b565 100644 --- a/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java @@ -26,13 +26,14 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.List; /** * Represents the unique key policy configuration for specifying uniqueness constraints on documents in the * collection in the Azure Cosmos DB service. */ public class UniqueKeyPolicy extends JsonSerializable { - private Collection uniqueKeys; + private List uniqueKeys; public UniqueKeyPolicy() { super(); @@ -43,7 +44,7 @@ public UniqueKeyPolicy() { * * @param jsonString the json string that represents the Unique Key policy. */ - public UniqueKeyPolicy(String jsonString) { + UniqueKeyPolicy(String jsonString) { super(jsonString); } @@ -55,7 +56,7 @@ public UniqueKeyPolicy(String jsonString) { */ public Collection uniqueKeys() { if (this.uniqueKeys == null) { - this.uniqueKeys = super.getCollection(Constants.Properties.UNIQUE_KEYS, UniqueKey.class); + this.uniqueKeys = super.getList(Constants.Properties.UNIQUE_KEYS, UniqueKey.class); if (this.uniqueKeys == null) { this.uniqueKeys = new ArrayList<>(); } @@ -63,7 +64,7 @@ public Collection uniqueKeys() { return this.uniqueKeys; } - public UniqueKeyPolicy uniqueKeys(Collection uniqueKeys) { + public UniqueKeyPolicy uniqueKeys(List uniqueKeys) { if (uniqueKeys == null) { throw new IllegalArgumentException("uniqueKeys cannot be null."); } diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java index 69bc12a787e36..0e6da921795f9 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.Strings; @@ -44,8 +44,8 @@ public GoneException() { this(RMResources.Gone, null); } - public GoneException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.GONE, error, responseHeaders); + public GoneException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.GONE, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } @@ -87,8 +87,8 @@ public GoneException(String message, super(message, innerException, headers, HttpConstants.StatusCodes.GONE, requestUriString); } - public GoneException(Error error, Map headers) { - super(HttpConstants.StatusCodes.GONE, error, headers); + public GoneException(CosmosError cosmosError, Map headers) { + super(HttpConstants.StatusCodes.GONE, cosmosError, headers); } private static String message(String localIP, String baseMessage) { diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java index f29f9dbf48ca2..d20210d473b37 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.Strings; @@ -40,8 +40,8 @@ public RequestTimeoutException() { this(RMResources.RequestTimeout, null); } - public RequestTimeoutException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.REQUEST_TIMEOUT, error, responseHeaders); + public RequestTimeoutException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.REQUEST_TIMEOUT, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java b/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java index 036289bfa37f1..cbba276c7822e 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -47,8 +47,8 @@ public BadRequestException() { this(RMResources.BadRequest); } - public BadRequestException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.BADREQUEST, error, responseHeaders); + public BadRequestException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.BADREQUEST, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java b/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java index 09a5bf248839c..8e368d7b9a2b7 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java @@ -26,7 +26,6 @@ import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.directconnectivity.StoreResponse; import com.azure.data.cosmos.directconnectivity.StoreResult; import com.azure.data.cosmos.directconnectivity.TimeoutHelper; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java b/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java index a8bac139adb8b..70d7d7b1a7736 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -46,8 +46,8 @@ public InternalServerErrorException() { this(RMResources.InternalServerError); } - public InternalServerErrorException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, error, responseHeaders); + public InternalServerErrorException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/commons/src/main/java/com/azure/data/cosmos/MediaReadMode.java b/commons/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/MediaReadMode.java rename to commons/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java index ab6aa698e5f5e..0c1c960553bd5 100644 --- a/commons/src/main/java/com/azure/data/cosmos/MediaReadMode.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; /** * Represents the mode for use with downloading attachment content (aka media) from the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/azure/data/cosmos/Offer.java b/commons/src/main/java/com/azure/data/cosmos/internal/Offer.java similarity index 86% rename from commons/src/main/java/com/azure/data/cosmos/Offer.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Offer.java index 5ec5a7ee39ba0..22c787aeeaa67 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Offer.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Offer.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; -import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.Resource; import com.fasterxml.jackson.databind.node.ObjectNode; /** @@ -70,7 +70,7 @@ public String getResourceLink() { * @param resourceLink the resource link. */ void setResourceLink(String resourceLink) { - super.set(Constants.Properties.RESOURCE_LINK, resourceLink); + BridgeInternal.setProperty(this, Constants.Properties.RESOURCE_LINK, resourceLink); } /** @@ -88,7 +88,7 @@ public String getOfferResourceId() { * @param resourceId the resource id. */ void setOfferResourceId(String resourceId) { - super.set(Constants.Properties.OFFER_RESOURCE_ID, resourceId); + BridgeInternal.setProperty(this, Constants.Properties.OFFER_RESOURCE_ID, resourceId); } /** @@ -106,7 +106,7 @@ public String getOfferType() { * @param offerType the offer type. */ public void setOfferType(String offerType) { - super.set(Constants.Properties.OFFER_TYPE, offerType); + BridgeInternal.setProperty(this, Constants.Properties.OFFER_TYPE, offerType); } /** @@ -124,7 +124,7 @@ public String getOfferVersion() { * @param offerVersion the version of the offer. */ public void setOfferVersion(String offerVersion) { - super.set(Constants.Properties.OFFER_VERSION, offerVersion); + BridgeInternal.setProperty(this, Constants.Properties.OFFER_VERSION, offerVersion); } /** @@ -146,10 +146,10 @@ public void setThroughput(int throughput) { } private ObjectNode getContent() { - return super.getObject(Constants.Properties.OFFER_CONTENT); + return BridgeInternal.getObject(this, Constants.Properties.OFFER_CONTENT); } private void setContent(ObjectNode offerContent) { - super.set(Constants.Properties.OFFER_CONTENT, offerContent); + BridgeInternal.setProperty(this, Constants.Properties.OFFER_CONTENT, offerContent); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java b/commons/src/main/java/com/azure/data/cosmos/internal/PartitionKey.java similarity index 92% rename from commons/src/main/java/com/azure/data/cosmos/PartitionKey.java rename to commons/src/main/java/com/azure/data/cosmos/internal/PartitionKey.java index df3cf998c9791..9a42201878919 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/PartitionKey.java @@ -21,9 +21,8 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; /** @@ -34,7 +33,7 @@ public class PartitionKey { private PartitionKeyInternal internalPartitionKey; - PartitionKey(PartitionKeyInternal partitionKeyInternal) { + public PartitionKey(PartitionKeyInternal partitionKeyInternal) { this.internalPartitionKey = partitionKeyInternal; } @@ -49,13 +48,13 @@ public PartitionKey(final Object key) { } /** - * CREATE a new instance of the PartitionKey object from a serialized JSON + * Create a new instance of the PartitionKey object from a serialized JSON * partition key. * * @param jsonString the JSON string representation of this PartitionKey object. * @return the PartitionKey instance. */ - public static PartitionKey FromJsonString(String jsonString) { + public static PartitionKey fromJsonString(String jsonString) { return new PartitionKey(PartitionKeyInternal.fromJsonString(jsonString)); } diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java b/commons/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java similarity index 91% rename from commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java rename to commons/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java index 7eba8f627f99f..4404f44aff93b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRange.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java @@ -21,9 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.routing.Range; import java.util.List; @@ -84,7 +85,7 @@ public String getMinInclusive() { } public void setMinInclusive(String minInclusive) { - super.set("minInclusive", minInclusive); + BridgeInternal.setProperty(this, "minInclusive", minInclusive); } public String getMaxExclusive() { @@ -92,7 +93,7 @@ public String getMaxExclusive() { } public void setMaxExclusive(String maxExclusive) { - super.set("maxExclusive", maxExclusive); + BridgeInternal.setProperty(this, "maxExclusive", maxExclusive); } public Range toRange() { @@ -121,8 +122,8 @@ public int hashCode() { return hash; } - void setParents(List parents) { - this.set(Constants.Properties.PARENTS, parents); + public void setParents(List parents) { + BridgeInternal.setProperty(this, Constants.Properties.PARENTS, parents); } /** diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java b/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java index c8d2d8627356d..2c0ca8ee3b100 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java @@ -28,13 +28,7 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.Offer; -import com.azure.data.cosmos.Permission; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.StoredProcedure; -import com.azure.data.cosmos.Trigger; -import com.azure.data.cosmos.User; -import com.azure.data.cosmos.UserDefinedFunction; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.text.StringEscapeUtils; diff --git a/commons/src/main/java/com/azure/data/cosmos/Permission.java b/commons/src/main/java/com/azure/data/cosmos/internal/Permission.java similarity index 87% rename from commons/src/main/java/com/azure/data/cosmos/Permission.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Permission.java index 27125e7e34024..8ba97f56453b2 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Permission.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Permission.java @@ -21,9 +21,11 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.PermissionMode; +import com.azure.data.cosmos.Resource; import com.fasterxml.jackson.databind.node.ArrayNode; import org.apache.commons.lang3.StringUtils; @@ -72,7 +74,7 @@ public String getResourceLink() { * @param resourceLink the resource link. */ public void setResourceLink(String resourceLink) { - super.set(Constants.Properties.RESOURCE_LINK, resourceLink); + BridgeInternal.setProperty(this, Constants.Properties.RESOURCE_LINK, resourceLink); } /** @@ -91,7 +93,7 @@ public PermissionMode getPermissionMode() { * @param permissionMode the permission mode. */ public void setPermissionMode(PermissionMode permissionMode) { - this.set(Constants.Properties.PERMISSION_MODE, + BridgeInternal.setProperty(this, Constants.Properties.PERMISSION_MODE, permissionMode.toString().toLowerCase()); } @@ -114,7 +116,7 @@ public PartitionKey getResourcePartitionKey() { Object value = super.get(Constants.Properties.RESOURCE_PARTITION_KEY); if (value != null) { ArrayNode arrayValue = (ArrayNode) value; - key = new PartitionKey(getValue(arrayValue.get(0))); + key = new PartitionKey(BridgeInternal.getValue(arrayValue.get(0))); } return key; @@ -126,6 +128,6 @@ public PartitionKey getResourcePartitionKey() { * @param partitionkey the partition key. */ public void setResourcePartitionKey(PartitionKey partitionkey) { - super.set(Constants.Properties.RESOURCE_PARTITION_KEY, partitionkey.getInternalPartitionKey().toJson()); + BridgeInternal.setProperty(this, Constants.Properties.RESOURCE_PARTITION_KEY, partitionkey.getInternalPartitionKey().toJson()); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/QueryMetrics.java b/commons/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java similarity index 96% rename from commons/src/main/java/com/azure/data/cosmos/QueryMetrics.java rename to commons/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java index c565ea0af452b..da298ab34d9f4 100644 --- a/commons/src/main/java/com/azure/data/cosmos/QueryMetrics.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; import com.azure.data.cosmos.internal.query.metrics.FetchExecutionRange; @@ -186,7 +186,7 @@ public Duration getDocumentWriteTime() { /** * @return the clientSideMetrics */ - ClientSideMetrics getClientSideMetrics() { + public ClientSideMetrics getClientSideMetrics() { return clientSideMetrics; } @@ -219,7 +219,7 @@ private String toTextString(int indentLevel) { return stringBuilder.toString(); } - static QueryMetrics createFromCollection(Collection queryMetricsCollection) { + public static QueryMetrics createFromCollection(Collection queryMetricsCollection) { long retrievedDocumentCount = 0; long retrievedDocumentSize = 0; long outputDocumentCount = 0; @@ -268,14 +268,14 @@ private static double getOrDefault(HashMap metrics, String key) return doubleReference == null ? 0 : doubleReference; } - static QueryMetrics createFromDelimitedString(String delimitedString) { + public static QueryMetrics createFromDelimitedString(String delimitedString) { HashMap metrics = QueryMetricsUtils.parseDelimitedString(delimitedString); return QueryMetrics.createFromDelimitedStringAndClientSideMetrics(delimitedString, new ClientSideMetrics(0, 0, new ArrayList(), new ArrayList>()), ""); } - static QueryMetrics createFromDelimitedStringAndClientSideMetrics(String delimitedString, ClientSideMetrics clientSideMetrics, + public static QueryMetrics createFromDelimitedStringAndClientSideMetrics(String delimitedString, ClientSideMetrics clientSideMetrics, String activityId) { HashMap metrics = QueryMetricsUtils.parseDelimitedString(delimitedString); double indexHitRatio; diff --git a/commons/src/main/java/com/azure/data/cosmos/QueryMetricsConstants.java b/commons/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java similarity index 99% rename from commons/src/main/java/com/azure/data/cosmos/QueryMetricsConstants.java rename to commons/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java index 59ea51c28d5d8..2fc5ebf913211 100644 --- a/commons/src/main/java/com/azure/data/cosmos/QueryMetricsConstants.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; public final class QueryMetricsConstants { // QueryMetrics diff --git a/commons/src/main/java/com/azure/data/cosmos/QueryMetricsUtils.java b/commons/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java similarity index 99% rename from commons/src/main/java/com/azure/data/cosmos/QueryMetricsUtils.java rename to commons/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java index b913289df3e19..dc57f3d0ce223 100644 --- a/commons/src/main/java/com/azure/data/cosmos/QueryMetricsUtils.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; import org.apache.commons.lang3.StringUtils; @@ -29,7 +29,7 @@ import java.util.List; import java.util.Locale; -class QueryMetricsUtils { +public class QueryMetricsUtils { static final String Indent = StringUtils.SPACE; private static final int NANOS_TO_MILLIS = 1000000; private static final String BytesUnitString = "bytes"; diff --git a/commons/src/main/java/com/azure/data/cosmos/QueryPreparationTimes.java b/commons/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java similarity index 99% rename from commons/src/main/java/com/azure/data/cosmos/QueryPreparationTimes.java rename to commons/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java index e3e2b2cf94875..e50c3fbd91fdc 100644 --- a/commons/src/main/java/com/azure/data/cosmos/QueryPreparationTimes.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; import java.time.Duration; import java.util.Collection; diff --git a/commons/src/main/java/com/azure/data/cosmos/ReplicationPolicy.java b/commons/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java similarity index 89% rename from commons/src/main/java/com/azure/data/cosmos/ReplicationPolicy.java rename to commons/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java index 30767a13db259..0036edba15523 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ReplicationPolicy.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java @@ -21,9 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.JsonSerializable; /** * Encapsulates the replication policy in the Azure Cosmos DB database service. @@ -53,9 +54,9 @@ public int getMaxReplicaSetSize() { return maxReplicaSetSize; } - void setMaxReplicaSetSize(int value) { + public void setMaxReplicaSetSize(int value) { Integer maxReplicaSetSize = super.getInt(Constants.Properties.MAX_REPLICA_SET_SIZE); - super.set(Constants.Properties.MAX_REPLICA_SET_SIZE, value); + BridgeInternal.setProperty(this, Constants.Properties.MAX_REPLICA_SET_SIZE, value); } public int getMinReplicaSetSize() { diff --git a/commons/src/main/java/com/azure/data/cosmos/RequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/RequestOptions.java rename to commons/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java index 5515ea15a8aee..b3d7ae3e1eb79 100644 --- a/commons/src/main/java/com/azure/data/cosmos/RequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java @@ -21,7 +21,11 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.AccessCondition; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.IndexingDirective; import java.util.HashMap; import java.util.List; diff --git a/commons/src/main/java/com/azure/data/cosmos/ResourceResponse.java b/commons/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/ResourceResponse.java rename to commons/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java index ef354f0fa67b0..b0c66f5a90921 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ResourceResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java @@ -21,8 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; @@ -45,7 +47,7 @@ public final class ResourceResponse { private Map usageHeaders; private Map quotaHeaders; - ResourceResponse(RxDocumentServiceResponse response, Class cls) { + public ResourceResponse(RxDocumentServiceResponse response, Class cls) { this.response = response; this.usageHeaders = new HashMap(); this.quotaHeaders = new HashMap(); diff --git a/commons/src/main/java/com/azure/data/cosmos/RuntimeExecutionTimes.java b/commons/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java similarity index 99% rename from commons/src/main/java/com/azure/data/cosmos/RuntimeExecutionTimes.java rename to commons/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java index de7eb4754a384..3d5153cc53772 100644 --- a/commons/src/main/java/com/azure/data/cosmos/RuntimeExecutionTimes.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; import java.time.Duration; import java.util.Collection; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java index 975ab6b58c485..940d1b9e7d266 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java @@ -24,7 +24,6 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.FeedOptionsBase; -import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.directconnectivity.WFConstants; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java index 93fa1c5b3513a..1b64cdee62658 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java @@ -30,14 +30,7 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.Offer; -import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.Permission; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.StoredProcedure; -import com.azure.data.cosmos.Trigger; -import com.azure.data.cosmos.User; -import com.azure.data.cosmos.UserDefinedFunction; import com.azure.data.cosmos.directconnectivity.Address; import com.azure.data.cosmos.directconnectivity.StoreResponse; import com.fasterxml.jackson.core.JsonProcessingException; diff --git a/commons/src/main/java/com/azure/data/cosmos/StoredProcedure.java b/commons/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java similarity index 92% rename from commons/src/main/java/com/azure/data/cosmos/StoredProcedure.java rename to commons/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java index 52dd6324b476b..59e60d6594be4 100644 --- a/commons/src/main/java/com/azure/data/cosmos/StoredProcedure.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java @@ -21,9 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.Resource; /** * Represents a stored procedure in the Azure Cosmos DB database service. @@ -75,7 +76,7 @@ public String getBody() { * @param body the body of the stored procedure. */ public void setBody(String body) { - super.set(Constants.Properties.BODY, body); + BridgeInternal.setProperty(this, Constants.Properties.BODY, body); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/StoredProcedureResponse.java b/commons/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java similarity index 95% rename from commons/src/main/java/com/azure/data/cosmos/StoredProcedureResponse.java rename to commons/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java index 903aa1d3f3597..6bb7c858bd2c8 100644 --- a/commons/src/main/java/com/azure/data/cosmos/StoredProcedureResponse.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java @@ -21,10 +21,11 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.RxDocumentServiceResponse; +import com.azure.data.cosmos.Attachment; +import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,7 +44,7 @@ public final class StoredProcedureResponse { * * @param response the document service response. */ - StoredProcedureResponse(RxDocumentServiceResponse response) { + public StoredProcedureResponse(RxDocumentServiceResponse response) { this.response = response; } diff --git a/commons/src/main/java/com/azure/data/cosmos/Trigger.java b/commons/src/main/java/com/azure/data/cosmos/internal/Trigger.java similarity index 88% rename from commons/src/main/java/com/azure/data/cosmos/Trigger.java rename to commons/src/main/java/com/azure/data/cosmos/internal/Trigger.java index 4cc3ebe42433d..7916cffa1c8ab 100644 --- a/commons/src/main/java/com/azure/data/cosmos/Trigger.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Trigger.java @@ -21,9 +21,12 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.TriggerOperation; +import com.azure.data.cosmos.TriggerType; import org.apache.commons.lang3.StringUtils; /** @@ -65,7 +68,7 @@ public String getBody() { * @param body the body of the trigger. */ public void setBody(String body) { - super.set(Constants.Properties.BODY, body); + BridgeInternal.setProperty(this, Constants.Properties.BODY, body); } /** @@ -91,7 +94,7 @@ public TriggerType getTriggerType() { * @param triggerType the trigger type. */ public void setTriggerType(TriggerType triggerType) { - super.set(Constants.Properties.TRIGGER_TYPE, triggerType.toString()); + BridgeInternal.setProperty(this, Constants.Properties.TRIGGER_TYPE, triggerType.toString()); } /** @@ -117,6 +120,6 @@ public TriggerOperation getTriggerOperation() { * @param triggerOperation the trigger operation. */ public void setTriggerOperation(TriggerOperation triggerOperation) { - super.set(Constants.Properties.TRIGGER_OPERATION, triggerOperation.toString()); + BridgeInternal.setProperty(this, Constants.Properties.TRIGGER_OPERATION, triggerOperation.toString()); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/User.java b/commons/src/main/java/com/azure/data/cosmos/internal/User.java similarity index 96% rename from commons/src/main/java/com/azure/data/cosmos/User.java rename to commons/src/main/java/com/azure/data/cosmos/internal/User.java index 637cb5496af7c..3a5fc9974857a 100644 --- a/commons/src/main/java/com/azure/data/cosmos/User.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/User.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.Resource; /** * Represents a database user in the Azure Cosmos DB database service. diff --git a/commons/src/main/java/com/azure/data/cosmos/UserDefinedFunction.java b/commons/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java similarity index 91% rename from commons/src/main/java/com/azure/data/cosmos/UserDefinedFunction.java rename to commons/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java index 060c249d6c42d..30bd5c7f67089 100644 --- a/commons/src/main/java/com/azure/data/cosmos/UserDefinedFunction.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java @@ -21,9 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.Resource; /** * Represents a user defined function in the Azure Cosmos DB database service. @@ -64,7 +65,7 @@ public String getBody() { * @param body the body. */ public void setBody(String body) { - super.set(Constants.Properties.BODY, body); + BridgeInternal.setProperty(this, Constants.Properties.BODY, body); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java index 62d3b660affa9..d61094020e326 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java @@ -1,9 +1,9 @@ package com.azure.data.cosmos.internal.query.metrics; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.QueryMetrics; -import com.azure.data.cosmos.QueryPreparationTimes; -import com.azure.data.cosmos.RuntimeExecutionTimes; +import com.azure.data.cosmos.internal.QueryMetrics; +import com.azure.data.cosmos.internal.QueryPreparationTimes; +import com.azure.data.cosmos.internal.RuntimeExecutionTimes; import org.apache.commons.lang3.tuple.ImmutablePair; import java.time.Duration; diff --git a/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java b/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java index 055c0e8c8cf40..ded954ac18370 100644 --- a/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java @@ -55,14 +55,14 @@ public void headerNotNull3() { @Test(groups = { "unit" }) public void headerNotNull4() { - CosmosClientException dce = new CosmosClientException(0, (Error) null, (Map) null); + CosmosClientException dce = new CosmosClientException(0, (CosmosError) null, (Map) null); assertThat(dce.responseHeaders()).isNotNull(); assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull5() { - CosmosClientException dce = new CosmosClientException((String) null, 0, (Error) null, (Map) null); + CosmosClientException dce = new CosmosClientException((String) null, 0, (CosmosError) null, (Map) null); assertThat(dce.responseHeaders()).isNotNull(); assertThat(dce.responseHeaders()).isEmpty(); } diff --git a/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java b/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java index d2a84034f3066..1f26c981df43c 100644 --- a/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java +++ b/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java @@ -26,6 +26,9 @@ import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; +import java.util.ArrayList; +import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; public class DocumentCollectionTests { @@ -52,4 +55,22 @@ public void getPartitionKey_serializeAndDeserialize() { assertThat(parsedColl.getPartitionKey().paths()).isEqualTo(partitionKeyDefinition.paths()); assertThat(parsedColl.getPartitionKey().version()).isEqualTo(partitionKeyDefinition.version()); } + + @Test(groups = { "unit"}) + public void indexingPolicy_serializeAndDeserialize() { + SpatialSpec spatialSpec = new SpatialSpec(); + List spatialSpecList = new ArrayList<>(); + spatialSpecList.add(spatialSpec); + IndexingPolicy indexingPolicy = new IndexingPolicy(); + indexingPolicy.spatialIndexes(spatialSpecList); + DocumentCollection documentCollection = new DocumentCollection(); + documentCollection.setIndexingPolicy(indexingPolicy); + String json = documentCollection.toJson(); + + DocumentCollection documentCollectionPostSerialization = new DocumentCollection(json); + IndexingPolicy indexingPolicyPostSerialization = documentCollectionPostSerialization.getIndexingPolicy(); + assertThat(indexingPolicyPostSerialization).isNotNull(); + List spatialSpecListPostSerialization = indexingPolicyPostSerialization.spatialIndexes(); + assertThat(spatialSpecListPostSerialization).isNotNull(); + } } diff --git a/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java b/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java index 0c1fbaca22b49..55d9e51cacfa3 100644 --- a/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java @@ -22,6 +22,8 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.Permission; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java index 37f1efadeaeaa..6c6308a8a843d 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.BadRequestException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java index 8a1527565a304..ab1fc9484b8b3 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -43,8 +43,8 @@ public ConflictException() { this(RMResources.EntityAlreadyExists); } - public ConflictException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.CONFLICT, error, responseHeaders); + public ConflictException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.CONFLICT, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } @@ -65,8 +65,8 @@ public ConflictException(Exception innerException) { this(RMResources.EntityAlreadyExists, innerException, null, null); } - public ConflictException(Error error, Map headers) { - super(HttpConstants.StatusCodes.CONFLICT, error, headers); + public ConflictException(CosmosError cosmosError, Map headers) { + super(HttpConstants.StatusCodes.CONFLICT, cosmosError, headers); } public ConflictException(String message, diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java index 5e36b3e56f5c0..f81a2f7a47ae4 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -38,8 +38,8 @@ public ForbiddenException() { this(RMResources.Forbidden); } - public ForbiddenException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.FORBIDDEN, error, responseHeaders); + public ForbiddenException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.FORBIDDEN, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java index 830694a288d96..e379ba7d1bbd1 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.Exceptions; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java index 684361de5839e..87a7bdf766631 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.DatabaseAccount; -import com.azure.data.cosmos.ReplicationPolicy; +import com.azure.data.cosmos.internal.ReplicationPolicy; import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.GlobalEndpointManager; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java index 4222179dec2b2..80adf730058a3 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java @@ -23,8 +23,9 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import com.azure.data.cosmos.internal.http.HttpRequest; @@ -53,10 +54,10 @@ private static Mono createDocumentClientException(HttpRes Mono readStream = ResponseUtils.toString(httpResponse.body()); return readStream.map(body -> { - Error error = new Error(body); + CosmosError cosmosError = BridgeInternal.createCosmosError(body); // TODO: we should set resource address in the Document Client Exception - return new CosmosClientException(httpResponse.statusCode(), error, + return new CosmosClientException(httpResponse.statusCode(), cosmosError, httpResponse.headers().toMap()); }); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java index 55697eda865cc..5cb8868a372ec 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -42,8 +42,8 @@ public LockedException() { this(RMResources.Locked); } - public LockedException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.LOCKED, error, responseHeaders); + public LockedException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.LOCKED, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java index 308b0728b5ccb..522506c671d1b 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -38,8 +38,8 @@ public MethodNotAllowedException() { this(RMResources.MethodNotAllowed); } - public MethodNotAllowedException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.METHOD_NOT_ALLOWED, error, responseHeaders); + public MethodNotAllowedException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.METHOD_NOT_ALLOWED, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java index faedc7a43ce15..0d9e1ae106f1a 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -45,8 +45,8 @@ public PartitionKeyRangeGoneException() { this(RMResources.Gone); } - public PartitionKeyRangeGoneException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.GONE, error, responseHeaders); + public PartitionKeyRangeGoneException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.GONE, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); this.setSubstatus(); diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java index 0fd726c167137..f2da4af52373c 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -43,8 +43,8 @@ public PreconditionFailedException() { this(RMResources.PreconditionFailed); } - public PreconditionFailedException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.PRECONDITION_FAILED, error, responseHeaders); + public PreconditionFailedException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.PRECONDITION_FAILED, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java index 9277ee71b2370..1713f86011b56 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -42,8 +42,8 @@ public RequestEntityTooLargeException() { this(RMResources.RequestEntityTooLarge); } - public RequestEntityTooLargeException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE, error, responseHeaders); + public RequestEntityTooLargeException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java index a16762c13f4bf..0e091353da3b5 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -39,8 +39,8 @@ public RequestRateTooLargeException() { this(RMResources.TooManyRequests, null); } - public RequestRateTooLargeException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.NOTFOUND, error, responseHeaders); + public RequestRateTooLargeException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.NOTFOUND, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java index 4de3fdf6a71f3..44631e5a281a3 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -34,8 +34,8 @@ public class RetryWithException extends CosmosClientException { - public RetryWithException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.RETRY_WITH, error, responseHeaders); + public RetryWithException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.RETRY_WITH, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java index 18bce5b766c6c..463706ddb39b7 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -38,8 +38,8 @@ public ServiceUnavailableException() { this(RMResources.ServiceUnavailable); } - public ServiceUnavailableException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.NOTFOUND, error, responseHeaders); + public ServiceUnavailableException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.NOTFOUND, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java index 6c13f5529f296..d6ee5589bba0b 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -39,8 +39,8 @@ public UnauthorizedException() { this(RMResources.Unauthorized); } - public UnauthorizedException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.UNAUTHORIZED, error, responseHeaders); + public UnauthorizedException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.UNAUTHORIZED, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java index cfa1fa43c8a2a..ec9deab03e578 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java @@ -25,7 +25,7 @@ package com.azure.data.cosmos.directconnectivity.rntbd; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.TransportException; import com.fasterxml.jackson.databind.node.ObjectNode; import io.netty.handler.codec.http.HttpResponseStatus; @@ -34,7 +34,7 @@ public final class RntbdContextException extends TransportException { - final private Error error; + final private CosmosError cosmosError; final private Map responseHeaders; final private HttpResponseStatus status; @@ -42,13 +42,13 @@ public final class RntbdContextException extends TransportException { super(status + ": " + details, null); - this.error = BridgeInternal.createError(details); + this.cosmosError = BridgeInternal.createCosmosError(details); this.responseHeaders = responseHeaders; this.status = status; } - public Error getError() { - return error; + public CosmosError getCosmosError() { + return cosmosError; } public Map getResponseHeaders() { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java index 4ba4400401ff5..89988d73dbef6 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.ConflictException; import com.azure.data.cosmos.directconnectivity.ForbiddenException; import com.azure.data.cosmos.directconnectivity.GoneException; @@ -649,9 +649,9 @@ private void messageReceived(final ChannelHandlerContext context, final RntbdRes // ..Create Error instance - final Error error = response.hasPayload() ? - BridgeInternal.createError(RntbdObjectMapper.readTree(response)) : - new Error(Integer.toString(status.code()), status.reasonPhrase(), status.codeClass().name()); + final CosmosError cosmosError = response.hasPayload() ? + BridgeInternal.createCosmosError(RntbdObjectMapper.readTree(response)) : + new CosmosError(Integer.toString(status.code()), status.reasonPhrase(), status.codeClass().name()); // ..Map RNTBD response headers to HTTP response headers @@ -664,15 +664,15 @@ private void messageReceived(final ChannelHandlerContext context, final RntbdRes switch (status.code()) { case StatusCodes.BADREQUEST: - cause = new BadRequestException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new BadRequestException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.CONFLICT: - cause = new ConflictException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new ConflictException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.FORBIDDEN: - cause = new ForbiddenException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new ForbiddenException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.GONE: @@ -681,69 +681,69 @@ private void messageReceived(final ChannelHandlerContext context, final RntbdRes switch (subStatusCode) { case SubStatusCodes.COMPLETING_SPLIT: - cause = new PartitionKeyRangeIsSplittingException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new PartitionKeyRangeIsSplittingException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.COMPLETING_PARTITION_MIGRATION: - cause = new PartitionIsMigratingException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new PartitionIsMigratingException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.NAME_CACHE_IS_STALE: - cause = new InvalidPartitionException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new InvalidPartitionException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case SubStatusCodes.PARTITION_KEY_RANGE_GONE: - cause = new PartitionKeyRangeGoneException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new PartitionKeyRangeGoneException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; default: - cause = new GoneException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new GoneException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; } break; case StatusCodes.INTERNAL_SERVER_ERROR: - cause = new InternalServerErrorException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new InternalServerErrorException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.LOCKED: - cause = new LockedException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new LockedException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.METHOD_NOT_ALLOWED: - cause = new MethodNotAllowedException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new MethodNotAllowedException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.NOTFOUND: - cause = new NotFoundException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new NotFoundException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.PRECONDITION_FAILED: - cause = new PreconditionFailedException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new PreconditionFailedException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_ENTITY_TOO_LARGE: - cause = new RequestEntityTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new RequestEntityTooLargeException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.REQUEST_TIMEOUT: - cause = new RequestTimeoutException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new RequestTimeoutException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.RETRY_WITH: - cause = new RetryWithException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new RetryWithException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.SERVICE_UNAVAILABLE: - cause = new ServiceUnavailableException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new ServiceUnavailableException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.TOO_MANY_REQUESTS: - cause = new RequestRateTooLargeException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new RequestRateTooLargeException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; case StatusCodes.UNAUTHORIZED: - cause = new UnauthorizedException(error, lsn, partitionKeyRangeId, responseHeaders); + cause = new UnauthorizedException(cosmosError, lsn, partitionKeyRangeId, responseHeaders); break; default: - cause = new CosmosClientException(status.code(), error, responseHeaders); + cause = new CosmosClientException(status.code(), cosmosError, responseHeaders); break; } diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java b/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java index bb40a6e61b63c..7b689595ff40d 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java @@ -1,5 +1,6 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.fasterxml.jackson.databind.node.NullNode; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java index 399eecaf7605e..ab9fe1cf2cdcb 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java @@ -25,9 +25,9 @@ import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; import com.azure.data.cosmos.internal.InvalidPartitionException; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java index 0698078c9f115..c7e72fb0dcfe9 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.directconnectivity; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java index bff642f62df92..886552c564219 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.HttpConstants; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java index 4181a71a27e2e..5cf0a6b75ffba 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.DatabaseAccount; -import com.azure.data.cosmos.ReplicationPolicy; +import com.azure.data.cosmos.internal.ReplicationPolicy; import org.mockito.Mockito; import reactor.core.publisher.Mono; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java index 8c91719e9529b..dc3417f3c8e3b 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.directconnectivity; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.Undefined; import com.azure.data.cosmos.internal.RMResources; @@ -63,7 +63,7 @@ public void partitionKey(Object partitionKey, String partitionKeyAsJson) { */ @Test(groups = "unit", dataProvider = "paramProvider") public void partitionKeyCompare(Object partitionKey, String partitionKeyAsJson) { - assertThat(new PartitionKey(partitionKey)).isEqualTo(PartitionKey.FromJsonString(partitionKeyAsJson)); + assertThat(new PartitionKey(partitionKey)).isEqualTo(PartitionKey.fromJsonString(partitionKeyAsJson)); } /** @@ -73,7 +73,7 @@ public void partitionKeyCompare(Object partitionKey, String partitionKeyAsJson) public void tooFewPartitionKeyComponents() { PartitionKeyDefinition pkd = new PartitionKeyDefinition(); pkd.paths(ImmutableList.of("/pk1", "/pk2")); - PartitionKey pk = PartitionKey.FromJsonString("[\"PartitionKeyValue\"]"); + PartitionKey pk = PartitionKey.fromJsonString("[\"PartitionKeyValue\"]"); try { PartitionKeyInternalHelper.getEffectivePartitionKeyString(pk.getInternalPartitionKey(), pkd); @@ -90,7 +90,7 @@ public void tooFewPartitionKeyComponents() { public void tooManyPartitionKeyComponents() { PartitionKeyDefinition pkd = new PartitionKeyDefinition(); pkd.paths(ImmutableList.of("/pk1")); - PartitionKey pk = PartitionKey.FromJsonString("[true, false]"); + PartitionKey pk = PartitionKey.fromJsonString("[true, false]"); try { PartitionKeyInternalHelper.getEffectivePartitionKeyString(pk.getInternalPartitionKey(), pkd); diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java index c8ba601f93fd3..0ddeaa8ef9d7c 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java index 78b2d875cc556..73cbe8ab81234 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.HttpConstants; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java index ef286b6f78ab4..4def77e1f07f7 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java @@ -26,8 +26,8 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.ReplicationPolicy; +import com.azure.data.cosmos.internal.PartitionKeyRange; +import com.azure.data.cosmos.internal.ReplicationPolicy; import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java index 87e2cf8d05866..2ae0fb09dd9b9 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ISessionToken; diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java index e20819277860a..ab1afe53d34c0 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.ResourceResponse; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java index 8e0c5d26bcff3..3c96d8ddf58e8 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java @@ -33,10 +33,10 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.StoredProcedure; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.StoredProcedure; import com.azure.data.cosmos.rx.examples.multimaster.Helpers; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java index afbb7fc319ef0..2b9b08cd2fef8 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java @@ -37,8 +37,8 @@ import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.ResourceResponse; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; @@ -394,7 +394,7 @@ private DocumentCollection getMultiPartitionCollectionDefinition() { // Set indexing policy to be range range for string and number IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection includedPaths = new ArrayList<>(); + List includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); includedPath.path("/*"); Collection indexes = new ArrayList<>(); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java index d2f2c94d2a8a7..a1d9b104c9275 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java @@ -30,7 +30,7 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.ResourceResponse; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java index 41c373439442e..4436f2f095000 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java @@ -34,10 +34,10 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.ResourceResponse; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java index 8f44e3aaf95d4..c406f95f8955b 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java @@ -33,7 +33,7 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java index 6efe0b1b9df83..d3a5733140c23 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java @@ -35,9 +35,9 @@ import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; -import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -156,7 +156,7 @@ private DocumentCollection getMultiPartitionCollectionDefinition() { // Set indexing policy to be range range for string and number IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection includedPaths = new ArrayList<>(); + List includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); includedPath.path("/*"); Collection indexes = new ArrayList<>(); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java index 53b98fb4cefb9..15c09e795818c 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java @@ -35,10 +35,10 @@ import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.StoredProcedure; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.StoredProcedure; import com.azure.data.cosmos.internal.HttpConstants; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -47,7 +47,6 @@ import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -246,10 +245,10 @@ private static DocumentCollection getMultiPartitionCollectionDefinition() { // Set indexing policy to be range range for string and number IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection includedPaths = new ArrayList(); + List includedPaths = new ArrayList(); IncludedPath includedPath = new IncludedPath(); includedPath.path("/*"); - Collection indexes = new ArrayList(); + List indexes = new ArrayList(); Index stringIndex = Index.Range(DataType.STRING); BridgeInternal.setProperty(stringIndex, "precision", -1); indexes.add(stringIndex); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java index b99f32c256d86..5b32500712b35 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java @@ -32,14 +32,14 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; -import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.TokenResolver; -import com.azure.data.cosmos.User; +import com.azure.data.cosmos.internal.User; import com.google.common.collect.ImmutableMap; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java index 1bceda236660e..6b16f43f26881 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java @@ -32,10 +32,11 @@ import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.UniqueKey; import com.azure.data.cosmos.UniqueKeyPolicy; +import com.azure.data.cosmos.internal.ResourceResponse; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; import io.reactivex.subscribers.TestSubscriber; import org.hamcrest.Matchers; import org.testng.annotations.AfterClass; @@ -44,7 +45,6 @@ import reactor.core.publisher.Flux; import java.util.ArrayList; -import java.util.Collections; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; @@ -64,7 +64,7 @@ public void uniqueIndex() { UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.paths(ImmutableList.of("/name", "/field")); - uniqueKeyPolicy.uniqueKeys(Collections.singleton(uniqueKey)); + uniqueKeyPolicy.uniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.setUniqueKeyPolicy(uniqueKeyPolicy); PartitionKeyDefinition partitionKeyDef = new PartitionKeyDefinition(); ArrayList paths = new ArrayList(); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java index c5de4b904b1b5..194dfc34b31d0 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java @@ -30,7 +30,7 @@ import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.rx.TestConfigurations; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java index 1b92a019695f4..6e940ba093cd6 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java @@ -22,7 +22,6 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.PartitionKeyRange; import com.azure.data.cosmos.internal.routing.Range; import reactor.core.publisher.Mono; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java index 37695b2958640..b8cb566c39a93 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -43,8 +43,8 @@ public InvalidPartitionException() { this(RMResources.Gone); } - public InvalidPartitionException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.GONE, error, responseHeaders); + public InvalidPartitionException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.GONE, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java index 3318eddc646f7..3b03cf957b9f7 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -42,8 +42,8 @@ public NotFoundException() { this(RMResources.NotFound); } - public NotFoundException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.NOTFOUND, error, responseHeaders); + public NotFoundException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.NOTFOUND, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java index 43ecf8b1619a6..199b93b965cda 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -43,8 +43,8 @@ public PartitionIsMigratingException() { this(RMResources.Gone); } - public PartitionIsMigratingException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.GONE, error, responseHeaders); + public PartitionIsMigratingException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.GONE, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java index c70b65d4ecf56..b2dfd9aba5df3 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import reactor.core.publisher.Mono; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java index 759baddf288ab..70efa706866eb 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -43,8 +43,8 @@ public PartitionKeyRangeIsSplittingException() { this(RMResources.Gone); } - public PartitionKeyRangeIsSplittingException(Error error, long lsn, String partitionKeyRangeId, Map responseHeaders) { - super(HttpConstants.StatusCodes.GONE, error, responseHeaders); + public PartitionKeyRangeIsSplittingException(CosmosError cosmosError, long lsn, String partitionKeyRangeId, Map responseHeaders) { + super(HttpConstants.StatusCodes.GONE, cosmosError, responseHeaders); BridgeInternal.setLSN(this, lsn); BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java index d283b21ae8cd0..8a209afd5a739 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.StoreResponse; @@ -400,13 +400,13 @@ private void validateOrThrow(RxDocumentServiceRequest request, HttpResponseStatu String statusCodeString = status.reasonPhrase() != null ? status.reasonPhrase().replace(" ", "") : ""; - Error error; - error = (StringUtils.isNotEmpty(body)) ? new Error(body) : new Error(); - error = new Error(statusCodeString, - String.format("%s, StatusCode: %s", error.getMessage(), statusCodeString), - error.getPartitionedQueryExecutionInfo()); + CosmosError cosmosError; + cosmosError = (StringUtils.isNotEmpty(body)) ? BridgeInternal.createCosmosError(body) : new CosmosError(); + cosmosError = new CosmosError(statusCodeString, + String.format("%s, StatusCode: %s", cosmosError.getMessage(), statusCodeString), + cosmosError.getPartitionedQueryExecutionInfo()); - CosmosClientException dce = new CosmosClientException(statusCode, error, headers.toMap()); + CosmosClientException dce = new CosmosClientException(statusCode, cosmosError, headers.toMap()); BridgeInternal.setRequestHeaders(dce, request.getHeaders()); throw dce; } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java index f30e7a9fcdec3..5057a560a2018 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos.internal.caches; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; import com.azure.data.cosmos.internal.IRoutingMapProvider; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java index c5ce551dc29d4..1c00989f57a33 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.Undefined; import com.azure.data.cosmos.internal.Constants; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java index 2afca90e9ff3e..14d72de58b29f 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java @@ -25,8 +25,8 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.internal.PartitionKeyRange; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.BackoffRetryUtility; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java index cf420023fd6e9..09480d89ee140 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java @@ -27,9 +27,9 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.JsonSerializable; -import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.QueryMetrics; -import com.azure.data.cosmos.QueryMetricsConstants; +import com.azure.data.cosmos.internal.PartitionKeyRange; +import com.azure.data.cosmos.internal.QueryMetrics; +import com.azure.data.cosmos.internal.QueryMetricsConstants; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java index 46f6d269d93bb..3990a3f8b7d0b 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java index 3cb8f4136437a..d7462d9da288f 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java @@ -25,8 +25,8 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.BadRequestException; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java index 4632d7c7b43dd..0695f55fd6e0c 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java @@ -25,8 +25,8 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.internal.PartitionKeyRange; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java index c120402c15f8a..eebd28a4cfc69 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java @@ -26,8 +26,8 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.internal.PartitionKeyRange; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; @@ -42,7 +42,6 @@ import com.azure.data.cosmos.internal.routing.Range; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.tuple.ImmutablePair; -import reactor.core.Exceptions; import reactor.core.publisher.Flux; import java.util.ArrayList; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java index 7f7d2cb7a6753..6917bec74b404 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos.internal.query; -import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.BadRequestException; import com.azure.data.cosmos.internal.RequestChargeTracker; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java index 4fb2d50ad2591..0fe81f7b2af86 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java index 53b78d6f0ec00..27a62159690f0 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java index 903423d06dfa6..c2182d3a54dd4 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.ResourceType; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java index b93e83a8bfea8..d754f6c2e9ab0 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.Exceptions; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java index 18509e3fe8027..bc49218e8b53d 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.internal.query.orderbyquery; import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.query.QueryItem; import java.util.List; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java index aaa00bd9d3ddb..a180c1955aeaa 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.routing; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import org.apache.commons.lang3.tuple.ImmutablePair; import java.util.Collection; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java index e04dae05d6e3f..89d14550f1394 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.routing; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java index 6791dc2aa7e7a..1b71b61269153 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.routing; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import java.util.Collection; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java index 4f6ebf240143a..512e12641f636 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.routing; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import java.util.ArrayList; import java.util.Collection; diff --git a/gateway/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java b/gateway/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java index 5d931bf37c846..af6900d868dc7 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java +++ b/gateway/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.PartitionKeyRange; + import java.util.List; public class GatewayTestUtils { diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java index e6c245b49787b..170de82b96921 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java @@ -24,7 +24,6 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.GatewayTestUtils; -import com.azure.data.cosmos.PartitionKeyRange; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.commons.io.IOUtils; diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java index 5466feb4f943f..944d32f179dca 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.routing; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java index 6cb444c4ad964..e8ed44a2fca5e 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.routing; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.testng.annotations.Test; diff --git a/pom.xml b/pom.xml index e40ab2618c189..526f1bd558412 100644 --- a/pom.xml +++ b/pom.xml @@ -283,6 +283,7 @@ ${javadoc.opts} **/internal/**/*.java + **/*BridgeInternal.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java b/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java index 85e32e16ef669..98a0956d8bbbd 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java @@ -23,7 +23,17 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.Offer; +import com.azure.data.cosmos.internal.PartitionKeyRange; +import com.azure.data.cosmos.internal.Permission; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.internal.RxDocumentClientImpl; +import com.azure.data.cosmos.internal.StoredProcedure; +import com.azure.data.cosmos.internal.StoredProcedureResponse; +import com.azure.data.cosmos.internal.Trigger; +import com.azure.data.cosmos.internal.User; +import com.azure.data.cosmos.internal.UserDefinedFunction; import reactor.core.publisher.Flux; import java.net.URI; @@ -624,7 +634,7 @@ Flux> queryDocumentChangeFeed(String collectionLink, * @return an {@link Flux} containing the single resource response with the created stored procedure or an error. */ Flux> createStoredProcedure(String collectionLink, StoredProcedure storedProcedure, - RequestOptions options); + RequestOptions options); /** * Upserts a stored procedure. @@ -871,7 +881,7 @@ Flux executeStoredProcedure(String storedProcedureLink, * @return an {@link Flux} containing the single resource response with the created user defined function or an error. */ Flux> createUserDefinedFunction(String collectionLink, UserDefinedFunction udf, - RequestOptions options); + RequestOptions options); /** * Upserts a user defined function. diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java index 3e59929fa0f10..0c7ff61fc8ff0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java @@ -24,6 +24,7 @@ import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Permission; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java index 64a37b8f77a50..5e0dd66e4ed25 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.Permission; import java.util.List; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java index c3cee03b24cf0..7983bc5b460a8 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.RequestOptions; import reactor.core.publisher.Mono; import static com.azure.data.cosmos.internal.Paths.CONFLICTS_PATH_SEGMENT; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java index ec121491b824f..2019544904b20 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java @@ -22,6 +22,8 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.RequestOptions; + public class CosmosConflictRequestOptions extends CosmosRequestOptions{ @Override diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java index e3bccae42d564..0cd4c14257954 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java @@ -22,6 +22,8 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.ResourceResponse; + public class CosmosConflictResponse extends CosmosResponse { private CosmosContainer container; private CosmosConflict conflictClient; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index ff95bb54c206c..b73d413f1bd18 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -23,7 +23,12 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.StoredProcedure; +import com.azure.data.cosmos.internal.Trigger; +import com.azure.data.cosmos.internal.UserDefinedFunction; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java index e9e9b5c3b36e1..8fc7813121d93 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java @@ -22,6 +22,8 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.ResourceResponse; + public class CosmosContainerResponse extends CosmosResponse { private CosmosContainer container; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java index f561d4dbb06c3..d1c918b327af9 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java @@ -23,7 +23,9 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.RequestOptions; import org.apache.commons.lang3.StringUtils; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java index 1c7cf0374af9f..4b75ef23d180b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java @@ -22,6 +22,8 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.ResourceResponse; + public class CosmosDatabaseResponse extends CosmosResponse{ private CosmosDatabase database; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java index ad29bb8fc5d5c..296bcada6e4c9 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.RequestOptions; import reactor.core.publisher.Mono; public class CosmosItem { diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java index 7d1ec05e614e7..d014981022d16 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java @@ -22,6 +22,9 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.ResourceResponse; + public class CosmosItemResponse extends CosmosResponse{ private CosmosItem itemClient; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java index 2ee8bb553a29e..f30ef3596389d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.RequestOptions; import reactor.core.publisher.Mono; public class CosmosPermission { diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java index 58a04c27dba39..63d93aa0ed2b7 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.Permission; import org.apache.commons.lang3.StringUtils; import java.util.List; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java index d1cfccd9f0ece..8227ac9419c10 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java @@ -22,6 +22,9 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Permission; +import com.azure.data.cosmos.internal.ResourceResponse; + public class CosmosPermissionResponse extends CosmosResponse { CosmosPermission permissionClient; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionsRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionsRequestOptions.java index 8fadd731035f7..96cd59f47e32c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionsRequestOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionsRequestOptions.java @@ -22,6 +22,8 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.RequestOptions; + /** * Contains the request options of CosmosPermission */ diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java index 7a2f9927f42e4..54ad53a361874 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java @@ -22,6 +22,9 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.StoredProcedure; +import com.azure.data.cosmos.internal.Trigger; +import com.azure.data.cosmos.internal.UserDefinedFunction; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java index a5e8d2a83b37d..7e22c9504598a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.StoredProcedure; import reactor.core.publisher.Mono; public class CosmosStoredProcedure { diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java index f1691c415fe3b..6e208cac567cd 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java @@ -22,6 +22,10 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.StoredProcedure; +import com.azure.data.cosmos.internal.StoredProcedureResponse; + public class CosmosStoredProcedureResponse extends CosmosResponse { private CosmosStoredProcedure storedProcedure; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java index 48c4afcb1b8ba..93aebc0f0bf56 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.Trigger; import reactor.core.publisher.Mono; public class CosmosTrigger { diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java index c15d0c49181a2..4cf3d4b12782f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java @@ -22,6 +22,9 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.Trigger; + public class CosmosTriggerResponse extends CosmosResponse { private CosmosTriggerProperties cosmosTriggerProperties; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java index 62d7977eff7b1..507cb41195952 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java @@ -1,6 +1,8 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.Permission; +import com.azure.data.cosmos.internal.RequestOptions; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java index f0f6295d6a748..ee0524c77eb19 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.UserDefinedFunction; import reactor.core.publisher.Mono; public class CosmosUserDefinedFunction { diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java index d5d578cc925e9..99b1429ce7dc1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java @@ -22,6 +22,9 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.UserDefinedFunction; + public class CosmosUserDefinedFunctionResponse extends CosmosResponse { private CosmosUserDefinedFunctionProperties cosmosUserDefinedFunctionProperties; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java index c20537fab19e5..e823f022a837d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java @@ -1,5 +1,8 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.User; + public class CosmosUserResponse extends CosmosResponse { private CosmosUser user; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java index 94ac800cb3a8b..2b54a50473df3 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java @@ -41,22 +41,10 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.JsonSerializable; -import com.azure.data.cosmos.MediaOptions; -import com.azure.data.cosmos.Offer; -import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.PartitionKeyRange; -import com.azure.data.cosmos.Permission; -import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.StoredProcedure; -import com.azure.data.cosmos.StoredProcedureResponse; import com.azure.data.cosmos.TokenResolver; -import com.azure.data.cosmos.Trigger; -import com.azure.data.cosmos.User; -import com.azure.data.cosmos.UserDefinedFunction; import com.azure.data.cosmos.directconnectivity.GatewayServiceConfigurationReader; import com.azure.data.cosmos.directconnectivity.ServerStoreModel; import com.azure.data.cosmos.directconnectivity.StoreClient; @@ -900,25 +888,6 @@ private Map getFeedHeaders(FeedOptionsBase options) { return BridgeInternal.getFeedHeaders(options); } - private Map getMediaHeaders(MediaOptions options) { - Map requestHeaders = new HashMap<>(); - - if (options == null || StringUtils.isEmpty(options.getContentType())) { - requestHeaders.put(HttpConstants.HttpHeaders.CONTENT_TYPE, RuntimeConstants.MediaTypes.OCTET_STREAM); - } - - if (options != null) { - if (!StringUtils.isEmpty(options.getContentType())) { - requestHeaders.put(HttpConstants.HttpHeaders.CONTENT_TYPE, options.getContentType()); - } - - if (!StringUtils.isEmpty(options.getSlug())) { - requestHeaders.put(HttpConstants.HttpHeaders.SLUG, options.getSlug()); - } - } - return requestHeaders; - } - private Mono addPartitionKeyInformation(RxDocumentServiceRequest request, Document document, RequestOptions options) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java index 3815b214d5051..63871ab24ebe7 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.NotFoundException; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java index c8c8d2cf839dc..b1b8fadfea04e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java @@ -36,7 +36,7 @@ import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.SqlQuerySpec; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java index af0eb8f9c21dd..eb1ab95444607 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java @@ -37,7 +37,7 @@ import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; import reactor.core.publisher.Flux; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java index b777341b321ac..27bfa38fb24b1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; import com.azure.data.cosmos.internal.changefeed.Lease; import com.azure.data.cosmos.internal.changefeed.LeaseContainer; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java index c0fb1fcaf04c6..d266711ad08f0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.changefeed.Lease; import com.azure.data.cosmos.internal.changefeed.RequestOptionsFactory; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java index 271aaaf299da0..ef9d095f266bc 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.directconnectivity.AddressInformation; import com.azure.data.cosmos.directconnectivity.AddressResolver; import com.azure.data.cosmos.directconnectivity.GatewayAddressCache; diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java index 25a3081572adf..4a6532b4964db 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java @@ -26,7 +26,9 @@ import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.Paths; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java index 8145f15a9b85b..26a98d9d0344b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java @@ -117,14 +117,14 @@ public void validate(T cosmosResponse) { return this; } - public Builder withCompositeIndexes(Collection> compositeIndexesWritten) { + public Builder withCompositeIndexes(List> compositeIndexesWritten) { validators.add(new CosmosResponseValidator() { @Override public void validate(CosmosContainerResponse resourceResponse) { - Iterator> compositeIndexesReadIterator = resourceResponse.properties() + Iterator> compositeIndexesReadIterator = resourceResponse.properties() .indexingPolicy().compositeIndexes().iterator(); - Iterator> compositeIndexesWrittenIterator = compositeIndexesWritten.iterator(); + Iterator> compositeIndexesWrittenIterator = compositeIndexesWritten.iterator(); ArrayList readIndexesStrings = new ArrayList(); ArrayList writtenIndexesStrings = new ArrayList(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java index 619dc39a8fe05..46cc003ed89ef 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java @@ -32,11 +32,11 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.StoredProcedure; -import com.azure.data.cosmos.StoredProcedureResponse; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.StoredProcedure; +import com.azure.data.cosmos.internal.StoredProcedureResponse; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java index b6635dfca30ee..2442d66357e8e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java index 75972cde51fef..24b0c41e28782 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java @@ -29,12 +29,8 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKind; -import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.User; import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.rx.ResourceResponseValidator; import com.azure.data.cosmos.rx.TestConfigurations; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java index a021a53055da7..34258ab7e22f0 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java @@ -33,8 +33,6 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.rx.FailureValidator; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java index a484d2d21e390..214cb8f65b4f4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java @@ -34,13 +34,9 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKind; -import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.User; import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.azure.data.cosmos.internal.routing.Range; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java index 9ed9aed385d3d..d0c644f44338c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java @@ -29,7 +29,6 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.SpyClientBuilder; import com.azure.data.cosmos.internal.http.HttpRequest; import com.azure.data.cosmos.rx.Utils; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java index 0e6b045406a30..464d7bf4f6723 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java @@ -26,7 +26,6 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.rx.FailureValidator; import org.mockito.Mockito; import org.testng.annotations.AfterClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java index d5d5fb19e4a9a..38a90e3229e03 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java @@ -25,11 +25,10 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.Error; -import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.rx.ResourceResponseValidator; import com.google.common.collect.ImmutableMap; @@ -86,7 +85,7 @@ public void retryDocumentCreate() throws Exception { HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_MISMATCH)); - return Flux.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, new Error() , header)); + return Flux.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, new CosmosError() , header)); } else { return client.getOrigGatewayStoreModel().processMessage(req); } @@ -117,7 +116,7 @@ public void createDocument_noRetryOnNonRetriableFailure() throws Exception { HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(2)); - return Flux.error(new CosmosClientException(1, new Error() , header)); + return Flux.error(new CosmosClientException(1, new CosmosError() , header)); } }).when(client.getSpyGatewayStoreModel()).processMessage(anyObject()); @@ -153,7 +152,7 @@ public void createDocument_failImmediatelyOnNonRetriable() throws Exception { HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(2)); - return Flux.error(new CosmosClientException(1, new Error() , header)); + return Flux.error(new CosmosClientException(1, new CosmosError() , header)); } else { return client.getOrigGatewayStoreModel().processMessage(req); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java index d4ca6decd529f..cc5ff81ae207d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java @@ -30,7 +30,6 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.rx.ResourceResponseValidator; import com.azure.data.cosmos.rx.TestConfigurations; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java index 52db5a19d3c44..ada7f6b7cb299 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java @@ -28,9 +28,7 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.internal.http.HttpRequest; import io.netty.handler.codec.http.HttpMethod; import org.apache.commons.lang3.StringUtils; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java b/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java index 9246efbc69c7f..d94f7a3f708e3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java @@ -26,7 +26,6 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.RequestOptions; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index 2190e5e7cc18d..a678d2615dc88 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -42,15 +42,11 @@ import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; -import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.ResourceResponse; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.Undefined; -import com.azure.data.cosmos.User; import com.azure.data.cosmos.directconnectivity.Protocol; import com.azure.data.cosmos.rx.FailureValidator; import com.azure.data.cosmos.rx.FeedResponseListValidator; @@ -342,7 +338,7 @@ private static DocumentCollection getCollectionDefinitionMultiPartitionWithCompo DocumentCollection documentCollection = new DocumentCollection(); IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection> compositeIndexes = new ArrayList>(); + List> compositeIndexes = new ArrayList<>(); //Simple ArrayList compositeIndexSimple = new ArrayList(); @@ -508,7 +504,7 @@ static protected DocumentCollection getCollectionDefinitionWithRangeRangeIndex() paths.add("/mypk"); partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection includedPaths = new ArrayList<>(); + List includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); includedPath.path("/*"); Collection indexes = new ArrayList<>(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java index 85b6cf49a62f9..1c64e9fb1c5ab 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.directconnectivity.GatewayAddressCache; import com.azure.data.cosmos.directconnectivity.GatewayServiceConfigurationReader; import com.azure.data.cosmos.directconnectivity.Protocol; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java index 2e96da81b22ff..ef6c3a8f489ae 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java @@ -26,9 +26,9 @@ import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.Error; +import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.GlobalEndpointManager; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IRetryPolicyFactory; @@ -737,7 +737,7 @@ private static CosmosClientException partitionKeyRangeGoneException() { Map headers = new HashMap<>(); headers.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)); - return new CosmosClientException(HttpConstants.StatusCodes.GONE, new Error(), headers); + return new CosmosClientException(HttpConstants.StatusCodes.GONE, new CosmosError(), headers); } protected void capture(String partitionId, CapturedInvocation captureInvocation) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java index 781afe1662d77..ef9bbeb9874ed 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java @@ -85,7 +85,7 @@ static protected CosmosContainerProperties getCollectionDefinition() { partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection includedPaths = new ArrayList<>(); + List includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); includedPath.path("/*"); Collection indexes = new ArrayList<>(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java index 44432fe875a48..595488345b39f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java @@ -33,7 +33,7 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.RxDocumentClientUnderTest; import io.reactivex.subscribers.TestSubscriber; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java index 3f473eafe03c1..45732a05f0bae 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java @@ -29,11 +29,11 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.internal.TestSuiteBase; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java index b60f3d1e7622f..262834c40dde8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java @@ -41,7 +41,7 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.IndexingMode; import com.azure.data.cosmos.IndexingPolicy; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RetryAnalyzer; import com.azure.data.cosmos.SpatialSpec; @@ -55,6 +55,7 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -152,7 +153,7 @@ public void createCollectionWithCompositeIndexAndSpatialSpec() throws Interrupte compositeIndex2.add(compositePath5); compositeIndex2.add(compositePath6); - Collection> compositeIndexes = new ArrayList>(); + List> compositeIndexes = new ArrayList<>(); compositeIndexes.add(compositeIndex1); compositeIndexes.add(compositeIndex2); indexingPolicy.compositeIndexes(compositeIndexes); @@ -163,9 +164,9 @@ public void createCollectionWithCompositeIndexAndSpatialSpec() throws Interrupte SpatialType.POLYGON, SpatialType.MULTI_POLYGON }; - Collection spatialIndexes = new ArrayList(); + List spatialIndexes = new ArrayList(); for (int index = 0; index < 2; index++) { - Collection collectionOfSpatialTypes = new ArrayList(); + List collectionOfSpatialTypes = new ArrayList(); SpatialSpec spec = new SpatialSpec(); spec.path("/path" + index + "/*"); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java index b8a32cd2980f8..7e7586414cb08 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.CosmosResponseValidator; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -40,7 +40,6 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; import reactor.core.publisher.Mono; -import sun.corba.Bridge; import java.time.Duration; import java.time.OffsetDateTime; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java index 31a662f1d5006..612949bca5826 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java @@ -67,7 +67,7 @@ public class MultiOrderByQueryTests extends TestSuiteBase { private static final String MEDIUM_STRING_FIELD = "mediumStringField"; private static final String LONG_STRING_FIELD = "longStringField"; private static final String PARTITION_KEY = "pk"; - private ArrayList documents = new ArrayList(); + private List documents = new ArrayList(); private CosmosContainer documentCollection; private CosmosClient client; @@ -211,9 +211,9 @@ public void queryDocumentsWithMultiOrder() throws CosmosClientException, Interru boolean[] booleanValues = new boolean[] {true, false}; CosmosContainerProperties containerSettings = documentCollection.read().block().properties(); - Iterator> compositeIndexesIterator = containerSettings.indexingPolicy().compositeIndexes().iterator(); + Iterator> compositeIndexesIterator = containerSettings.indexingPolicy().compositeIndexes().iterator(); while (compositeIndexesIterator.hasNext()) { - ArrayList compositeIndex = compositeIndexesIterator.next(); + List compositeIndex = compositeIndexesIterator.next(); // for every order for (boolean invert : booleanValues) { // for normal and inverted order @@ -261,7 +261,7 @@ public void queryDocumentsWithMultiOrder() throws CosmosClientException, Interru "FROM root " + whereString + " " + "ORDER BY " + orderByItemStringBuilder.toString(); - ArrayList expectedOrderedList = top(sort(filter(this.documents, hasFilter), compositeIndex, invert), hasTop, topCount) ; + List expectedOrderedList = top(sort(filter(this.documents, hasFilter), compositeIndex, invert), hasTop, topCount) ; Flux> queryObservable = documentCollection.queryItems(query, feedOptions); @@ -291,8 +291,8 @@ public void queryDocumentsWithMultiOrder() throws CosmosClientException, Interru validateQueryFailure(queryObservable, validator); } - private ArrayList top(ArrayList arrayList, boolean hasTop, int topCount) { - ArrayList result = new ArrayList(); + private List top(List arrayList, boolean hasTop, int topCount) { + List result = new ArrayList(); int counter = 0; if (hasTop) { while (counter < topCount && counter < arrayList.size()) { @@ -305,7 +305,7 @@ private ArrayList top(ArrayList arra return result; } - private ArrayList sort(ArrayList arrayList, ArrayList compositeIndex, + private List sort(List arrayList, List compositeIndex, boolean invert) { Collection> comparators = new ArrayList>(); Iterator compositeIndexIterator = compositeIndex.iterator(); @@ -326,8 +326,8 @@ private ArrayList sort(ArrayList arr return arrayList; } - private ArrayList filter(ArrayList cosmosItemSettings, boolean hasFilter) { - ArrayList result = new ArrayList(); + private List filter(List cosmosItemSettings, boolean hasFilter) { + List result = new ArrayList(); if (hasFilter) { for (CosmosItemProperties document : cosmosItemSettings) { if (document.getInt(NUMBER_FIELD) % 2 == 0) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java index 280716fa34fae..a9815bb274d19 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.TestSuiteBase; import org.assertj.core.util.Strings; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java index 22166d05c11bc..4eb3568514dd8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java @@ -26,8 +26,8 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.Offer; -import com.azure.data.cosmos.ResourceResponse; +import com.azure.data.cosmos.internal.Offer; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java index 7b72e8ff0ed32..7815f04194e89 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.RetryAnalyzer; import com.azure.data.cosmos.internal.Utils.ValueHolder; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java index 782e22da2c7df..b8c0592f8f554 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.QueryMetrics; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.CompositeContinuationToken; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java index 500dea2a01e7b..d235d0e832e98 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java @@ -29,9 +29,9 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; -import com.azure.data.cosmos.User; +import com.azure.data.cosmos.internal.User; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java index e027d9c4a3eeb..48c31595f5181 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.Offer; +import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java index db4966d0dc7b5..addf634935ef9 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java @@ -27,10 +27,10 @@ import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.User; +import com.azure.data.cosmos.internal.User; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java index 4c405c6614841..5d7a824e8efd1 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java @@ -30,7 +30,7 @@ import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKeyRange; +import com.azure.data.cosmos.internal.PartitionKeyRange; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java index c3025e76a2ba1..e0cc377c8caba 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.CosmosUserProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java index ae14803ebad44..1dc22790dd92b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java @@ -29,13 +29,13 @@ import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; -import com.azure.data.cosmos.RequestOptions; -import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.User; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.User; import com.azure.data.cosmos.internal.TestSuiteBase; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java index 1ccaea396ca1c..98998b47be187 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java @@ -31,8 +31,8 @@ import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; import com.azure.data.cosmos.CosmosStoredProcedureResponse; import com.azure.data.cosmos.CosmosStoredProcedureProperties; -import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.RequestOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index e9796ded07bc8..4b3cbe6718c41 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -54,7 +54,7 @@ import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.RetryOptions; @@ -346,7 +346,7 @@ private static CosmosContainerProperties getCollectionDefinitionMultiPartitionWi CosmosContainerProperties cosmosContainerProperties = new CosmosContainerProperties(UUID.randomUUID().toString(), partitionKeyDefinition); IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection> compositeIndexes = new ArrayList>(); + List> compositeIndexes = new ArrayList<>(); //Simple ArrayList compositeIndexSimple = new ArrayList(); @@ -508,7 +508,7 @@ static protected CosmosContainerProperties getCollectionDefinitionWithRangeRange paths.add("/mypk"); partitionKeyDef.paths(paths); IndexingPolicy indexingPolicy = new IndexingPolicy(); - Collection includedPaths = new ArrayList<>(); + List includedPaths = new ArrayList<>(); IncludedPath includedPath = new IncludedPath(); includedPath.path("/*"); Collection indexes = new ArrayList<>(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java index ce34953600b2a..6bbe2832405ef 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java @@ -35,16 +35,16 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.Permission; +import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.ResourceResponse; -import com.azure.data.cosmos.StoredProcedure; -import com.azure.data.cosmos.StoredProcedureResponse; +import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.StoredProcedure; +import com.azure.data.cosmos.internal.StoredProcedureResponse; import com.azure.data.cosmos.TokenResolver; -import com.azure.data.cosmos.User; +import com.azure.data.cosmos.internal.User; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.SkipException; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java index 81acc28ad5b60..e7f86f0956ae6 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.RetryAnalyzer; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.TakeContinuationToken; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java index c7d9077791516..1f46ecdcb91d5 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java @@ -31,7 +31,7 @@ import com.azure.data.cosmos.CosmosTrigger; import com.azure.data.cosmos.CosmosTriggerProperties; import com.azure.data.cosmos.CosmosTriggerResponse; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; import org.testng.annotations.AfterClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java index 8994d2f724a61..353f2315d14a0 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosTriggerProperties; import com.azure.data.cosmos.CosmosTriggerResponse; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; import org.testng.annotations.AfterClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java index 1650eb8fb1bd3..93bbe83862abe 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java @@ -39,7 +39,7 @@ import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.IndexingMode; import com.azure.data.cosmos.IndexingPolicy; -import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.UniqueKey; import com.azure.data.cosmos.UniqueKeyPolicy; @@ -49,6 +49,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -83,7 +84,7 @@ public void insertWithUniqueIndex() throws Exception { UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.paths(ImmutableList.of("/name", "/description")); - uniqueKeyPolicy.uniqueKeys(Collections.singleton(uniqueKey)); + uniqueKeyPolicy.uniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.uniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); @@ -139,7 +140,7 @@ public void replaceAndDeleteWithUniqueIndex() throws Exception { UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.paths(ImmutableList.of("/name", "/description")); - uniqueKeyPolicy.uniqueKeys(Collections.singleton(uniqueKey)); + uniqueKeyPolicy.uniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.uniqueKeyPolicy(uniqueKeyPolicy); collection = database.createContainer(collectionDefinition).block().container(); @@ -184,7 +185,7 @@ public void uniqueKeySerializationDeserialization() { UniqueKeyPolicy uniqueKeyPolicy = new UniqueKeyPolicy(); UniqueKey uniqueKey = new UniqueKey(); uniqueKey.paths(ImmutableList.of("/name", "/description")); - uniqueKeyPolicy.uniqueKeys(Collections.singleton(uniqueKey)); + uniqueKeyPolicy.uniqueKeys(Lists.newArrayList(uniqueKey)); collectionDefinition.uniqueKeyPolicy(uniqueKeyPolicy); IndexingPolicy indexingPolicy = new IndexingPolicy(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java index 0f8ae18382ec9..34811b0d57da1 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosUserDefinedFunctionProperties; import com.azure.data.cosmos.CosmosUserDefinedFunctionResponse; -import com.azure.data.cosmos.RequestOptions; +import com.azure.data.cosmos.internal.RequestOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; From 7aa95edc41dcf568bcc33eb6681f5cd43f9aa1e1 Mon Sep 17 00:00:00 2001 From: Christopher Anderson Date: Wed, 26 Jun 2019 21:50:26 -0700 Subject: [PATCH 51/85] Feed Options refactor (#213) * FeedOptions refactoring * Remove FeedOptionsBase --- .../com/azure/data/cosmos/BridgeInternal.java | 73 +++++---- .../azure/data/cosmos/ChangeFeedOptions.java | 124 +++++++++++++- .../data/cosmos/CommonsBridgeInternal.java | 36 +++++ .../com/azure/data/cosmos/FeedOptions.java | 126 ++++++++++++++- .../azure/data/cosmos/FeedOptionsBase.java | 152 ------------------ .../internal/RxDocumentServiceRequest.java | 9 +- .../DefaultDocumentQueryExecutionContext.java | 6 +- .../internal/query/DocumentProducer.java | 2 +- .../DocumentQueryExecutionContextBase.java | 7 +- .../data/cosmos/internal/query/Fetcher.java | 9 +- .../data/cosmos/internal/query/Paginator.java | 13 +- .../cosmos/internal/ChangeFeedQueryImpl.java | 10 +- .../cosmos/internal/RxDocumentClientImpl.java | 5 - .../PartitionProcessorImpl.java | 4 +- .../cosmos/internal/query/FetcherTest.java | 15 +- .../azure/data/cosmos/rx/ChangeFeedTest.java | 3 +- .../cosmos/rx/ParallelDocumentQueryTest.java | 3 +- 17 files changed, 359 insertions(+), 238 deletions(-) delete mode 100644 commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java diff --git a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java index c1aa19da4b966..b0b43b70e6b87 100644 --- a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java @@ -99,7 +99,7 @@ public static DatabaseAccount toDatabaseAccount(RxDocumentServiceResponse respon return account; } - public static Map getFeedHeaders(FeedOptionsBase options) { + public static Map getFeedHeaders(ChangeFeedOptions options) { if (options == null) return new HashMap<>(); @@ -110,58 +110,69 @@ public static Map getFeedHeaders(FeedOptionsBase options) { headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, options.maxItemCount().toString()); } - if (options instanceof ChangeFeedOptions) { - ChangeFeedOptions changeFeedOptions = (ChangeFeedOptions) options; + String ifNoneMatchValue = null; + if (options.requestContinuation() != null) { + ifNoneMatchValue = options.requestContinuation(); + } else if (!options.startFromBeginning()) { + ifNoneMatchValue = "*"; + } + // On REST level, change feed is using IF_NONE_MATCH/ETag instead of + // continuation. + if (ifNoneMatchValue != null) { + headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, ifNoneMatchValue); + } - String ifNoneMatchValue = null; - if (changeFeedOptions.requestContinuation() != null) { - ifNoneMatchValue = changeFeedOptions.requestContinuation(); - } else if (!changeFeedOptions.startFromBeginning()) { - ifNoneMatchValue = "*"; - } - // On REST level, change feed is using IF_NONE_MATCH/ETag instead of - // continuation. - if (ifNoneMatchValue != null) { - headers.put(HttpConstants.HttpHeaders.IF_NONE_MATCH, ifNoneMatchValue); - } + headers.put(HttpConstants.HttpHeaders.A_IM, INCREMENTAL_FEED_HEADER_VALUE); + + return headers; + } + + public static Map getFeedHeaders(FeedOptions options) { + + if (options == null) + return new HashMap<>(); + + Map headers = new HashMap<>(); + + if (options.maxItemCount() != null) { + headers.put(HttpConstants.HttpHeaders.PAGE_SIZE, options.maxItemCount().toString()); + } - headers.put(HttpConstants.HttpHeaders.A_IM, INCREMENTAL_FEED_HEADER_VALUE); - } else if (options.requestContinuation() != null) { + if (options.requestContinuation() != null) { headers.put(HttpConstants.HttpHeaders.CONTINUATION, options.requestContinuation()); } - FeedOptions feedOptions = options instanceof FeedOptions ? (FeedOptions) options : null; - if (feedOptions != null) { - if (feedOptions.sessionToken() != null) { - headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, feedOptions.sessionToken()); + if (options != null) { + if (options.sessionToken() != null) { + headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, options.sessionToken()); } - if (feedOptions.enableScanInQuery() != null) { - headers.put(HttpConstants.HttpHeaders.ENABLE_SCAN_IN_QUERY, feedOptions.enableScanInQuery().toString()); + if (options.enableScanInQuery() != null) { + headers.put(HttpConstants.HttpHeaders.ENABLE_SCAN_IN_QUERY, options.enableScanInQuery().toString()); } - if (feedOptions.emitVerboseTracesInQuery() != null) { + if (options.emitVerboseTracesInQuery() != null) { headers.put(HttpConstants.HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY, - feedOptions.emitVerboseTracesInQuery().toString()); + options.emitVerboseTracesInQuery().toString()); } - if (feedOptions.enableCrossPartitionQuery() != null) { + if (options.enableCrossPartitionQuery() != null) { headers.put(HttpConstants.HttpHeaders.ENABLE_CROSS_PARTITION_QUERY, - feedOptions.enableCrossPartitionQuery().toString()); + options.enableCrossPartitionQuery().toString()); } - if (feedOptions.maxDegreeOfParallelism() != 0) { + if (options.maxDegreeOfParallelism() != 0) { headers.put(HttpConstants.HttpHeaders.PARALLELIZE_CROSS_PARTITION_QUERY, Boolean.TRUE.toString()); } - if (feedOptions.responseContinuationTokenLimitInKb() > 0) { + if (options.responseContinuationTokenLimitInKb() > 0) { headers.put(HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, - Strings.toString(feedOptions.responseContinuationTokenLimitInKb())); + Strings.toString(options.responseContinuationTokenLimitInKb())); } - if (feedOptions.populateQueryMetrics()) { + if (options.populateQueryMetrics()) { headers.put(HttpConstants.HttpHeaders.POPULATE_QUERY_METRICS, - String.valueOf(feedOptions.populateQueryMetrics())); + String.valueOf(options.populateQueryMetrics())); } } diff --git a/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java b/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java index baf1f3b0dfbb7..060b5166b4e7d 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java @@ -23,30 +23,39 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.PartitionKeyRange; import java.time.OffsetDateTime; +import java.util.Map; /** * Specifies the options associated with change feed methods (enumeration * operations) in the Azure Cosmos DB database service. */ -public final class ChangeFeedOptions extends FeedOptionsBase { +public final class ChangeFeedOptions { private String partitionKeyRangeId; private boolean startFromBeginning; private OffsetDateTime startDateTime; + private Integer maxItemCount; + private String requestContinuation; + private PartitionKey partitionkey; + private boolean populateQueryMetrics; + private Map properties; public ChangeFeedOptions() { } public ChangeFeedOptions(ChangeFeedOptions options) { - super(options); this.partitionKeyRangeId = options.partitionKeyRangeId; this.startFromBeginning = options.startFromBeginning; this.startDateTime = options.startDateTime; + this.maxItemCount = options.maxItemCount; + this.requestContinuation = options.requestContinuation; + this.partitionkey = options.partitionkey; + this.populateQueryMetrics = options.populateQueryMetrics; } - // TODO: Make private /** * Get the partition key range id for the current request *

@@ -58,11 +67,10 @@ public ChangeFeedOptions(ChangeFeedOptions options) { * @return a string indicating the partition key range ID * @see PartitionKeyRange */ - public String partitionKeyRangeId() { + String partitionKeyRangeId() { return partitionKeyRangeId; } - // TODO: Make private /** * Set the partition key range id for the current request *

@@ -75,7 +83,7 @@ public String partitionKeyRangeId() { * @see PartitionKeyRange * @return the ChangeFeedOptions. */ - public ChangeFeedOptions partitionKeyRangeId(String partitionKeyRangeId) { + ChangeFeedOptions partitionKeyRangeId(String partitionKeyRangeId) { this.partitionKeyRangeId = partitionKeyRangeId; return this; } @@ -125,4 +133,108 @@ public ChangeFeedOptions startDateTime(OffsetDateTime startDateTime) { this.startDateTime = startDateTime; return this; } + + /** + * Gets the maximum number of items to be returned in the enumeration + * operation. + * + * @return the max number of items. + */ + public Integer maxItemCount() { + return this.maxItemCount; + } + + /** + * Sets the maximum number of items to be returned in the enumeration + * operation. + * + * @param maxItemCount the max number of items. + * @return the FeedOptionsBase. + */ + public ChangeFeedOptions maxItemCount(Integer maxItemCount) { + this.maxItemCount = maxItemCount; + return this; + } + + /** + * Gets the request continuation token. + * + * @return the request continuation. + */ + public String requestContinuation() { + return this.requestContinuation; + } + + /** + * Sets the request continuation token. + * + * @param requestContinuation + * the request continuation. + * @return the FeedOptionsBase. + */ + public ChangeFeedOptions requestContinuation(String requestContinuation) { + this.requestContinuation = requestContinuation; + return this; + } + + /** + * Gets the partition key used to identify the current request's target + * partition. + * + * @return the partition key. + */ + public PartitionKey partitionKey() { + return this.partitionkey; + } + + /** + * Sets the partition key used to identify the current request's target + * partition. + * + * @param partitionkey + * the partition key value. + * @return the FeedOptionsBase. + */ + public ChangeFeedOptions partitionKey(PartitionKey partitionkey) { + this.partitionkey = partitionkey; + return this; + } + + /** + * Gets the option to enable populate query metrics + * @return whether to enable populate query metrics + */ + public boolean populateQueryMetrics() { + return populateQueryMetrics; + } + + /** + * Sets the option to enable/disable getting metrics relating to query execution on document query requests + * @param populateQueryMetrics whether to enable or disable query metrics + * @return the FeedOptionsBase. + */ + public ChangeFeedOptions populateQueryMetrics(boolean populateQueryMetrics) { + this.populateQueryMetrics = populateQueryMetrics; + return this; + } + + /** + * Gets the properties + * + * @return Map of request options properties + */ + public Map properties() { + return properties; + } + + /** + * Sets the properties used to identify the request token. + * + * @param properties the properties. + * @return the FeedOptionsBase. + */ + public ChangeFeedOptions properties(Map properties) { + this.properties = properties; + return this; + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java b/commons/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java index 6c6a72a5d8608..00d1f014a5382 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java @@ -31,4 +31,40 @@ public static boolean isV2(PartitionKeyDefinition pkd) { public static void setV2(PartitionKeyDefinition pkd) { pkd.version(PartitionKeyDefinitionVersion.V2); } + + /** + * Gets the partitionKeyRangeId. + * + * @return the partitionKeyRangeId. + */ + public static String partitionKeyRangeIdInternal(FeedOptions options) { + return options.partitionKeyRangeIdInternal(); + } + + /** + * Gets the partitionKeyRangeId. + * + * @return the partitionKeyRangeId. + */ + public static String partitionKeyRangeIdInternal(ChangeFeedOptions options) { + return options.partitionKeyRangeId(); + } + + /** + * Sets the partitionKeyRangeId. + * + * @return the partitionKeyRangeId. + */ + public static FeedOptions partitionKeyRangeIdInternal(FeedOptions options, String partitionKeyRangeId) { + return options.partitionKeyRangeIdInternal(partitionKeyRangeId); + } + + /** + * Sets the partitionKeyRangeId. + * + * @return the partitionKeyRangeId. + */ + public static ChangeFeedOptions partitionKeyRangeIdInternal(ChangeFeedOptions options, String partitionKeyRangeId) { + return options.partitionKeyRangeId(partitionKeyRangeId); + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java b/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java index 0cb65f51724c9..1493e656fe168 100644 --- a/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java @@ -23,11 +23,15 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.PartitionKey; + +import java.util.Map; + /** * Specifies the options associated with feed methods (enumeration operations) * in the Azure Cosmos DB database service. */ -public final class FeedOptions extends FeedOptionsBase { +public final class FeedOptions { private String sessionToken; private String partitionKeyRangeId; private Boolean enableScanInQuery; @@ -36,12 +40,16 @@ public final class FeedOptions extends FeedOptionsBase { private int maxDegreeOfParallelism; private int maxBufferedItemCount; private int responseContinuationTokenLimitInKb; + private Integer maxItemCount; + private String requestContinuation; + private PartitionKey partitionkey; + private boolean populateQueryMetrics; + private Map properties; public FeedOptions() { } public FeedOptions(FeedOptions options) { - super(options); this.sessionToken = options.sessionToken; this.partitionKeyRangeId = options.partitionKeyRangeId; this.enableScanInQuery = options.enableScanInQuery; @@ -50,6 +58,10 @@ public FeedOptions(FeedOptions options) { this.maxDegreeOfParallelism = options.maxDegreeOfParallelism; this.maxBufferedItemCount = options.maxBufferedItemCount; this.responseContinuationTokenLimitInKb = options.responseContinuationTokenLimitInKb; + this.maxItemCount = options.maxItemCount; + this.requestContinuation = options.requestContinuation; + this.partitionkey = options.partitionkey; + this.populateQueryMetrics = options.populateQueryMetrics; } /** @@ -57,18 +69,17 @@ public FeedOptions(FeedOptions options) { * * @return the partitionKeyRangeId. */ - public String partitionKeyRangeIdInternal() { + String partitionKeyRangeIdInternal() { return this.partitionKeyRangeId; } - // TODO: make private /** * Sets the partitionKeyRangeId. * * @param partitionKeyRangeId the partitionKeyRangeId. * @return the FeedOptions. */ - public FeedOptions partitionKeyRangeIdInternal(String partitionKeyRangeId) { + FeedOptions partitionKeyRangeIdInternal(String partitionKeyRangeId) { this.partitionKeyRangeId = partitionKeyRangeId; return this; } @@ -244,4 +255,109 @@ public FeedOptions responseContinuationTokenLimitInKb(int limitInKb) { public int responseContinuationTokenLimitInKb() { return responseContinuationTokenLimitInKb; } + + + /** + * Gets the maximum number of items to be returned in the enumeration + * operation. + * + * @return the max number of items. + */ + public Integer maxItemCount() { + return this.maxItemCount; + } + + /** + * Sets the maximum number of items to be returned in the enumeration + * operation. + * + * @param maxItemCount the max number of items. + * @return the FeedOptionsBase. + */ + public FeedOptions maxItemCount(Integer maxItemCount) { + this.maxItemCount = maxItemCount; + return this; + } + + /** + * Gets the request continuation token. + * + * @return the request continuation. + */ + public String requestContinuation() { + return this.requestContinuation; + } + + /** + * Sets the request continuation token. + * + * @param requestContinuation + * the request continuation. + * @return the FeedOptionsBase. + */ + public FeedOptions requestContinuation(String requestContinuation) { + this.requestContinuation = requestContinuation; + return this; + } + + /** + * Gets the partition key used to identify the current request's target + * partition. + * + * @return the partition key. + */ + public PartitionKey partitionKey() { + return this.partitionkey; + } + + /** + * Sets the partition key used to identify the current request's target + * partition. + * + * @param partitionkey + * the partition key value. + * @return the FeedOptionsBase. + */ + public FeedOptions partitionKey(PartitionKey partitionkey) { + this.partitionkey = partitionkey; + return this; + } + + /** + * Gets the option to enable populate query metrics + * @return whether to enable populate query metrics + */ + public boolean populateQueryMetrics() { + return populateQueryMetrics; + } + + /** + * Sets the option to enable/disable getting metrics relating to query execution on document query requests + * @param populateQueryMetrics whether to enable or disable query metrics + * @return the FeedOptionsBase. + */ + public FeedOptions populateQueryMetrics(boolean populateQueryMetrics) { + this.populateQueryMetrics = populateQueryMetrics; + return this; + } + + /** + * Gets the properties + * + * @return Map of request options properties + */ + public Map properties() { + return properties; + } + + /** + * Sets the properties used to identify the request token. + * + * @param properties the properties. + * @return the FeedOptionsBase. + */ + public FeedOptions properties(Map properties) { + this.properties = properties; + return this; + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java b/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java deleted file mode 100644 index dbcd58e15dc88..0000000000000 --- a/commons/src/main/java/com/azure/data/cosmos/FeedOptionsBase.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.azure.data.cosmos; - -import com.azure.data.cosmos.internal.PartitionKey; - -import java.util.Map; - -/** - * Specifies the common options associated with feed methods (enumeration operations) in the Azure Cosmos DB database service. - */ -public abstract class FeedOptionsBase { - private Integer maxItemCount; - private String requestContinuation; - private PartitionKey partitionkey; - private boolean populateQueryMetrics; - private Map properties; - - protected FeedOptionsBase() {} - - FeedOptionsBase(FeedOptionsBase options) { - this.maxItemCount = options.maxItemCount; - this.requestContinuation = options.requestContinuation; - this.partitionkey = options.partitionkey; - this.populateQueryMetrics = options.populateQueryMetrics; - } - - /** - * Gets the maximum number of items to be returned in the enumeration - * operation. - * - * @return the max number of items. - */ - public Integer maxItemCount() { - return this.maxItemCount; - } - - /** - * Sets the maximum number of items to be returned in the enumeration - * operation. - * - * @param maxItemCount the max number of items. - * @return the FeedOptionsBase. - */ - public FeedOptionsBase maxItemCount(Integer maxItemCount) { - this.maxItemCount = maxItemCount; - return this; - } - - /** - * Gets the request continuation token. - * - * @return the request continuation. - */ - public String requestContinuation() { - return this.requestContinuation; - } - - /** - * Sets the request continuation token. - * - * @param requestContinuation - * the request continuation. - * @return the FeedOptionsBase. - */ - public FeedOptionsBase requestContinuation(String requestContinuation) { - this.requestContinuation = requestContinuation; - return this; - } - - /** - * Gets the partition key used to identify the current request's target - * partition. - * - * @return the partition key. - */ - public PartitionKey partitionKey() { - return this.partitionkey; - } - - /** - * Sets the partition key used to identify the current request's target - * partition. - * - * @param partitionkey - * the partition key value. - * @return the FeedOptionsBase. - */ - public FeedOptionsBase partitionKey(PartitionKey partitionkey) { - this.partitionkey = partitionkey; - return this; - } - - /** - * Gets the option to enable populate query metrics - * @return whether to enable populate query metrics - */ - public boolean populateQueryMetrics() { - return populateQueryMetrics; - } - - /** - * Sets the option to enable/disable getting metrics relating to query execution on document query requests - * @param populateQueryMetrics whether to enable or disable query metrics - * @return the FeedOptionsBase. - */ - public FeedOptionsBase populateQueryMetrics(boolean populateQueryMetrics) { - this.populateQueryMetrics = populateQueryMetrics; - return this; - } - - /** - * Gets the properties - * - * @return Map of request options properties - */ - public Map properties() { - return properties; - } - - /** - * Sets the properties used to identify the request token. - * - * @param properties the properties. - * @return the FeedOptionsBase. - */ - public FeedOptionsBase properties(Map properties) { - this.properties = properties; - return this; - } -} diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java index 940d1b9e7d266..96d1142e21fc2 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java @@ -23,7 +23,8 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.FeedOptionsBase; +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.directconnectivity.WFConstants; @@ -1037,8 +1038,10 @@ private static Map getProperties(Object options) { return null; } else if (options instanceof RequestOptions) { return ((RequestOptions) options).getProperties(); - } else if (options instanceof FeedOptionsBase) { - return ((FeedOptionsBase) options).properties(); + } else if (options instanceof FeedOptions) { + return ((FeedOptions) options).properties(); + } else if (options instanceof ChangeFeedOptions) { + return ((ChangeFeedOptions) options).properties(); } else { return null; } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java index 14d72de58b29f..1aabf7b8a54a0 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java @@ -61,6 +61,8 @@ import java.util.function.BiFunction; import java.util.function.Function; +import static com.azure.data.cosmos.CommonsBridgeInternal.partitionKeyRangeIdInternal; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. @@ -234,8 +236,8 @@ public RxDocumentServiceRequest createRequestAsync(String continuationToken, Int this.query, this.getPartitionKeyInternal()); - if (!StringUtils.isEmpty(feedOptions.partitionKeyRangeIdInternal())) { - request.routeTo(new PartitionKeyRangeIdentity(feedOptions.partitionKeyRangeIdInternal())); + if (!StringUtils.isEmpty(partitionKeyRangeIdInternal(feedOptions))) { + request.routeTo(new PartitionKeyRangeIdentity(partitionKeyRangeIdInternal(feedOptions))); } return request; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java index 09480d89ee140..80f06f6fe1942 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java @@ -179,7 +179,7 @@ public Flux produceAsync() { (token, maxItemCount) -> createRequestFunc.apply(targetRange, token, maxItemCount); Flux> obs = Paginator .getPaginatedQueryResultAsObservable( - feedOptions, + feedOptions.requestContinuation(), sourcePartitionCreateRequestFunc, executeRequestFuncWithRetries, resourceType, diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java index 3990a3f8b7d0b..0aafde005198e 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java @@ -49,6 +49,8 @@ import java.util.Map; import java.util.UUID; +import static com.azure.data.cosmos.CommonsBridgeInternal.partitionKeyRangeIdInternal; + /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. @@ -84,11 +86,6 @@ protected DocumentQueryExecutionContextBase(IDocumentQueryClient client, Resourc @Override abstract public Flux> executeAsync(); - public String getPartitionKeyId() { - // TODO Auto-generated method stub - return this.feedOptions.partitionKeyRangeIdInternal(); - } - public RxDocumentServiceRequest createDocumentServiceRequest(Map requestHeaders, SqlQuerySpec querySpec, PartitionKeyInternal partitionKey) { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java index c71717b72c308..564b836d1e426 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java @@ -23,10 +23,7 @@ package com.azure.data.cosmos.internal.query; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.FeedOptionsBase; -import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.*; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -50,7 +47,7 @@ class Fetcher { public Fetcher(BiFunction createRequestFunc, Function>> executeFunc, - FeedOptionsBase options, + String continuationToken, boolean isChangeFeed, int top, int maxItemCount) { @@ -59,7 +56,7 @@ public Fetcher(BiFunction createReque this.executeFunc = executeFunc; this.isChangeFeed = isChangeFeed; - this.continuationToken = options.requestContinuation(); + this.continuationToken = continuationToken; this.top = top; if (top == -1) { this.maxItemCount = maxItemCount; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java index f55fe964f4b34..4780965387d37 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java @@ -24,7 +24,6 @@ import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedOptionsBase; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; @@ -47,7 +46,7 @@ public static Flux> getPaginatedChangeFeedQ ChangeFeedOptions feedOptions, BiFunction createRequestFunc, Function>> executeFunc, Class resourceType, int maxPageSize) { - return getPaginatedQueryResultAsObservable(feedOptions, createRequestFunc, executeFunc, resourceType, + return getPaginatedQueryResultAsObservable(feedOptions.requestContinuation(), createRequestFunc, executeFunc, resourceType, -1, maxPageSize, true); } @@ -56,28 +55,28 @@ public static Flux> getPaginatedQueryResult BiFunction createRequestFunc, Function>> executeFunc, Class resourceType, int maxPageSize) { - return getPaginatedQueryResultAsObservable(feedOptions, createRequestFunc, executeFunc, resourceType, + return getPaginatedQueryResultAsObservable(feedOptions.requestContinuation(), createRequestFunc, executeFunc, resourceType, -1, maxPageSize); } public static Flux> getPaginatedQueryResultAsObservable( - FeedOptions options, + String continuationToken, BiFunction createRequestFunc, Function>> executeFunc, Class resourceType, int top, int maxPageSize) { - return getPaginatedQueryResultAsObservable(options, createRequestFunc, executeFunc, resourceType, + return getPaginatedQueryResultAsObservable(continuationToken, createRequestFunc, executeFunc, resourceType, top, maxPageSize, false); } private static Flux> getPaginatedQueryResultAsObservable( - FeedOptionsBase options, + String continuationToken, BiFunction createRequestFunc, Function>> executeFunc, Class resourceType, int top, int maxPageSize, boolean isChangeFeed) { return Flux.defer(() -> { Flux>> generate = Flux.generate(() -> - new Fetcher<>(createRequestFunc, executeFunc, options, isChangeFeed, top, maxPageSize), + new Fetcher<>(createRequestFunc, executeFunc, continuationToken, isChangeFeed, top, maxPageSize), (tFetcher, sink) -> { if (tFetcher.shouldFetchMore()) { Flux> nextPage = tFetcher.nextPage(); diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java index c7b2b60dae307..91b36e4bd4ff4 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java @@ -36,6 +36,8 @@ import java.util.function.BiFunction; import java.util.function.Function; +import static com.azure.data.cosmos.CommonsBridgeInternal.partitionKeyRangeIdInternal; + class ChangeFeedQueryImpl { private static final String IfNonMatchAllHeaderValue = "*"; @@ -58,12 +60,12 @@ public ChangeFeedQueryImpl(RxDocumentClientImpl client, changeFeedOptions = changeFeedOptions != null ? changeFeedOptions: new ChangeFeedOptions(); - if (resourceType.isPartitioned() && changeFeedOptions.partitionKeyRangeId() == null && changeFeedOptions.partitionKey() == null) { + if (resourceType.isPartitioned() && partitionKeyRangeIdInternal(changeFeedOptions) == null && changeFeedOptions.partitionKey() == null) { throw new IllegalArgumentException(RMResources.PartitionKeyRangeIdOrPartitionKeyMustBeSpecified); } if (changeFeedOptions.partitionKey() != null && - !Strings.isNullOrEmpty(changeFeedOptions.partitionKeyRangeId())) { + !Strings.isNullOrEmpty(partitionKeyRangeIdInternal(changeFeedOptions))) { throw new IllegalArgumentException(String.format( RMResources.PartitionKeyAndParitionKeyRangeIdBothSpecified @@ -120,8 +122,8 @@ private RxDocumentServiceRequest createDocumentServiceRequest(String continuatio headers, options); - if (options.partitionKeyRangeId() != null) { - req.routeTo(new PartitionKeyRangeIdentity(this.options.partitionKeyRangeId())); + if (partitionKeyRangeIdInternal(options) != null) { + req.routeTo(new PartitionKeyRangeIdentity(partitionKeyRangeIdInternal(this.options))); } return req; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java index 2b54a50473df3..1cfed79c8bb54 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java @@ -37,7 +37,6 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedOptionsBase; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.JsonSerializable; @@ -884,10 +883,6 @@ private Map getRequestHeaders(RequestOptions options) { return headers; } - private Map getFeedHeaders(FeedOptionsBase options) { - return BridgeInternal.getFeedHeaders(options); - } - private Mono addPartitionKeyInformation(RxDocumentServiceRequest request, Document document, RequestOptions options) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java index e9d3b9c1cef9f..ef454fc40f0de 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java @@ -41,6 +41,8 @@ import java.time.Duration; import java.util.List; +import static com.azure.data.cosmos.CommonsBridgeInternal.partitionKeyRangeIdInternal; + /** * Implementation for {@link PartitionProcessor}. */ @@ -64,7 +66,7 @@ public PartitionProcessorImpl(ChangeFeedObserver observer, ChangeFeedContextClie this.options = new ChangeFeedOptions(); this.options.maxItemCount(settings.getMaxItemCount()); - this.options.partitionKeyRangeId(settings.getPartitionKeyRangeId()); + partitionKeyRangeIdInternal(this.options, settings.getPartitionKeyRangeId()); // this.options.sessionToken(settings.sessionToken()); this.options.startFromBeginning(settings.isStartFromBeginning()); this.options.requestContinuation(settings.getStartContinuation()); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java index 26e2899ca24f6..b8ec8137b1094 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java @@ -26,7 +26,6 @@ import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.FeedOptionsBase; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import io.reactivex.subscribers.TestSubscriber; @@ -98,7 +97,7 @@ public void query(FeedOptions options, int top) { assertThat(maxItemCount).describedAs("max item count").isEqualTo( getExpectedMaxItemCountInRequest(options, top, feedResponseList, requestIndex.get())); assertThat(token).describedAs("continuation token").isEqualTo( - getExpectedContinuationTokenInRequest(options, feedResponseList, requestIndex.get())); + getExpectedContinuationTokenInRequest(options.requestContinuation(), feedResponseList, requestIndex.get())); requestIndex.getAndIncrement(); return mock(RxDocumentServiceRequest.class); @@ -113,7 +112,7 @@ public void query(FeedOptions options, int top) { }; Fetcher fetcher = - new Fetcher<>(createRequestFunc, executeFunc, options, false, top, + new Fetcher<>(createRequestFunc, executeFunc, options.requestContinuation(), false, top, options.maxItemCount()); validateFetcher(fetcher, options, top, feedResponseList); @@ -165,7 +164,7 @@ public void changeFeed() { BiFunction createRequestFunc = (token, maxItemCount) -> { assertThat(maxItemCount).describedAs("max item count").isEqualTo(options.maxItemCount()); assertThat(token).describedAs("continuation token").isEqualTo( - getExpectedContinuationTokenInRequest(options, feedResponseList, requestIndex.getAndIncrement())); + getExpectedContinuationTokenInRequest(options.requestContinuation(), feedResponseList, requestIndex.getAndIncrement())); return mock(RxDocumentServiceRequest.class); }; @@ -177,7 +176,7 @@ public void changeFeed() { }; Fetcher fetcher = - new Fetcher<>(createRequestFunc, executeFunc, options, isChangeFeed, top, + new Fetcher<>(createRequestFunc, executeFunc, options.requestContinuation(), isChangeFeed, top, options.maxItemCount()); validateFetcher(fetcher, options, feedResponseList); @@ -206,17 +205,17 @@ private FeedResponse validate(Flux> page) { return subscriber.values().get(0); } - private String getExpectedContinuationTokenInRequest(FeedOptionsBase options, + private String getExpectedContinuationTokenInRequest(String continuationToken, List> feedResponseList, int requestIndex) { if (requestIndex == 0) { - return options.requestContinuation(); + return continuationToken; } return feedResponseList.get(requestIndex - 1).continuationToken(); } - private int getExpectedMaxItemCountInRequest(FeedOptionsBase options, + private int getExpectedMaxItemCountInRequest(FeedOptions options, int top, List> feedResponseList, int requestIndex) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java index 45732a05f0bae..60d1158452289 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java @@ -52,6 +52,7 @@ import java.util.List; import java.util.UUID; +import static com.azure.data.cosmos.CommonsBridgeInternal.partitionKeyRangeIdInternal; import static org.assertj.core.api.Assertions.assertThat; //TODO: change to use external TestSuiteBase @@ -128,7 +129,7 @@ public void changesFromPartitionKeyRangeId_FromBeginning() throws Exception { ChangeFeedOptions changeFeedOption = new ChangeFeedOptions(); changeFeedOption.maxItemCount(3); - changeFeedOption.partitionKeyRangeId(pkRangeId); + partitionKeyRangeIdInternal(changeFeedOption, pkRangeId); changeFeedOption.startFromBeginning(true); List> changeFeedResultList = client.queryDocumentChangeFeed(getCollectionLink(), changeFeedOption) .collectList().block(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java index b8c0592f8f554..f9f735d8b73c5 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java @@ -52,6 +52,7 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import static com.azure.data.cosmos.CommonsBridgeInternal.partitionKeyRangeIdInternal; import static org.assertj.core.api.Assertions.assertThat; public class ParallelDocumentQueryTest extends TestSuiteBase { @@ -220,7 +221,7 @@ public void partitionKeyRangeId() { .map(Resource::id).collectList().single().block()) { String query = "SELECT * from root"; FeedOptions options = new FeedOptions(); - options.partitionKeyRangeIdInternal(partitionKeyRangeId); + partitionKeyRangeIdInternal(options, partitionKeyRangeId); int queryResultCount = createdCollection.queryItems(query, options) .flatMap(p -> Flux.fromIterable(p.results())) .collectList().block().size(); From 292169336ade34acc533445bccdb2efdae8794f8 Mon Sep 17 00:00:00 2001 From: Milis Date: Wed, 26 Jun 2019 21:54:06 -0700 Subject: [PATCH 52/85] Fix issue with the restarting of the processor; the executor cannot be shutdown since this will stop any future execution using it. (#212) --- .../changefeed/implementation/LeaseStoreManagerImpl.java | 8 +++++--- .../implementation/PartitionSupervisorImpl.java | 1 - 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java index ad0f0ba3ddec2..2fcc5460e045e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java @@ -267,9 +267,11 @@ public Mono release(Lease lease) { self.requestOptionsFactory.createRequestOptions(lease), serverLease -> { - if (!serverLease.getOwner().equalsIgnoreCase(lease.getOwner())) { - logger.info("Partition {} no need to release lease. The lease was already taken by another host '{}'.", lease.getLeaseToken(), serverLease.getOwner()); - throw Exceptions.propagate(new LeaseLostException(lease)); + if (serverLease.getOwner() != null) { + if (!serverLease.getOwner().equalsIgnoreCase(lease.getOwner())) { + logger.info("Partition {} no need to release lease. The lease was already taken by another host '{}'.", lease.getLeaseToken(), serverLease.getOwner()); + throw Exceptions.propagate(new LeaseLostException(lease)); + } } serverLease.setOwner(null); diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java index 70dfd1a3c48f5..870c35061074e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java @@ -112,7 +112,6 @@ public void run() { this.processorCancellation.cancel(); this.renewerCancellation.cancel(); - executorService.shutdown(); if (self.processor.getResultException() != null) { throw self.processor.getResultException(); From 40d79fd1c3dcbb655a6bf17ddb77f2dd5eb6ec4e Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Wed, 26 Jun 2019 23:23:42 -0700 Subject: [PATCH 53/85] Exceptions changes (#211) * Moved exceptions to commons module, made most of the constructors package private * Moved PartitionKey back to public scope --- .../cosmos/benchmark/AsyncMixedBenchmark.java | 2 +- .../cosmos/benchmark/AsyncQueryBenchmark.java | 2 +- .../AsyncQuerySinglePartitionMultiple.java | 2 +- .../cosmos/benchmark/AsyncReadBenchmark.java | 2 +- .../data/cosmos/benchmark/DocDBUtils.java | 6 +- .../cosmos/benchmark/ReadMyWriteWorkflow.java | 12 ++-- .../azure/data/cosmos/DatabaseForTest.java | 2 +- .../{internal => }/BadRequestException.java | 13 ++-- .../com/azure/data/cosmos/BridgeInternal.java | 38 ++++++++++- .../azure/data/cosmos/ChangeFeedOptions.java | 1 - .../azure/data/cosmos}/ConflictException.java | 18 +++-- .../data/cosmos/CosmosClientException.java | 21 +++--- .../data/cosmos/CosmosItemRequestOptions.java | 1 - .../CosmosStoredProcedureRequestOptions.java | 1 - .../com/azure/data/cosmos/FeedOptions.java | 2 - .../data/cosmos}/ForbiddenException.java | 16 ++--- .../GoneException.java | 14 ++-- .../InternalServerErrorException.java | 21 +++--- .../cosmos}/InvalidPartitionException.java | 11 ++-- .../azure/data/cosmos}/LockedException.java | 16 ++--- .../cosmos}/MethodNotAllowedException.java | 16 ++--- .../azure/data/cosmos}/NotFoundException.java | 15 ++--- .../PartitionIsMigratingException.java | 15 ++--- .../cosmos/{internal => }/PartitionKey.java | 5 +- .../PartitionKeyRangeGoneException.java | 13 ++-- ...PartitionKeyRangeIsSplittingException.java | 15 ++--- .../cosmos}/PreconditionFailedException.java | 16 ++--- .../RequestEntityTooLargeException.java | 16 ++--- .../cosmos}/RequestRateTooLargeException.java | 16 ++--- .../RequestTimeoutException.java | 14 ++-- .../data/cosmos}/RetryWithException.java | 14 ++-- .../cosmos}/ServiceUnavailableException.java | 14 ++-- ...rCollection.java => SqlParameterList.java} | 65 +++++++++++++++++-- .../com/azure/data/cosmos/SqlQuerySpec.java | 10 +-- .../data/cosmos}/UnauthorizedException.java | 16 ++--- .../directconnectivity/StoreResult.java | 2 +- .../directconnectivity/TimeoutHelper.java | 3 + .../data/cosmos/internal/PathsHelper.java | 1 + .../data/cosmos/internal/Permission.java | 1 + .../data/cosmos/internal/RequestOptions.java | 1 + .../com/azure/data/cosmos/internal/Utils.java | 1 + .../cosmos/CosmosClientExceptionTest.java | 14 ++-- .../com/azure/data/cosmos/PermissionTest.java | 1 - .../directconnectivity/AddressResolver.java | 9 +-- .../directconnectivity/AddressSelector.java | 1 + .../BarrierRequestHelper.java | 2 +- .../directconnectivity/ConsistencyReader.java | 4 +- .../directconnectivity/ConsistencyWriter.java | 3 +- .../GatewayAddressCache.java | 1 + .../GoneAndRetryWithRetryPolicy.java | 20 +++--- .../directconnectivity/HttpClientUtils.java | 2 +- .../HttpTransportClient.java | 25 +++++-- .../directconnectivity/QuorumReader.java | 3 +- .../directconnectivity/RequestHelper.java | 2 +- .../directconnectivity/ServerStoreModel.java | 2 +- .../directconnectivity/StoreClient.java | 5 +- .../directconnectivity/StoreReader.java | 10 +-- .../rntbd/RntbdRequestManager.java | 40 ++++++------ .../rntbd/RntbdRequestRecord.java | 2 +- .../rntbd/RntbdServiceEndpoint.java | 2 +- .../data/cosmos/PartitionKeyHashingTests.java | 1 - .../AddressResolverTest.java | 7 +- .../AddressSelectorTest.java | 1 + .../ConsistencyReaderTest.java | 3 +- .../ConsistencyWriterTest.java | 6 +- .../directconnectivity/ExceptionBuilder.java | 8 ++- .../GoneAndRetryWithRetryPolicyTest.java | 9 +-- .../HttpTransportClientTest.java | 25 +++++-- .../directconnectivity/PartitionKeyTest.java | 2 +- ...catedResourceClientPartitionSplitTest.java | 3 +- .../ReplicatedResourceClientTest.java | 1 + .../RntbdTransportClientTest.java | 25 +++++-- .../StoreReaderDotNetTest.java | 4 +- .../directconnectivity/StoreReaderTest.java | 9 ++- .../data/cosmos/internal/RetryUtilsTest.java | 2 +- .../rx/examples/DocumentCRUDAsyncAPITest.java | 2 +- .../examples/DocumentQueryAsyncAPITest.java | 4 +- .../rx/examples/InMemoryGroupbyTest.java | 6 +- .../examples/StoredProcedureAsyncAPITest.java | 2 +- .../cosmos/rx/examples/TokenResolverTest.java | 2 +- .../cosmos/internal/RxGatewayStoreModel.java | 6 +- .../cosmos/internal/SessionTokenHelper.java | 2 + .../cosmos/internal/VectorSessionToken.java | 1 + .../internal/caches/RxCollectionCache.java | 4 +- .../DocumentQueryExecutionContextBase.java | 4 +- .../DocumentQueryExecutionContextFactory.java | 4 +- .../OrderByDocumentQueryExecutionContext.java | 4 +- .../cosmos/internal/query/OrderByUtils.java | 2 +- ...ParallelDocumentQueryExecutionContext.java | 2 +- ...llelDocumentQueryExecutionContextBase.java | 3 +- .../TopDocumentQueryExecutionContext.java | 4 +- ...eCollectionAwareClientRetryPolicyTest.java | 2 + .../cosmos/internal/SessionTokenTest.java | 1 + .../azure/data/cosmos/CosmosContainer.java | 4 +- .../com/azure/data/cosmos/CosmosDatabase.java | 4 +- .../azure/data/cosmos/CosmosItemResponse.java | 1 - .../cosmos/CosmosPermissionProperties.java | 1 - .../cosmos/internal/RxDocumentClientImpl.java | 1 + .../caches/RxPartitionKeyRangeCache.java | 2 +- .../implementation/LeaseStoreManagerImpl.java | 4 +- ...edByIdCollectionRequestOptionsFactory.java | 2 +- .../data/cosmos/CosmosDatabaseForTest.java | 2 +- .../data/cosmos/CosmosPartitionKeyTests.java | 1 - .../DCDocumentCrudTest.java | 2 +- .../cosmos/internal/ConsistencyTests1.java | 1 + .../cosmos/internal/ConsistencyTests2.java | 1 + .../cosmos/internal/ConsistencyTestsBase.java | 1 + .../DocumentQuerySpyWireContentTest.java | 1 + .../internal/RetryCreateDocumentTest.java | 7 +- .../cosmos/internal/RetryThrottleTest.java | 3 +- .../data/cosmos/internal/SessionTest.java | 1 + .../data/cosmos/internal/TestSuiteBase.java | 1 + .../internal/query/DocumentProducerTest.java | 2 +- .../azure/data/cosmos/rx/ChangeFeedTest.java | 2 +- .../data/cosmos/rx/CollectionCrudTest.java | 3 +- .../data/cosmos/rx/DocumentCrudTest.java | 2 +- .../cosmos/rx/OrderbyDocumentQueryTest.java | 2 +- .../rx/ReadFeedExceptionHandlingTest.java | 2 +- .../data/cosmos/rx/ResourceTokenTest.java | 2 +- .../rx/SinglePartitionDocumentQueryTest.java | 6 +- .../rx/StoredProcedureUpsertReplaceTest.java | 2 +- .../azure/data/cosmos/rx/TestSuiteBase.java | 2 +- .../data/cosmos/rx/TokenResolverTest.java | 2 +- .../azure/data/cosmos/rx/TopQueryTests.java | 2 +- .../azure/data/cosmos/rx/UniqueIndexTest.java | 2 +- 125 files changed, 495 insertions(+), 355 deletions(-) rename commons/src/main/java/com/azure/data/cosmos/{internal => }/BadRequestException.java (88%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/ConflictException.java (84%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/ForbiddenException.java (84%) rename commons/src/main/java/com/azure/data/cosmos/{directconnectivity => }/GoneException.java (89%) rename commons/src/main/java/com/azure/data/cosmos/{internal => }/InternalServerErrorException.java (81%) rename {gateway/src/main/java/com/azure/data/cosmos/internal => commons/src/main/java/com/azure/data/cosmos}/InvalidPartitionException.java (91%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/LockedException.java (86%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/MethodNotAllowedException.java (82%) rename {gateway/src/main/java/com/azure/data/cosmos/internal => commons/src/main/java/com/azure/data/cosmos}/NotFoundException.java (88%) rename {gateway/src/main/java/com/azure/data/cosmos/internal => commons/src/main/java/com/azure/data/cosmos}/PartitionIsMigratingException.java (87%) rename commons/src/main/java/com/azure/data/cosmos/{internal => }/PartitionKey.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/PartitionKeyRangeGoneException.java (86%) rename {gateway/src/main/java/com/azure/data/cosmos/internal => commons/src/main/java/com/azure/data/cosmos}/PartitionKeyRangeIsSplittingException.java (87%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/PreconditionFailedException.java (85%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/RequestEntityTooLargeException.java (85%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/RequestRateTooLargeException.java (84%) rename commons/src/main/java/com/azure/data/cosmos/{directconnectivity => }/RequestTimeoutException.java (88%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/RetryWithException.java (85%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/ServiceUnavailableException.java (85%) rename commons/src/main/java/com/azure/data/cosmos/{SqlParameterCollection.java => SqlParameterList.java} (67%) rename {direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity => commons/src/main/java/com/azure/data/cosmos}/UnauthorizedException.java (84%) diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java index 80a75565751d8..d9e6132dc9300 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.ResourceResponse; import org.apache.commons.lang3.RandomStringUtils; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java index 71cdd6e428924..50132efdabc7c 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import reactor.core.publisher.BaseSubscriber; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java index e89278149bb3a..665e55877a572 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import reactor.core.publisher.BaseSubscriber; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java index 1f2ec84bc2e65..97edb051a503b 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.benchmark; import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.ResourceResponse; import com.codahale.metrics.Timer; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java index f232625048cfa..e9b52b9467fb3 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.SqlParameter; -import com.azure.data.cosmos.SqlParameterCollection; +import com.azure.data.cosmos.SqlParameterList; import com.azure.data.cosmos.SqlQuerySpec; class DocDBUtils { @@ -39,7 +39,7 @@ private DocDBUtils() { static Database getDatabase(AsyncDocumentClient client, String databaseId) { FeedResponse feedResponsePages = client .queryDatabases(new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", - new SqlParameterCollection(new SqlParameter("@id", databaseId))), null) + new SqlParameterList(new SqlParameter("@id", databaseId))), null) .single().block(); if (feedResponsePages.results().isEmpty()) { @@ -53,7 +53,7 @@ static DocumentCollection getCollection(AsyncDocumentClient client, String datab FeedResponse feedResponsePages = client .queryCollections(databaseLink, new SqlQuerySpec("SELECT * FROM root r WHERE r.id=@id", - new SqlParameterCollection(new SqlParameter("@id", collectionId))), + new SqlParameterList(new SqlParameter("@id", collectionId))), null) .single().block(); diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java index 306edfd9f8657..001ef47925016 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java @@ -26,13 +26,13 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.SqlParameterList; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.SqlParameter; -import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.Utils; import org.apache.commons.lang3.RandomUtils; import reactor.core.publisher.BaseSubscriber; @@ -382,14 +382,14 @@ String getWhereCondition(String rootName) { } @Override - SqlParameterCollection getSqlParameterCollection() { - return new SqlParameterCollection(this.parameters); + SqlParameterList getSqlParameterCollection() { + return new SqlParameterList(this.parameters); } } abstract String getWhereCondition(String rootName); - abstract SqlParameterCollection getSqlParameterCollection(); + abstract SqlParameterList getSqlParameterCollection(); } SqlQuerySpec toSqlQuerySpec() { diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java b/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java index b0bae44f957cc..fd8aa47c9774e 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java +++ b/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java @@ -104,7 +104,7 @@ public static void cleanupStaleTestDatabases(DatabaseManager client) { logger.info("Cleaning stale test databases ..."); List dbs = client.queryDatabases( new SqlQuerySpec("SELECT * FROM c WHERE STARTSWITH(c.id, @PREFIX)", - new SqlParameterCollection(new SqlParameter("@PREFIX", DatabaseForTest.SHARED_DB_ID_PREFIX)))) + new SqlParameterList(new SqlParameter("@PREFIX", DatabaseForTest.SHARED_DB_ID_PREFIX)))) .flatMap(page -> Flux.fromIterable(page.results())).collectList().block(); for (Database db : dbs) { diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java b/commons/src/main/java/com/azure/data/cosmos/BadRequestException.java similarity index 88% rename from commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java rename to commons/src/main/java/com/azure/data/cosmos/BadRequestException.java index cbba276c7822e..c5ea16caabcd8 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/BadRequestException.java +++ b/commons/src/main/java/com/azure/data/cosmos/BadRequestException.java @@ -20,12 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.internal; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; @@ -57,7 +56,7 @@ public BadRequestException(String message) { this(message, null, null, null); } - public BadRequestException(String message, HttpHeaders headers, String requestUrlString) { + BadRequestException(String message, HttpHeaders headers, String requestUrlString) { this(message, null, headers, requestUrlString); } @@ -65,11 +64,11 @@ public BadRequestException(String message, HttpHeaders headers, URI requestUri) this(message, headers, requestUri != null ? requestUri.toString() : null); } - public BadRequestException(Exception innerException) { + BadRequestException(Exception innerException) { this(RMResources.BadRequest, innerException, null, null); } - public BadRequestException(String message, + BadRequestException(String message, Exception innerException, HttpHeaders headers, String requestUrlString) { diff --git a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java index b0b43b70e6b87..34b17d27cec67 100644 --- a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java +++ b/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java @@ -23,8 +23,8 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.internal.ReplicationPolicy; import com.azure.data.cosmos.internal.ResourceResponse; @@ -331,4 +331,40 @@ public static CosmosStoredProcedureProperties createCosmosStoredProcedurePropert public static Object getValue(JsonNode value) { return JsonSerializable.getValue(value); } + + public static CosmosClientException setClientSideRequestStatistics(CosmosClientException cosmosClientException, ClientSideRequestStatistics clientSideRequestStatistics) { + return cosmosClientException.clientSideRequestStatistics(clientSideRequestStatistics); + } + + public static CosmosClientException createCosmosClientException(int statusCode) { + return new CosmosClientException(statusCode, null, null, null); + } + + public static CosmosClientException createCosmosClientException(int statusCode, String errorMessage) { + CosmosClientException cosmosClientException = new CosmosClientException(statusCode, errorMessage, null, null); + cosmosClientException.error(new CosmosError()); + cosmosClientException.error().set(Constants.Properties.MESSAGE, errorMessage); + return cosmosClientException; + } + + public static CosmosClientException createCosmosClientException(int statusCode, Exception innerException) { + return new CosmosClientException(statusCode, null, null, innerException); + } + + public static CosmosClientException createCosmosClientException(int statusCode, CosmosError cosmosErrorResource, Map responseHeaders) { + return new CosmosClientException(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); + } + + public static CosmosClientException createCosmosClientException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map responseHeaders) { + CosmosClientException cosmosClientException = new CosmosClientException(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); + cosmosClientException.resourceAddress = resourceAddress; + cosmosClientException.error(cosmosErrorResource); + return cosmosClientException; + } + + public static CosmosClientException createCosmosClientException(String message, Exception exception, Map responseHeaders, int statusCode, String resourceAddress) { + CosmosClientException cosmosClientException = new CosmosClientException(statusCode, message, responseHeaders, exception); + cosmosClientException.resourceAddress = resourceAddress; + return cosmosClientException; + } } diff --git a/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java b/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java index 060b5166b4e7d..daedc612113c1 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.PartitionKeyRange; import java.time.OffsetDateTime; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java b/commons/src/main/java/com/azure/data/cosmos/ConflictException.java similarity index 84% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java rename to commons/src/main/java/com/azure/data/cosmos/ConflictException.java index ab1fc9484b8b3..26bbc48897e3e 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConflictException.java +++ b/commons/src/main/java/com/azure/data/cosmos/ConflictException.java @@ -20,11 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -39,7 +37,7 @@ public class ConflictException extends CosmosClientException { private static final long serialVersionUID = 1L; - public ConflictException() { + ConflictException() { this(RMResources.EntityAlreadyExists); } @@ -49,11 +47,11 @@ public ConflictException(CosmosError cosmosError, long lsn, String partitionKeyR BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public ConflictException(String msg) { + ConflictException(String msg) { super(HttpConstants.StatusCodes.CONFLICT, msg); } - public ConflictException(String msg, String resourceAddress) { + ConflictException(String msg, String resourceAddress) { super(msg, null, null, HttpConstants.StatusCodes.CONFLICT, resourceAddress); } @@ -61,15 +59,15 @@ public ConflictException(String message, HttpHeaders headers, String requestUriS this(message, null, headers, requestUriString); } - public ConflictException(Exception innerException) { + ConflictException(Exception innerException) { this(RMResources.EntityAlreadyExists, innerException, null, null); } - public ConflictException(CosmosError cosmosError, Map headers) { + ConflictException(CosmosError cosmosError, Map headers) { super(HttpConstants.StatusCodes.CONFLICT, cosmosError, headers); } - public ConflictException(String message, + ConflictException(String message, Exception innerException, HttpHeaders headers, String requestUriString) { diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java b/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java index 2d20054c4faaf..a33b84290106d 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java @@ -62,7 +62,7 @@ public class CosmosClientException extends Exception { URI requestUri; String resourceAddress; - private CosmosClientException(int statusCode, String message, Map responseHeaders, Throwable cause) { + CosmosClientException(int statusCode, String message, Map responseHeaders, Throwable cause) { super(message, cause, /* enableSuppression */ true, /* writableStackTrace */ false); this.statusCode = statusCode; this.responseHeaders = responseHeaders == null ? new HashMap<>() : new HashMap<>(responseHeaders); @@ -73,7 +73,7 @@ private CosmosClientException(int statusCode, String message, Map responseHeaders) { + CosmosClientException(int statusCode, CosmosError cosmosErrorResource, Map responseHeaders) { this(/* resourceAddress */ null, statusCode, cosmosErrorResource, responseHeaders); } @@ -119,7 +119,7 @@ public CosmosClientException(int statusCode, CosmosError cosmosErrorResource, Ma * @param responseHeaders the response headers. */ - public CosmosClientException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map responseHeaders) { + CosmosClientException(String resourceAddress, int statusCode, CosmosError cosmosErrorResource, Map responseHeaders) { this(statusCode, cosmosErrorResource == null ? null : cosmosErrorResource.getMessage(), responseHeaders, null); this.resourceAddress = resourceAddress; this.cosmosError = cosmosErrorResource; @@ -134,7 +134,7 @@ public CosmosClientException(String resourceAddress, int statusCode, CosmosError * @param responseHeaders the response headers. * @param resourceAddress the address of the resource the request is associated with. */ - public CosmosClientException(String message, Exception exception, Map responseHeaders, int statusCode, String resourceAddress) { + CosmosClientException(String message, Exception exception, Map responseHeaders, int statusCode, String resourceAddress) { this(statusCode, message, responseHeaders, exception); this.resourceAddress = resourceAddress; } @@ -199,6 +199,10 @@ public CosmosError error() { return this.cosmosError; } + void error(CosmosError cosmosError) { + this.cosmosError = cosmosError; + } + /** * Gets the recommended time interval after which the client can retry failed * requests @@ -254,8 +258,7 @@ public ClientSideRequestStatistics clientSideRequestStatistics() { return clientSideRequestStatistics; } - // TODO: make private - public CosmosClientException clientSideRequestStatistics(ClientSideRequestStatistics clientSideRequestStatistics) { + CosmosClientException clientSideRequestStatistics(ClientSideRequestStatistics clientSideRequestStatistics) { this.clientSideRequestStatistics = clientSideRequestStatistics; return this; } diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java index f844c1808bc96..0c20bddcf5adb 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java @@ -22,7 +22,6 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.RequestOptions; import java.util.List; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java index 1f1c618c634a5..fac71c1937f44 100644 --- a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java @@ -22,7 +22,6 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.RequestOptions; /** diff --git a/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java b/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java index 1493e656fe168..56a45b4330d8a 100644 --- a/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java @@ -23,8 +23,6 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.PartitionKey; - import java.util.Map; /** diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java b/commons/src/main/java/com/azure/data/cosmos/ForbiddenException.java similarity index 84% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java rename to commons/src/main/java/com/azure/data/cosmos/ForbiddenException.java index f81a2f7a47ae4..bb92a2f5ca602 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ForbiddenException.java +++ b/commons/src/main/java/com/azure/data/cosmos/ForbiddenException.java @@ -21,11 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -34,7 +32,7 @@ import java.util.Map; public class ForbiddenException extends CosmosClientException { - public ForbiddenException() { + ForbiddenException() { this(RMResources.Forbidden); } @@ -44,11 +42,11 @@ public ForbiddenException(CosmosError cosmosError, long lsn, String partitionKey BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public ForbiddenException(String message) { + ForbiddenException(String message) { this(message, null, null, null); } - public ForbiddenException(String message, HttpHeaders headers, String requestUrlString) { + ForbiddenException(String message, HttpHeaders headers, String requestUrlString) { this(message, null, headers, requestUrlString); } @@ -56,11 +54,11 @@ public ForbiddenException(String message, HttpHeaders headers, URI requestUri) { this(message, headers, requestUri != null ? requestUri.toString() : null); } - public ForbiddenException(Exception innerException) { + ForbiddenException(Exception innerException) { this(RMResources.Forbidden, innerException, null, null); } - public ForbiddenException(String message, + ForbiddenException(String message, Exception innerException, HttpHeaders headers, String requestUrlString) { diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java b/commons/src/main/java/com/azure/data/cosmos/GoneException.java similarity index 89% rename from commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java rename to commons/src/main/java/com/azure/data/cosmos/GoneException.java index 0e6da921795f9..68a0d2fb7e6c2 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/GoneException.java +++ b/commons/src/main/java/com/azure/data/cosmos/GoneException.java @@ -21,11 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.Strings; @@ -54,14 +52,14 @@ public GoneException(String message, String requestUri) { this(message, null, new HashMap<>(), requestUri); } - public GoneException(String message, + GoneException(String message, Exception innerException, URI requestUri, String localIpAddress) { this(message(localIpAddress, message), innerException, null, requestUri); } - public GoneException(Exception innerException) { + GoneException(Exception innerException) { this(RMResources.Gone, innerException, new HashMap<>(), null); } @@ -69,7 +67,7 @@ public GoneException(String message, HttpHeaders headers, URI requestUrl) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUrl != null ? requestUrl.toString() : null); } - public GoneException(String message, HttpHeaders headers, String requestUriString) { + GoneException(String message, HttpHeaders headers, String requestUriString) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUriString); } @@ -87,7 +85,7 @@ public GoneException(String message, super(message, innerException, headers, HttpConstants.StatusCodes.GONE, requestUriString); } - public GoneException(CosmosError cosmosError, Map headers) { + GoneException(CosmosError cosmosError, Map headers) { super(HttpConstants.StatusCodes.GONE, cosmosError, headers); } diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java b/commons/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java similarity index 81% rename from commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java rename to commons/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java index 70d7d7b1a7736..5920bab2a7a8a 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/InternalServerErrorException.java +++ b/commons/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java @@ -21,12 +21,11 @@ * SOFTWARE. */ -package com.azure.data.cosmos.internal; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; @@ -42,7 +41,7 @@ */ public class InternalServerErrorException extends CosmosClientException { - public InternalServerErrorException() { + InternalServerErrorException() { this(RMResources.InternalServerError); } @@ -57,11 +56,11 @@ public InternalServerErrorException(String message) { } - public InternalServerErrorException(String message, Exception innerException) { + InternalServerErrorException(String message, Exception innerException) { this(message, innerException, (HttpHeaders) null, (String) null); } - public InternalServerErrorException(Exception innerException) { + InternalServerErrorException(Exception innerException) { this(RMResources.InternalServerError, innerException, (HttpHeaders) null, (String) null); } @@ -69,19 +68,19 @@ public InternalServerErrorException(String message, HttpHeaders headers, URI req super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUri != null ? requestUri.toString() : null); } - public InternalServerErrorException(String message, HttpHeaders headers, String requestUriString) { + InternalServerErrorException(String message, HttpHeaders headers, String requestUriString) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUriString); } - public InternalServerErrorException(String message, HttpHeaders headers, URL requestUrl) { + InternalServerErrorException(String message, HttpHeaders headers, URL requestUrl) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUrl != null ? requestUrl.toString() : null); } - public InternalServerErrorException(String message, Exception innerException, HttpHeaders headers, URI requestUri) { + InternalServerErrorException(String message, Exception innerException, HttpHeaders headers, URI requestUri) { super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUri != null ? requestUri.toString() : null); } - public InternalServerErrorException(String message, Exception innerException, HttpHeaders headers, String requestUriString) { + InternalServerErrorException(String message, Exception innerException, HttpHeaders headers, String requestUriString) { super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, requestUriString); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java b/commons/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java similarity index 91% rename from gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java rename to commons/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java index b8cb566c39a93..fb082096cd5f9 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionException.java +++ b/commons/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java @@ -20,13 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.internal; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -63,11 +62,11 @@ public InvalidPartitionException(String message, HttpHeaders headers, String req this(message, null, headers, requestUri); } - public InvalidPartitionException(Exception innerException) { + InvalidPartitionException(Exception innerException) { this(RMResources.Gone, innerException, null, null); } - public InvalidPartitionException(String message, + InvalidPartitionException(String message, Exception innerException, HttpHeaders headers, String requestUri) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java b/commons/src/main/java/com/azure/data/cosmos/LockedException.java similarity index 86% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java rename to commons/src/main/java/com/azure/data/cosmos/LockedException.java index 5cb8868a372ec..ed4997899325b 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/LockedException.java +++ b/commons/src/main/java/com/azure/data/cosmos/LockedException.java @@ -20,11 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -38,7 +36,7 @@ public class LockedException extends CosmosClientException { private static final long serialVersionUID = 1L; - public LockedException() { + LockedException() { this(RMResources.Locked); } @@ -48,11 +46,11 @@ public LockedException(CosmosError cosmosError, long lsn, String partitionKeyRan BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public LockedException(String msg) { + LockedException(String msg) { super(HttpConstants.StatusCodes.LOCKED, msg); } - public LockedException(String msg, String resourceAddress) { + LockedException(String msg, String resourceAddress) { super(msg, null, null, HttpConstants.StatusCodes.LOCKED, resourceAddress); } @@ -60,11 +58,11 @@ public LockedException(String message, HttpHeaders headers, String requestUriStr this(message, null, headers, requestUriString); } - public LockedException(Exception innerException) { + LockedException(Exception innerException) { this(RMResources.Locked, innerException, null, null); } - public LockedException(String message, + LockedException(String message, Exception innerException, HttpHeaders headers, String requestUriString) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java b/commons/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java similarity index 82% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java rename to commons/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java index 522506c671d1b..cc7786f4dc8df 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/MethodNotAllowedException.java +++ b/commons/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java @@ -21,11 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -34,7 +32,7 @@ import java.util.Map; public class MethodNotAllowedException extends CosmosClientException { - public MethodNotAllowedException() { + MethodNotAllowedException() { this(RMResources.MethodNotAllowed); } @@ -44,19 +42,19 @@ public MethodNotAllowedException(CosmosError cosmosError, long lsn, String parti BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public MethodNotAllowedException(String message) { + MethodNotAllowedException(String message) { this(message, null, null, null); } - public MethodNotAllowedException(String message, HttpHeaders headers, String requestUriString) { + MethodNotAllowedException(String message, HttpHeaders headers, String requestUriString) { this(message, null, headers, requestUriString); } - public MethodNotAllowedException(String message, HttpHeaders headers, URI requestUri) { + MethodNotAllowedException(String message, HttpHeaders headers, URI requestUri) { this(message, headers, requestUri != null ? requestUri.toString() : null); } - public MethodNotAllowedException(Exception innerException) { + MethodNotAllowedException(Exception innerException) { this(RMResources.MethodNotAllowed, innerException, null, null); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java b/commons/src/main/java/com/azure/data/cosmos/NotFoundException.java similarity index 88% rename from gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java rename to commons/src/main/java/com/azure/data/cosmos/NotFoundException.java index 3b03cf957b9f7..f64010738b35d 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/NotFoundException.java +++ b/commons/src/main/java/com/azure/data/cosmos/NotFoundException.java @@ -20,12 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.internal; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; @@ -56,7 +55,7 @@ public NotFoundException(String message, Map headers, String req this(message, null, headers, requestUri); } - public NotFoundException(String message, HttpHeaders headers, String requestUri) { + NotFoundException(String message, HttpHeaders headers, String requestUri) { this(message, null, headers, requestUri); } @@ -64,18 +63,18 @@ public NotFoundException(String message, HttpHeaders headers, URI requestUri) { this(message, headers, requestUri != null ? requestUri.toString() : null); } - public NotFoundException(Exception innerException) { + NotFoundException(Exception innerException) { this(RMResources.NotFound, innerException, (Map) null, null); } - public NotFoundException(String message, + NotFoundException(String message, Exception innerException, HttpHeaders headers, String requestUri) { this(message, innerException, HttpUtils.asMap(headers), requestUri); } - public NotFoundException(String message, + NotFoundException(String message, Exception innerException, Map headers, String requestUri) { diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java b/commons/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java similarity index 87% rename from gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java rename to commons/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java index 199b93b965cda..49162efd1f9bd 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionIsMigratingException.java +++ b/commons/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java @@ -20,13 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.internal; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -49,12 +48,12 @@ public PartitionIsMigratingException(CosmosError cosmosError, long lsn, String p BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public PartitionIsMigratingException(String msg) { + PartitionIsMigratingException(String msg) { super(HttpConstants.StatusCodes.GONE, msg); setSubStatus(); } - public PartitionIsMigratingException(String msg, String resourceAddress) { + PartitionIsMigratingException(String msg, String resourceAddress) { super(msg, null, null, HttpConstants.StatusCodes.GONE, resourceAddress); setSubStatus(); } @@ -63,11 +62,11 @@ public PartitionIsMigratingException(String message, HttpHeaders headers, String this(message, null, headers, requestUri); } - public PartitionIsMigratingException(Exception innerException) { + PartitionIsMigratingException(Exception innerException) { this(RMResources.Gone, innerException, null, null); } - public PartitionIsMigratingException(String message, + PartitionIsMigratingException(String message, Exception innerException, HttpHeaders headers, String requestUri) { diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/PartitionKey.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java similarity index 96% rename from commons/src/main/java/com/azure/data/cosmos/internal/PartitionKey.java rename to commons/src/main/java/com/azure/data/cosmos/PartitionKey.java index 9a42201878919..ff4130e6152da 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/PartitionKey.java +++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java @@ -21,8 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.internal; +package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; /** @@ -33,7 +34,7 @@ public class PartitionKey { private PartitionKeyInternal internalPartitionKey; - public PartitionKey(PartitionKeyInternal partitionKeyInternal) { + PartitionKey(PartitionKeyInternal partitionKeyInternal) { this.internalPartitionKey = partitionKeyInternal; } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java similarity index 86% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java rename to commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java index 0d9e1ae106f1a..895934bf4e43a 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PartitionKeyRangeGoneException.java +++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java @@ -21,11 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; +import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -56,11 +55,11 @@ public PartitionKeyRangeGoneException(String message) { this(message, null, null, null); } - public PartitionKeyRangeGoneException(String message, Exception innerException) { + PartitionKeyRangeGoneException(String message, Exception innerException) { this(message, innerException, null, null); } - public PartitionKeyRangeGoneException(Exception innerException) { + PartitionKeyRangeGoneException(Exception innerException) { this(RMResources.Gone, innerException, null, null); } @@ -70,7 +69,7 @@ public PartitionKeyRangeGoneException(String message, HttpHeaders headers, Strin this.setSubstatus(); } - public PartitionKeyRangeGoneException(String message, Exception innerException, HttpHeaders headers, String requestUriString) { + PartitionKeyRangeGoneException(String message, Exception innerException, HttpHeaders headers, String requestUriString) { super(message, innerException, HttpUtils.asMap(headers), HttpConstants.StatusCodes.GONE, requestUriString); this.setSubstatus(); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java similarity index 87% rename from gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java rename to commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java index 70efa706866eb..f66d030eafcfa 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeIsSplittingException.java +++ b/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java @@ -20,13 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.internal; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; @@ -49,12 +48,12 @@ public PartitionKeyRangeIsSplittingException(CosmosError cosmosError, long lsn, BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public PartitionKeyRangeIsSplittingException(String msg) { + PartitionKeyRangeIsSplittingException(String msg) { super(HttpConstants.StatusCodes.GONE, msg); setSubStatus(); } - public PartitionKeyRangeIsSplittingException(String msg, String resourceAddress) { + PartitionKeyRangeIsSplittingException(String msg, String resourceAddress) { super(msg, null, null, HttpConstants.StatusCodes.GONE, resourceAddress); setSubStatus(); } @@ -63,11 +62,11 @@ public PartitionKeyRangeIsSplittingException(String message, HttpHeaders headers this(message, null, headers, requestUri); } - public PartitionKeyRangeIsSplittingException(Exception innerException) { + PartitionKeyRangeIsSplittingException(Exception innerException) { this(RMResources.Gone, innerException, null, null); } - public PartitionKeyRangeIsSplittingException(String message, + PartitionKeyRangeIsSplittingException(String message, Exception innerException, HttpHeaders headers, String requestUri) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java b/commons/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java similarity index 85% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java rename to commons/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java index f2da4af52373c..0b8942e5b101d 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/PreconditionFailedException.java +++ b/commons/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java @@ -20,11 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -39,7 +37,7 @@ public class PreconditionFailedException extends CosmosClientException { private static final long serialVersionUID = 1L; - public PreconditionFailedException() { + PreconditionFailedException() { this(RMResources.PreconditionFailed); } @@ -49,11 +47,11 @@ public PreconditionFailedException(CosmosError cosmosError, long lsn, String par BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public PreconditionFailedException(String msg) { + PreconditionFailedException(String msg) { super(HttpConstants.StatusCodes.PRECONDITION_FAILED, msg); } - public PreconditionFailedException(String msg, String resourceAddress) { + PreconditionFailedException(String msg, String resourceAddress) { super(msg, null, null, HttpConstants.StatusCodes.PRECONDITION_FAILED, resourceAddress); } @@ -61,11 +59,11 @@ public PreconditionFailedException(String message, HttpHeaders headers, String r this(message, null, headers, requestUriString); } - public PreconditionFailedException(Exception innerException) { + PreconditionFailedException(Exception innerException) { this(RMResources.PreconditionFailed, innerException, null, null); } - public PreconditionFailedException(String message, + PreconditionFailedException(String message, Exception innerException, HttpHeaders headers, String requestUriString) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java b/commons/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java similarity index 85% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java rename to commons/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java index 1713f86011b56..de826ceab0c64 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestEntityTooLargeException.java +++ b/commons/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java @@ -20,11 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -38,7 +36,7 @@ public class RequestEntityTooLargeException extends CosmosClientException { private static final long serialVersionUID = 1L; - public RequestEntityTooLargeException() { + RequestEntityTooLargeException() { this(RMResources.RequestEntityTooLarge); } @@ -48,11 +46,11 @@ public RequestEntityTooLargeException(CosmosError cosmosError, long lsn, String BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public RequestEntityTooLargeException(String msg) { + RequestEntityTooLargeException(String msg) { super(HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE, msg); } - public RequestEntityTooLargeException(String msg, String resourceAddress) { + RequestEntityTooLargeException(String msg, String resourceAddress) { super(msg, null, null, HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE, resourceAddress); } @@ -60,11 +58,11 @@ public RequestEntityTooLargeException(String message, HttpHeaders headers, Strin this(message, null, headers, requestUriString); } - public RequestEntityTooLargeException(Exception innerException) { + RequestEntityTooLargeException(Exception innerException) { this(RMResources.RequestEntityTooLarge, innerException, null, null); } - public RequestEntityTooLargeException(String message, + RequestEntityTooLargeException(String message, Exception innerException, HttpHeaders headers, String requestUriString) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java b/commons/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java similarity index 84% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java rename to commons/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java index 0e091353da3b5..219878c192706 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestRateTooLargeException.java +++ b/commons/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java @@ -21,11 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -45,17 +43,17 @@ public RequestRateTooLargeException(CosmosError cosmosError, long lsn, String pa BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public RequestRateTooLargeException(String message, URI requestUri) { + RequestRateTooLargeException(String message, URI requestUri) { this(message, null, null, requestUri); } - public RequestRateTooLargeException(String message, + RequestRateTooLargeException(String message, Exception innerException, URI requestUri) { this(message, innerException, null, requestUri); } - public RequestRateTooLargeException(Exception innerException) { + RequestRateTooLargeException(Exception innerException) { this(RMResources.TooManyRequests, innerException, null, null); } @@ -63,11 +61,11 @@ public RequestRateTooLargeException(String message, HttpHeaders headers, URI req super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.TOO_MANY_REQUESTS, requestUri != null ? requestUri.toString() : null); } - public RequestRateTooLargeException(String message, HttpHeaders headers, String requestUriString) { + RequestRateTooLargeException(String message, HttpHeaders headers, String requestUriString) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.TOO_MANY_REQUESTS, requestUriString); } - public RequestRateTooLargeException(String message, + RequestRateTooLargeException(String message, Exception innerException, HttpHeaders headers, URI requestUri) { diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java b/commons/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java similarity index 88% rename from commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java rename to commons/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java index d20210d473b37..d9431f86aacba 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/RequestTimeoutException.java +++ b/commons/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java @@ -21,11 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.Strings; @@ -50,14 +48,14 @@ public RequestTimeoutException(String message, URI requestUri) { this(message, null, null, requestUri); } - public RequestTimeoutException(String message, + RequestTimeoutException(String message, Exception innerException, URI requestUri, String localIpAddress) { this(message(localIpAddress, message), innerException, null, requestUri); } - public RequestTimeoutException(Exception innerException) { + RequestTimeoutException(Exception innerException) { this(RMResources.Gone, innerException, (HttpHeaders) null, null); } @@ -65,11 +63,11 @@ public RequestTimeoutException(String message, HttpHeaders headers, URI requestU super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUrl != null ? requestUrl.toString() : null); } - public RequestTimeoutException(String message, HttpHeaders headers, String requestUriString) { + RequestTimeoutException(String message, HttpHeaders headers, String requestUriString) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.REQUEST_TIMEOUT, requestUriString); } - public RequestTimeoutException(String message, + RequestTimeoutException(String message, Exception innerException, HttpHeaders headers, URI requestUrl) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java b/commons/src/main/java/com/azure/data/cosmos/RetryWithException.java similarity index 85% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java rename to commons/src/main/java/com/azure/data/cosmos/RetryWithException.java index 44631e5a281a3..31d8b317ecbf2 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RetryWithException.java +++ b/commons/src/main/java/com/azure/data/cosmos/RetryWithException.java @@ -21,11 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -40,11 +38,11 @@ public RetryWithException(CosmosError cosmosError, long lsn, String partitionKey BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public RetryWithException(String message, URI requestUri) { + RetryWithException(String message, URI requestUri) { this(message, null, null, requestUri); } - public RetryWithException(String message, + RetryWithException(String message, Exception innerException, URI requestUri) { this(message, innerException, null, requestUri); @@ -54,11 +52,11 @@ public RetryWithException(String message, HttpHeaders headers, URI requestUri) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.RETRY_WITH, requestUri != null ? requestUri.toString() : null); } - public RetryWithException(String message, HttpHeaders headers, String requestUriString) { + RetryWithException(String message, HttpHeaders headers, String requestUriString) { super(message, null, HttpUtils.asMap(headers), HttpConstants.StatusCodes.RETRY_WITH, requestUriString); } - public RetryWithException(String message, + RetryWithException(String message, Exception innerException, HttpHeaders headers, URI requestUri) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java b/commons/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java similarity index 85% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java rename to commons/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java index 463706ddb39b7..8e9ab2dd3434a 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceUnavailableException.java +++ b/commons/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java @@ -21,11 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -34,7 +32,7 @@ import java.util.Map; public class ServiceUnavailableException extends CosmosClientException { - public ServiceUnavailableException() { + ServiceUnavailableException() { this(RMResources.ServiceUnavailable); } @@ -44,11 +42,11 @@ public ServiceUnavailableException(CosmosError cosmosError, long lsn, String par BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public ServiceUnavailableException(String message) { + ServiceUnavailableException(String message) { this(message, null, null, null); } - public ServiceUnavailableException(String message, HttpHeaders headers, String requestUriString) { + ServiceUnavailableException(String message, HttpHeaders headers, String requestUriString) { this(message, null, headers, requestUriString); } @@ -56,7 +54,7 @@ public ServiceUnavailableException(String message, HttpHeaders headers, URI requ this(message, headers, requestUri != null ? requestUri.toString() : null); } - public ServiceUnavailableException(Exception innerException) { + ServiceUnavailableException(Exception innerException) { this(RMResources.ServiceUnavailable, innerException, null, null); } diff --git a/commons/src/main/java/com/azure/data/cosmos/SqlParameterCollection.java b/commons/src/main/java/com/azure/data/cosmos/SqlParameterList.java similarity index 67% rename from commons/src/main/java/com/azure/data/cosmos/SqlParameterCollection.java rename to commons/src/main/java/com/azure/data/cosmos/SqlParameterList.java index 6e59d37c4c5ce..ff1d9620f00cc 100644 --- a/commons/src/main/java/com/azure/data/cosmos/SqlParameterCollection.java +++ b/commons/src/main/java/com/azure/data/cosmos/SqlParameterList.java @@ -28,27 +28,28 @@ import java.util.Collection; import java.util.Iterator; import java.util.List; +import java.util.ListIterator; /** * Represents a collection of SQL parameters to for a SQL query in the Azure Cosmos DB database service. */ -public final class SqlParameterCollection implements Collection { +public final class SqlParameterList implements List { private List parameters; /** - * Initializes a new instance of the SqlParameterCollection class. + * Initializes a new instance of the SqlParameterList class. */ - public SqlParameterCollection() { + public SqlParameterList() { this.parameters = new ArrayList(); } /** - * Initializes a new instance of the SqlParameterCollection class from an array of parameters. + * Initializes a new instance of the SqlParameterList class from an array of parameters. * * @param parameters the array of parameters. */ - public SqlParameterCollection(SqlParameter... parameters) { + public SqlParameterList(SqlParameter... parameters) { if (parameters == null) { throw new IllegalArgumentException("parameters"); } @@ -57,11 +58,11 @@ public SqlParameterCollection(SqlParameter... parameters) { } /** - * Initializes a new instance of the SqlParameterCollection class from a collection of parameters. + * Initializes a new instance of the SqlParameterList class from a collection of parameters. * * @param parameters the collection of parameters. */ - public SqlParameterCollection(Collection parameters) { + public SqlParameterList(Collection parameters) { if (parameters == null) { throw new IllegalArgumentException("parameters"); } @@ -79,11 +80,61 @@ public boolean addAll(Collection parameters) { return this.parameters.addAll(parameters); } + @Override + public boolean addAll(int index, Collection c) { + return this.parameters.addAll(index, c); + } + @Override public void clear() { this.parameters.clear(); } + @Override + public SqlParameter get(int index) { + return this.parameters.get(index); + } + + @Override + public SqlParameter set(int index, SqlParameter element) { + return this.parameters.set(index, element); + } + + @Override + public void add(int index, SqlParameter element) { + this.parameters.add(index, element); + } + + @Override + public SqlParameter remove(int index) { + return this.parameters.remove(index); + } + + @Override + public int indexOf(Object o) { + return this.parameters.indexOf(o); + } + + @Override + public int lastIndexOf(Object o) { + return this.parameters.lastIndexOf(o); + } + + @Override + public ListIterator listIterator() { + return this.listIterator(); + } + + @Override + public ListIterator listIterator(int index) { + return this.listIterator(index); + } + + @Override + public List subList(int fromIndex, int toIndex) { + return this.parameters.subList(fromIndex, toIndex); + } + @Override public boolean contains(Object parameter) { return this.parameters.contains(parameter); diff --git a/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java b/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java index 85dfa4d027dc7..e5a6805e9e1c7 100644 --- a/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java +++ b/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java @@ -31,7 +31,7 @@ */ public final class SqlQuerySpec extends JsonSerializable { - private SqlParameterCollection parameters; + private SqlParameterList parameters; /** * Initializes a new instance of the SqlQuerySpec class. @@ -59,7 +59,7 @@ public SqlQuerySpec(String queryText) { * @param queryText the query text. * @param parameters the query parameters. */ - public SqlQuerySpec(String queryText, SqlParameterCollection parameters) { + public SqlQuerySpec(String queryText, SqlParameterList parameters) { super(); this.queryText(queryText); this.parameters = parameters; @@ -91,14 +91,14 @@ public SqlQuerySpec queryText(String queryText) { * * @return the query parameters. */ - public SqlParameterCollection parameters() { + public SqlParameterList parameters() { if (this.parameters == null) { Collection sqlParameters = super.getCollection("parameters", SqlParameter.class); if (sqlParameters == null) { sqlParameters = new ArrayList(); } - this.parameters = new SqlParameterCollection(sqlParameters); + this.parameters = new SqlParameterList(sqlParameters); } return this.parameters; @@ -111,7 +111,7 @@ public SqlParameterCollection parameters() { * the query parameters. * @return the SqlQuerySpec. */ - public SqlQuerySpec parameters(SqlParameterCollection parameters) { + public SqlQuerySpec parameters(SqlParameterList parameters) { this.parameters = parameters; return this; } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java b/commons/src/main/java/com/azure/data/cosmos/UnauthorizedException.java similarity index 84% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java rename to commons/src/main/java/com/azure/data/cosmos/UnauthorizedException.java index d6ee5589bba0b..71d4ee151a6c1 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/UnauthorizedException.java +++ b/commons/src/main/java/com/azure/data/cosmos/UnauthorizedException.java @@ -21,11 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos; -import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.CosmosError; +import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.http.HttpHeaders; @@ -35,7 +33,7 @@ public class UnauthorizedException extends CosmosClientException { - public UnauthorizedException() { + UnauthorizedException() { this(RMResources.Unauthorized); } @@ -45,11 +43,11 @@ public UnauthorizedException(CosmosError cosmosError, long lsn, String partition BridgeInternal.setPartitionKeyRangeId(this, partitionKeyRangeId); } - public UnauthorizedException(String message) { + UnauthorizedException(String message) { this(message, null, null, null); } - public UnauthorizedException(String message, HttpHeaders headers, String requestUriString) { + UnauthorizedException(String message, HttpHeaders headers, String requestUriString) { this(message, null, headers, requestUriString); } @@ -57,11 +55,11 @@ public UnauthorizedException(String message, HttpHeaders headers, URI requestUri this(message, headers, requestUri != null ? requestUri.toString() : null); } - public UnauthorizedException(Exception innerException) { + UnauthorizedException(Exception innerException) { this(RMResources.Unauthorized, innerException, null, null); } - public UnauthorizedException(String message, + UnauthorizedException(String message, Exception innerException, HttpHeaders headers, String requestUri) { diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java index 0415be2f0bdba..a855e5d20c705 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.Strings; diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/TimeoutHelper.java b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/TimeoutHelper.java index 87820baba28d8..269c76f164b79 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/TimeoutHelper.java +++ b/commons/src/main/java/com/azure/data/cosmos/directconnectivity/TimeoutHelper.java @@ -23,6 +23,9 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.RequestTimeoutException; + import java.time.Duration; import java.time.Instant; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java b/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java index 2c0ca8ee3b100..c890b843f2e7b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.Attachment; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.Conflict; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Permission.java b/commons/src/main/java/com/azure/data/cosmos/internal/Permission.java index 8ba97f56453b2..bd14847bc6996 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/Permission.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Permission.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PermissionMode; import com.azure.data.cosmos.Resource; import com.fasterxml.jackson.databind.node.ArrayNode; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java b/commons/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java index b3d7ae3e1eb79..556491686f7df 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java @@ -26,6 +26,7 @@ import com.azure.data.cosmos.AccessCondition; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.IndexingDirective; +import com.azure.data.cosmos.PartitionKey; import java.util.HashMap; import java.util.List; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java b/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java index f67d210adff6e..bfa3a73274f8e 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java +++ b/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.DocumentCollection; import com.fasterxml.jackson.core.JsonParser; diff --git a/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java b/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java index ded954ac18370..12b15173cc756 100644 --- a/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java @@ -34,42 +34,42 @@ public class CosmosClientExceptionTest { @Test(groups = { "unit" }) public void headerNotNull1() { - CosmosClientException dce = new CosmosClientException(0); + CosmosClientException dce = BridgeInternal.createCosmosClientException(0); assertThat(dce.responseHeaders()).isNotNull(); assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull2() { - CosmosClientException dce = new CosmosClientException(0, "dummy"); + CosmosClientException dce = BridgeInternal.createCosmosClientException(0, "dummy"); assertThat(dce.responseHeaders()).isNotNull(); assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull3() { - CosmosClientException dce = new CosmosClientException(0, new RuntimeException()); + CosmosClientException dce = BridgeInternal.createCosmosClientException(0, new RuntimeException()); assertThat(dce.responseHeaders()).isNotNull(); assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull4() { - CosmosClientException dce = new CosmosClientException(0, (CosmosError) null, (Map) null); + CosmosClientException dce = BridgeInternal.createCosmosClientException(0, (CosmosError) null, (Map) null); assertThat(dce.responseHeaders()).isNotNull(); assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull5() { - CosmosClientException dce = new CosmosClientException((String) null, 0, (CosmosError) null, (Map) null); + CosmosClientException dce = BridgeInternal.createCosmosClientException((String) null, 0, (CosmosError) null, (Map) null); assertThat(dce.responseHeaders()).isNotNull(); assertThat(dce.responseHeaders()).isEmpty(); } @Test(groups = { "unit" }) public void headerNotNull6() { - CosmosClientException dce = new CosmosClientException((String) null, (Exception) null, (Map) null, 0, (String) null); + CosmosClientException dce = BridgeInternal.createCosmosClientException((String) null, (Exception) null, (Map) null, 0, (String) null); assertThat(dce.responseHeaders()).isNotNull(); assertThat(dce.responseHeaders()).isEmpty(); } @@ -77,7 +77,7 @@ public void headerNotNull6() { @Test(groups = { "unit" }) public void headerNotNull7() { ImmutableMap respHeaders = ImmutableMap.of("key", "value"); - CosmosClientException dce = new CosmosClientException((String) null, (Exception) null, respHeaders, 0, (String) null); + CosmosClientException dce = BridgeInternal.createCosmosClientException((String) null, (Exception) null, respHeaders, 0, (String) null); assertThat(dce.responseHeaders()).isNotNull(); assertThat(dce.responseHeaders()).contains(respHeaders.entrySet().iterator().next()); } diff --git a/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java b/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java index 55d9e51cacfa3..50eec6fa13355 100644 --- a/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java +++ b/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java @@ -22,7 +22,6 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.Permission; import org.testng.annotations.Test; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java index 6c6308a8a843d..043aca5d1ef4f 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java @@ -26,13 +26,14 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; -import com.azure.data.cosmos.internal.InternalServerErrorException; -import com.azure.data.cosmos.internal.InvalidPartitionException; -import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.InternalServerErrorException; +import com.azure.data.cosmos.InvalidPartitionException; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.ResourceId; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java index 9737533ae0eb3..d3e085d3f3515 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Strings; import reactor.core.publisher.Mono; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java index d0c7ea2013f05..bfe5e4dd465b0 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.PathsHelper; import com.azure.data.cosmos.internal.RMResources; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java index 2427dee230453..ebc83142ac6ee 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java @@ -26,12 +26,14 @@ import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.RequestTimeoutException; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java index 9dd94774451b8..62493cb91e5c1 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java @@ -26,7 +26,9 @@ import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.RequestTimeoutException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.Integers; @@ -39,7 +41,6 @@ import org.apache.commons.collections4.ComparatorUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import reactor.core.Exceptions; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java index e379ba7d1bbd1..4926462b93264 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java @@ -26,6 +26,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.Constants; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java index 779d125cafaca..7dab50fe5479d 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java @@ -23,12 +23,16 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.RetryWithException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IRetryPolicy; -import com.azure.data.cosmos.internal.InvalidPartitionException; -import com.azure.data.cosmos.internal.PartitionIsMigratingException; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.InvalidPartitionException; +import com.azure.data.cosmos.PartitionIsMigratingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.Quadruple; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.time.StopWatch; @@ -101,7 +105,7 @@ public Mono shouldRetry(Exception exception) { } else { logger.warn("Received gone exception after backoff/retry. Will fail the request. {}", exception.toString()); - exceptionToThrow = new CosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, + exceptionToThrow = BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception); } @@ -116,7 +120,7 @@ public Mono shouldRetry(Exception exception) { logger.warn( "Received partition key range gone exception after backoff/retry. Will fail the request. {}", exception.toString()); - exceptionToThrow = new CosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, + exceptionToThrow = BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception); } } else if (exception instanceof InvalidPartitionException) { @@ -129,7 +133,7 @@ public Mono shouldRetry(Exception exception) { logger.warn( "Received invalid collection partition exception after backoff/retry. Will fail the request. {}", exception.toString()); - exceptionToThrow = new CosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, + exceptionToThrow = BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception); } } else { @@ -167,7 +171,7 @@ public Mono shouldRetry(Exception exception) { logger.warn("Received second InvalidPartitionException after backoff/retry. Will fail the request. {}", exception.toString()); return Mono.just(ShouldRetryResult - .error(new CosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception))); + .error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.SERVICE_UNAVAILABLE, exception))); } if (this.request != null) { @@ -177,7 +181,7 @@ public Mono shouldRetry(Exception exception) { logger.error("Received unexpected invalid collection exception, request should be non-null.", exception); return Mono.just(ShouldRetryResult - .error(new CosmosClientException(HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, exception))); + .error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR, exception))); } forceRefreshAddressCache = false; } else if (exception instanceof PartitionKeyRangeIsSplittingException) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java index 80adf730058a3..2495fc154d231 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java @@ -57,7 +57,7 @@ private static Mono createDocumentClientException(HttpRes CosmosError cosmosError = BridgeInternal.createCosmosError(body); // TODO: we should set resource address in the Document Client Exception - return new CosmosClientException(httpResponse.statusCode(), cosmosError, + return BridgeInternal.createCosmosClientException(httpResponse.statusCode(), cosmosError, httpResponse.headers().toMap()); }); } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java index 1ddf45e6f89a4..24664a29ce060 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java @@ -24,20 +24,33 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ConflictException; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.BadRequestException; +import com.azure.data.cosmos.ForbiddenException; +import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.LockedException; +import com.azure.data.cosmos.MethodNotAllowedException; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.PreconditionFailedException; +import com.azure.data.cosmos.RequestEntityTooLargeException; +import com.azure.data.cosmos.RequestRateTooLargeException; +import com.azure.data.cosmos.RequestTimeoutException; +import com.azure.data.cosmos.RetryWithException; +import com.azure.data.cosmos.ServiceUnavailableException; +import com.azure.data.cosmos.UnauthorizedException; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Integers; -import com.azure.data.cosmos.internal.InternalServerErrorException; -import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.InternalServerErrorException; +import com.azure.data.cosmos.InvalidPartitionException; import com.azure.data.cosmos.internal.Lists; import com.azure.data.cosmos.internal.Longs; import com.azure.data.cosmos.internal.MutableVolatile; -import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.PartitionIsMigratingException; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.PartitionIsMigratingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.PathsHelper; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.ResourceType; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java index e3828f79d20db..39fd468c16dc4 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java @@ -26,9 +26,10 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.JavaStreamUtils; import com.azure.data.cosmos.internal.MutableVolatile; import com.azure.data.cosmos.internal.Quadruple; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java index 6ddc0bfcf83f9..ae119d14832eb 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java index e39b292c72a89..395ded73c5de6 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java index d782ccdc3aa0c..141dfd0b24edf 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.internal.BackoffRetryUtility; @@ -32,7 +33,7 @@ import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.IRetryPolicy; import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.ResourceType; @@ -113,7 +114,7 @@ public Mono processMessageAsync(RxDocumentServiceRequ return; } - exception.clientSideRequestStatistics(request.requestContext.clientSideRequestStatistics); + exception = BridgeInternal.setClientSideRequestStatistics(exception, request.requestContext.clientSideRequestStatistics); handleUnsuccessfulStoreResponse(request, exception); } catch (Throwable throwable) { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java index 14396dd22d3d0..f2815bcb4c499 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java @@ -26,16 +26,18 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.BadRequestException; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ISessionToken; import com.azure.data.cosmos.internal.Integers; -import com.azure.data.cosmos.internal.InternalServerErrorException; +import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.MutableVolatile; import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.PartitionIsMigratingException; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.PartitionIsMigratingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.SessionTokenHelper; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java index 89988d73dbef6..186c99766c3e2 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java @@ -26,27 +26,27 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosError; -import com.azure.data.cosmos.directconnectivity.ConflictException; -import com.azure.data.cosmos.directconnectivity.ForbiddenException; -import com.azure.data.cosmos.directconnectivity.GoneException; -import com.azure.data.cosmos.directconnectivity.LockedException; -import com.azure.data.cosmos.directconnectivity.MethodNotAllowedException; -import com.azure.data.cosmos.directconnectivity.PartitionKeyRangeGoneException; -import com.azure.data.cosmos.directconnectivity.PreconditionFailedException; -import com.azure.data.cosmos.directconnectivity.RequestEntityTooLargeException; -import com.azure.data.cosmos.directconnectivity.RequestRateTooLargeException; -import com.azure.data.cosmos.directconnectivity.RequestTimeoutException; -import com.azure.data.cosmos.directconnectivity.RetryWithException; -import com.azure.data.cosmos.directconnectivity.ServiceUnavailableException; +import com.azure.data.cosmos.ConflictException; +import com.azure.data.cosmos.ForbiddenException; +import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.LockedException; +import com.azure.data.cosmos.MethodNotAllowedException; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.PreconditionFailedException; +import com.azure.data.cosmos.RequestEntityTooLargeException; +import com.azure.data.cosmos.RequestRateTooLargeException; +import com.azure.data.cosmos.RequestTimeoutException; +import com.azure.data.cosmos.RetryWithException; +import com.azure.data.cosmos.ServiceUnavailableException; import com.azure.data.cosmos.directconnectivity.StoreResponse; -import com.azure.data.cosmos.directconnectivity.UnauthorizedException; +import com.azure.data.cosmos.UnauthorizedException; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; -import com.azure.data.cosmos.internal.BadRequestException; -import com.azure.data.cosmos.internal.InternalServerErrorException; -import com.azure.data.cosmos.internal.InvalidPartitionException; -import com.azure.data.cosmos.internal.NotFoundException; -import com.azure.data.cosmos.internal.PartitionIsMigratingException; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.BadRequestException; +import com.azure.data.cosmos.InternalServerErrorException; +import com.azure.data.cosmos.InvalidPartitionException; +import com.azure.data.cosmos.NotFoundException; +import com.azure.data.cosmos.PartitionIsMigratingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.google.common.base.Strings; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; @@ -743,7 +743,7 @@ private void messageReceived(final ChannelHandlerContext context, final RntbdRes break; default: - cause = new CosmosClientException(status.code(), cosmosError, responseHeaders); + cause = BridgeInternal.createCosmosClientException(status.code(), cosmosError, responseHeaders); break; } diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java index c315a0092136a..ce0b34d831dc9 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.directconnectivity.rntbd; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.directconnectivity.RequestTimeoutException; +import com.azure.data.cosmos.RequestTimeoutException; import com.azure.data.cosmos.directconnectivity.StoreResponse; import io.netty.util.Timeout; import io.netty.util.TimerTask; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java index 8f36c15095d8b..ad9128736795c 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java +++ b/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java @@ -25,7 +25,7 @@ package com.azure.data.cosmos.directconnectivity.rntbd; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.directconnectivity.GoneException; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.directconnectivity.RntbdTransportClient.Options; import com.azure.data.cosmos.internal.HttpConstants; import com.fasterxml.jackson.core.JsonGenerator; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java b/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java index 7b689595ff40d..bb40a6e61b63c 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java @@ -1,6 +1,5 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.fasterxml.jackson.databind.node.NullNode; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java index ab9fe1cf2cdcb..df7ea57d585b1 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java @@ -25,13 +25,14 @@ import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; -import com.azure.data.cosmos.internal.InvalidPartitionException; -import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.InvalidPartitionException; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java index 5c761c385ac79..2b1043a7dbb39 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.google.common.collect.ImmutableList; import org.mockito.Matchers; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java index 886552c564219..87f40978033db 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java @@ -26,13 +26,14 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.RequestRateTooLargeException; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceType; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java index 9592a9f64de05..334033c396825 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java @@ -25,10 +25,12 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.RequestTimeoutException; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.PartitionIsMigratingException; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.PartitionIsMigratingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.rx.FailureValidator; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ExceptionBuilder.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ExceptionBuilder.java index 467e8ece1e2ed..4535a4c89f3ae 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ExceptionBuilder.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ExceptionBuilder.java @@ -24,9 +24,11 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.InvalidPartitionException; -import com.azure.data.cosmos.internal.PartitionIsMigratingException; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.InvalidPartitionException; +import com.azure.data.cosmos.PartitionIsMigratingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import java.util.AbstractMap; import java.util.ArrayList; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java index 66dbeebb28e67..cbfa51e14a9e5 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java @@ -25,13 +25,14 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.BadRequestException; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IRetryPolicy; -import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.InvalidPartitionException; import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.PartitionIsMigratingException; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.PartitionIsMigratingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java index c96762623ffe9..7b4616bc61d9f 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java @@ -23,15 +23,28 @@ package com.azure.data.cosmos.directconnectivity; -import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.BadRequestException; +import com.azure.data.cosmos.ConflictException; +import com.azure.data.cosmos.ForbiddenException; +import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.LockedException; +import com.azure.data.cosmos.MethodNotAllowedException; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.PreconditionFailedException; +import com.azure.data.cosmos.RequestEntityTooLargeException; +import com.azure.data.cosmos.RequestRateTooLargeException; +import com.azure.data.cosmos.RequestTimeoutException; +import com.azure.data.cosmos.RetryWithException; +import com.azure.data.cosmos.ServiceUnavailableException; +import com.azure.data.cosmos.UnauthorizedException; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.InternalServerErrorException; -import com.azure.data.cosmos.internal.InvalidPartitionException; -import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.InternalServerErrorException; +import com.azure.data.cosmos.InvalidPartitionException; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.PartitionIsMigratingException; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.PartitionIsMigratingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.UserAgentContainer; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java index dc3417f3c8e3b..db5c22acae358 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.directconnectivity; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.Undefined; import com.azure.data.cosmos.internal.RMResources; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java index 73cbe8ab81234..4290a003925a2 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java @@ -25,13 +25,14 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.SessionContainer; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java index fa63170e95ed2..b67ddb000c98f 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java @@ -25,6 +25,7 @@ package com.azure.data.cosmos.directconnectivity; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java index 5c3932ee9840e..bc2fb9c95269a 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java @@ -23,7 +23,20 @@ package com.azure.data.cosmos.directconnectivity; +import com.azure.data.cosmos.ConflictException; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.ForbiddenException; +import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.LockedException; +import com.azure.data.cosmos.MethodNotAllowedException; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.PreconditionFailedException; +import com.azure.data.cosmos.RequestEntityTooLargeException; +import com.azure.data.cosmos.RequestRateTooLargeException; +import com.azure.data.cosmos.RequestTimeoutException; +import com.azure.data.cosmos.RetryWithException; +import com.azure.data.cosmos.ServiceUnavailableException; +import com.azure.data.cosmos.UnauthorizedException; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContext; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContextNegotiator; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContextRequest; @@ -37,14 +50,14 @@ import com.azure.data.cosmos.directconnectivity.rntbd.RntbdResponse; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdResponseDecoder; import com.azure.data.cosmos.directconnectivity.rntbd.RntbdUUID; -import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.InternalServerErrorException; -import com.azure.data.cosmos.internal.InvalidPartitionException; -import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.InternalServerErrorException; +import com.azure.data.cosmos.InvalidPartitionException; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.PartitionIsMigratingException; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.PartitionIsMigratingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.Paths; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java index 4def77e1f07f7..16ac64e9d50e4 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java @@ -25,7 +25,9 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.ServiceUnavailableException; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.ReplicationPolicy; import com.azure.data.cosmos.internal.AuthorizationTokenType; @@ -33,7 +35,7 @@ import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.InvalidPartitionException; +import com.azure.data.cosmos.InvalidPartitionException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceType; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java index 2ae0fb09dd9b9..cbedf41768d15 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java @@ -25,15 +25,18 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.RequestRateTooLargeException; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.DocumentServiceRequestContext; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.PartitionIsMigratingException; -import com.azure.data.cosmos.internal.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.PartitionIsMigratingException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java b/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java index d6d80a7a4f7ec..5812c55fe5928 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java +++ b/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.directconnectivity.GoneException; +import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.directconnectivity.StoreResponse; import com.azure.data.cosmos.directconnectivity.StoreResponseBuilder; import com.azure.data.cosmos.directconnectivity.StoreResponseValidator; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java index 4436f2f095000..3323a42999909 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java @@ -34,7 +34,7 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.ResourceResponse; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java index c406f95f8955b..ebdf0f6d85906 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java @@ -33,9 +33,9 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.SqlParameterList; import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.SqlParameterCollection; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; import org.apache.commons.lang3.RandomStringUtils; @@ -412,7 +412,7 @@ public void qrderBy_Async() throws Exception { } // Query for the documents order by the prop field - SqlQuerySpec query = new SqlQuerySpec("SELECT r.id FROM r ORDER BY r.prop", new SqlParameterCollection()); + SqlQuerySpec query = new SqlQuerySpec("SELECT r.id FROM r ORDER BY r.prop", new SqlParameterList()); FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); options.maxItemCount(5); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java index f295ccea9ae99..ddf6feee69bfc 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java @@ -33,7 +33,7 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.SqlParameter; -import com.azure.data.cosmos.SqlParameterCollection; +import com.azure.data.cosmos.SqlParameterList; import com.azure.data.cosmos.SqlQuerySpec; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -128,7 +128,7 @@ public void groupByInMemory() { Flux documentsObservable = client .queryDocuments(getCollectionLink(), new SqlQuerySpec("SELECT * FROM root r WHERE r.site_id=@site_id", - new SqlParameterCollection(new SqlParameter("@site_id", "ABC"))), + new SqlParameterList(new SqlParameter("@site_id", "ABC"))), options) .flatMap(page -> Flux.fromIterable(page.results())); @@ -160,7 +160,7 @@ public void groupByInMemory_MoreDetail() { Flux documentsObservable = client .queryDocuments(getCollectionLink(), new SqlQuerySpec("SELECT * FROM root r WHERE r.site_id=@site_id", - new SqlParameterCollection(new SqlParameter("@site_id", "ABC"))), + new SqlParameterList(new SqlParameter("@site_id", "ABC"))), options) .flatMap(page -> Flux.fromIterable(page.results())); diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java index 15c09e795818c..5351d24b18cb4 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java @@ -35,7 +35,7 @@ import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.StoredProcedure; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java index 5b32500712b35..bb7c7cb5a8a77 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java b/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java index 8a209afd5a739..583936a30b9dc 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java @@ -368,7 +368,7 @@ private Flux toDocumentServiceResponse(Mono 0, "query.parameters", "Unsupported argument in query compatibility mode '%s'", this.client.getQueryCompatibilityMode().toString()); diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java index d7462d9da288f..9531ae30c84a9 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java @@ -25,11 +25,11 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java index eebd28a4cfc69..4868801c15f3c 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java @@ -163,7 +163,7 @@ private void initialize( outOrderByContinuationToken)) { String message = String.format("INVALID JSON in continuation token %s for OrderBy~Context", continuationToken); - throw new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + throw BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, message); } @@ -175,7 +175,7 @@ private void initialize( if (compositeContinuationToken.getRange().isEmpty()) { String message = String.format("INVALID RANGE in the continuation token %s for OrderBy~Context.", continuationToken); - throw new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + throw BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, message); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java index 6917bec74b404..532b2db6f443e 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.internal.BadRequestException; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceId; import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java index 0fe81f7b2af86..7c820fa0b542c 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java @@ -141,7 +141,7 @@ private void initialize( outCompositeContinuationToken)) { String message = String.format("INVALID JSON in continuation token %s for Parallel~Context", continuationToken); - throw new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + throw BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, message); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java index 27a62159690f0..43236c5165c0c 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos.internal.query; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; @@ -129,7 +130,7 @@ protected int FindTargetRangeAndExtractContinuationTokens( } if (minIndex == partitionKeyRanges.size()) { - throw new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + throw BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, String.format("Could not find partition key range for continuation token: {0}", needle)); } diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java index 8ec81cbf7063b..f169b94ff5bdf 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java +++ b/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java @@ -58,7 +58,7 @@ public static Flux> cre if (!TakeContinuationToken.tryParse(topContinuationToken, outTakeContinuationToken)) { String message = String.format("INVALID JSON in continuation token %s for Top~Context", topContinuationToken); - CosmosClientException dce = new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + CosmosClientException dce = BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, message); return Flux.error(dce); } @@ -70,7 +70,7 @@ public static Flux> cre String message = String.format( "top count in continuation token: %d can not be greater than the top count in the query: %d.", takeContinuationToken.getTakeCount(), topCount); - CosmosClientException dce = new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, message); + CosmosClientException dce = BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, message); return Flux.error(dce); } diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java index 8f6199c7db4de..1d145a0ae702e 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java @@ -22,9 +22,11 @@ */ package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import io.netty.handler.timeout.ReadTimeoutException; diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java b/gateway/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java index db1645fadcf42..13299080d0978 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java +++ b/gateway/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.InternalServerErrorException; import org.testng.annotations.Test; import static com.azure.data.cosmos.internal.Utils.ValueHolder; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index b73d413f1bd18..e60a4697c1773 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -450,7 +450,7 @@ public Mono readProvisionedThroughput() { + cosmosContainerResponse.resourceSettings().resourceId() + "'", new FeedOptions()) .single()).flatMap(offerFeedResponse -> { if (offerFeedResponse.results().isEmpty()) { - return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + return Mono.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return database.getDocClientWrapper().readOffer(offerFeedResponse.results().get(0).selfLink()) @@ -472,7 +472,7 @@ public Mono replaceProvisionedThroughput(int requestUnitsPerSecond) { + cosmosContainerResponse.resourceSettings().resourceId() + "'", new FeedOptions()) .single()).flatMap(offerFeedResponse -> { if (offerFeedResponse.results().isEmpty()) { - return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + return Mono.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.results().get(0); diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java index d1c918b327af9..b51bf62ec4adf 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java @@ -418,7 +418,7 @@ public Mono readProvisionedThroughput() { + cosmosDatabaseResponse.resourceSettings().resourceId() + "'", new FeedOptions()) .single().flatMap(offerFeedResponse -> { if (offerFeedResponse.results().isEmpty()) { - return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + return Mono.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } return getDocClientWrapper().readOffer(offerFeedResponse.results().get(0).selfLink()).single(); @@ -439,7 +439,7 @@ public Mono replaceProvisionedThroughput(int requestUnitsPerSecond) { + cosmosDatabaseResponse.resourceSettings().resourceId() + "'", new FeedOptions()) .single().flatMap(offerFeedResponse -> { if (offerFeedResponse.results().isEmpty()) { - return Mono.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, + return Mono.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, "No offers found for the resource")); } Offer offer = offerFeedResponse.results().get(0); diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java index d014981022d16..d98cca0b42bd9 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java @@ -22,7 +22,6 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.ResourceResponse; public class CosmosItemResponse extends CosmosResponse{ diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java index 63d93aa0ed2b7..88aa2534af423 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Constants; -import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.Permission; import org.apache.commons.lang3.StringUtils; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java index 1cfed79c8bb54..0fa8465ed6c7c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java @@ -40,6 +40,7 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.JsonSerializable; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java index 63871ab24ebe7..a76199b3b968b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.NotFoundException; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java index 2fcc5460e045e..dafb72dd3f601 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.SqlParameter; -import com.azure.data.cosmos.SqlParameterCollection; +import com.azure.data.cosmos.SqlParameterList; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; import com.azure.data.cosmos.internal.changefeed.Lease; @@ -416,7 +416,7 @@ private Flux listDocuments(String prefix) { param.value(prefix); SqlQuerySpec querySpec = new SqlQuerySpec( "SELECT * FROM c WHERE STARTSWITH(c.id, @PartitionLeasePrefix)", - new SqlParameterCollection(param)); + new SqlParameterList(param)); Flux> query = this.leaseDocumentClient.queryItems( this.settings.getLeaseCollectionLink(), diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java index d266711ad08f0..c0fb1fcaf04c6 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.internal.changefeed.Lease; import com.azure.data.cosmos.internal.changefeed.RequestOptionsFactory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java index 172cc349a761a..dd9266c790445 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java @@ -103,7 +103,7 @@ public static void cleanupStaleTestDatabases(DatabaseManager client) { logger.info("Cleaning stale test databases ..."); List dbs = client.queryDatabases( new SqlQuerySpec("SELECT * FROM c WHERE STARTSWITH(c.id, @PREFIX)", - new SqlParameterCollection(new SqlParameter("@PREFIX", CosmosDatabaseForTest.SHARED_DB_ID_PREFIX)))) + new SqlParameterList(new SqlParameter("@PREFIX", CosmosDatabaseForTest.SHARED_DB_ID_PREFIX)))) .flatMap(page -> Flux.fromIterable(page.results())).collectList().block(); for (CosmosDatabaseProperties db : dbs) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java index 4a6532b4964db..82e3908bf3b55 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java @@ -26,7 +26,6 @@ import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.PartitionKey; import com.azure.data.cosmos.internal.Paths; import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.ResourceType; diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java index 46cc003ed89ef..b064991e51995 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.internal.StoredProcedure; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java index 24b0c41e28782..6dbd216ba97e3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java @@ -29,6 +29,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKind; import com.azure.data.cosmos.rx.FailureValidator; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java index 34258ab7e22f0..df7048f27c722 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java @@ -33,6 +33,7 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.rx.FailureValidator; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java index 214cb8f65b4f4..6d26342c51c1f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java @@ -34,6 +34,7 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKind; import com.azure.data.cosmos.Resource; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java index d0c644f44338c..9ed9aed385d3d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java @@ -29,6 +29,7 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.SpyClientBuilder; import com.azure.data.cosmos.internal.http.HttpRequest; import com.azure.data.cosmos.rx.Utils; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java index 38a90e3229e03..3620b59fa2c5a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.Database; @@ -85,7 +86,7 @@ public void retryDocumentCreate() throws Exception { HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_MISMATCH)); - return Flux.error(new CosmosClientException(HttpConstants.StatusCodes.BADREQUEST, new CosmosError() , header)); + return Flux.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.BADREQUEST, new CosmosError() , header)); } else { return client.getOrigGatewayStoreModel().processMessage(req); } @@ -116,7 +117,7 @@ public void createDocument_noRetryOnNonRetriableFailure() throws Exception { HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(2)); - return Flux.error(new CosmosClientException(1, new CosmosError() , header)); + return Flux.error(BridgeInternal.createCosmosClientException(1, new CosmosError() , header)); } }).when(client.getSpyGatewayStoreModel()).processMessage(anyObject()); @@ -152,7 +153,7 @@ public void createDocument_failImmediatelyOnNonRetriable() throws Exception { HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(2)); - return Flux.error(new CosmosClientException(1, new CosmosError() , header)); + return Flux.error(BridgeInternal.createCosmosClientException(1, new CosmosError() , header)); } else { return client.getOrigGatewayStoreModel().processMessage(req); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java index cc5ff81ae207d..df6a96f1f23ed 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java @@ -24,6 +24,7 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; @@ -123,7 +124,7 @@ public void retryDocumentCreate() throws Exception { } int currentAttempt = count.getAndIncrement(); if (currentAttempt == 0) { - return Flux.error(new CosmosClientException(HttpConstants.StatusCodes.TOO_MANY_REQUESTS)); + return Flux.error(BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.TOO_MANY_REQUESTS)); } else { return client.getOrigGatewayStoreModel().processMessage(req); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java index ada7f6b7cb299..08c6f759f8531 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java @@ -28,6 +28,7 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.http.HttpRequest; import io.netty.handler.codec.http.HttpMethod; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index a678d2615dc88..bdb9c5c3c59ba 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -42,6 +42,7 @@ import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.RetryOptions; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java index ef6c3a8f489ae..57854fe55438b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java @@ -737,7 +737,7 @@ private static CosmosClientException partitionKeyRangeGoneException() { Map headers = new HashMap<>(); headers.put(HttpConstants.HttpHeaders.SUB_STATUS, Integer.toString(HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE)); - return new CosmosClientException(HttpConstants.StatusCodes.GONE, new CosmosError(), headers); + return BridgeInternal.createCosmosClientException(HttpConstants.StatusCodes.GONE, new CosmosError(), headers); } protected void capture(String partitionId, CapturedInvocation captureInvocation) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java index 60d1158452289..edec9a5e57483 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.Resource; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java index 262834c40dde8..ed4d79dba1c25 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java @@ -41,7 +41,7 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.IndexingMode; import com.azure.data.cosmos.IndexingPolicy; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.RetryAnalyzer; import com.azure.data.cosmos.SpatialSpec; @@ -54,7 +54,6 @@ import reactor.core.publisher.Mono; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import java.util.UUID; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java index 7e7586414cb08..8277ce0fe73dd 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.CosmosResponseValidator; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java index 7815f04194e89..7b72e8ff0ed32 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.RetryAnalyzer; import com.azure.data.cosmos.internal.Utils.ValueHolder; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java index 166d8a773b883..7dc535fd7c78c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java @@ -61,7 +61,7 @@ public void readFeedException() throws Exception { frps.add(BridgeInternal.createFeedResponse(dbs, null)); Flux> response = Flux.merge(Flux.fromIterable(frps)) - .mergeWith(Flux.error(new CosmosClientException(0))) + .mergeWith(Flux.error(BridgeInternal.createCosmosClientException(0))) .mergeWith(Flux.fromIterable(frps)); final CosmosClient mockClient = Mockito.spy(client); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java index 1dc22790dd92b..4c5937ccbf289 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java index ad21c0e824b69..9562960df550f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.SqlParameter; -import com.azure.data.cosmos.SqlParameterCollection; +import com.azure.data.cosmos.SqlParameterList; import com.azure.data.cosmos.SqlQuerySpec; import io.reactivex.subscribers.TestSubscriber; import org.testng.annotations.AfterClass; @@ -96,7 +96,7 @@ public void queryDocuments(boolean queryMetricsEnabled) throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryDocuments_ParameterizedQueryWithInClause() throws Exception { String query = "SELECT * from c where c.prop IN (@param1, @param2)"; - SqlParameterCollection params = new SqlParameterCollection(new SqlParameter("@param1", 3), new SqlParameter("@param2", 4)); + SqlParameterList params = new SqlParameterList(new SqlParameter("@param1", 3), new SqlParameter("@param2", 4)); SqlQuerySpec sqs = new SqlQuerySpec(query, params); FeedOptions options = new FeedOptions(); @@ -123,7 +123,7 @@ public void queryDocuments_ParameterizedQueryWithInClause() throws Exception { @Test(groups = { "simple" }, timeOut = TIMEOUT) public void queryDocuments_ParameterizedQuery() throws Exception { String query = "SELECT * from c where c.prop = @param"; - SqlParameterCollection params = new SqlParameterCollection(new SqlParameter("@param", 3)); + SqlParameterList params = new SqlParameterList(new SqlParameter("@param", 3)); SqlQuerySpec sqs = new SqlQuerySpec(query, params); FeedOptions options = new FeedOptions(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java index 98998b47be187..5639ef21df480 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java @@ -31,7 +31,7 @@ import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; import com.azure.data.cosmos.CosmosStoredProcedureResponse; import com.azure.data.cosmos.CosmosStoredProcedureProperties; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.internal.RequestOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index 4b3cbe6718c41..61611e66a056d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -54,7 +54,7 @@ import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.RetryOptions; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java index 6bbe2832405ef..07380bdb41fda 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java @@ -35,7 +35,7 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; import com.azure.data.cosmos.internal.RequestOptions; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java index e7f86f0956ae6..81acc28ad5b60 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java @@ -29,7 +29,7 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.RetryAnalyzer; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.TakeContinuationToken; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java index 93bbe83862abe..31b2de8c32c7a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java @@ -39,7 +39,7 @@ import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.IndexingMode; import com.azure.data.cosmos.IndexingPolicy; -import com.azure.data.cosmos.internal.PartitionKey; +import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.UniqueKey; import com.azure.data.cosmos.UniqueKeyPolicy; From 801607454120ab8773a2f4234b61f53a63398e21 Mon Sep 17 00:00:00 2001 From: Christopher Anderson Date: Thu, 27 Jun 2019 19:00:01 -0700 Subject: [PATCH 54/85] Merge packages into SDK (#214) * merge modules * fix tests * move direct mode internal * Optimized imports, fixed dependencies for benchmarks and sdk --- benchmark/pom.xml | 4 - .../data/cosmos/benchmark/AsyncBenchmark.java | 2 +- .../cosmos/benchmark/ReadMyWriteWorkflow.java | 8 +- benchmark/src/main/resources/log4j.properties | 2 +- .../ReadMyWritesConsistencyTest.java | 2 +- .../azure/data/cosmos/benchmark/Utils.java | 4 +- .../data/cosmos/benchmark/WorkflowTest.java | 2 +- commons-test-utils/pom.xml | 159 -------- .../azure/data/cosmos/ConfigsBuilderTest.java | 51 --- .../src/main/tests/resources/log4j.properties | 15 - commons/pom.xml | 223 ------------ .../com/azure/data/cosmos/package-info.java | 28 -- commons/src/test/resources/log4j.properties | 16 - direct-impl/pom.xml | 341 ------------------ .../src/test/resources/log4j.properties | 16 - examples/pom.xml | 4 - .../ChangeFeed/SampleChangeFeedProcessor.java | 1 - .../multimaster/samples/ConflictWorker.java | 2 +- .../azure/data/cosmos/rx/examples/Utils.java | 4 +- gateway/pom.xml | 149 -------- .../azure/cosmosdb/internal/RetryPolicy.java | 36 -- gateway/src/test/resources/log4j.properties | 15 - pom.xml | 52 --- sdk/pom.xml | 48 ++- .../azure/data/cosmos/AccessCondition.java | 0 .../data/cosmos/AccessConditionType.java | 0 .../com/azure/data/cosmos/Attachment.java | 0 .../data/cosmos/BadRequestException.java | 2 +- .../com/azure/data/cosmos/BridgeInternal.java | 0 .../azure/data/cosmos/ChangeFeedOptions.java | 0 .../data/cosmos/ChangeFeedProcessor.java | 1 - .../cosmos/ChangeFeedProcessorOptions.java | 2 - .../cosmos/ClientSideRequestStatistics.java | 2 +- .../data/cosmos/CommonsBridgeInternal.java | 0 .../com/azure/data/cosmos/CompositePath.java | 0 .../data/cosmos/CompositePathSortOrder.java | 0 .../java/com/azure/data/cosmos/Conflict.java | 0 .../azure/data/cosmos/ConflictException.java | 2 +- .../data/cosmos/ConflictResolutionMode.java | 0 .../data/cosmos/ConflictResolutionPolicy.java | 0 .../com/azure/data/cosmos/ConnectionMode.java | 0 .../azure/data/cosmos/ConnectionPolicy.java | 0 .../azure/data/cosmos/ConsistencyLevel.java | 0 .../azure/data/cosmos/ConsistencyPolicy.java | 0 .../data/cosmos/CosmosClientException.java | 0 .../azure/data/cosmos/CosmosContainer.java | 3 - .../cosmos/CosmosContainerProperties.java | 0 .../cosmos/CosmosContainerRequestOptions.java | 0 .../data/cosmos/CosmosDatabaseProperties.java | 0 .../cosmos/CosmosDatabaseRequestOptions.java | 0 .../com/azure/data/cosmos/CosmosError.java | 0 .../azure/data/cosmos/CosmosFeedResponse.java | 0 .../data/cosmos/CosmosItemProperties.java | 0 .../data/cosmos/CosmosItemRequestOptions.java | 0 .../data/cosmos/CosmosRequestOptions.java | 0 .../azure/data/cosmos/CosmosResourceType.java | 0 .../com/azure/data/cosmos/CosmosResponse.java | 0 .../CosmosStoredProcedureProperties.java | 0 .../CosmosStoredProcedureRequestOptions.java | 0 .../data/cosmos/CosmosTriggerProperties.java | 0 .../CosmosUserDefinedFunctionProperties.java | 0 .../data/cosmos/CosmosUserProperties.java | 0 .../java/com/azure/data/cosmos/DataType.java | 0 .../java/com/azure/data/cosmos/Database.java | 0 .../azure/data/cosmos/DatabaseAccount.java | 0 .../data/cosmos/DatabaseAccountLocation.java | 0 .../DatabaseAccountManagerInternal.java | 0 .../java/com/azure/data/cosmos/Document.java | 0 .../azure/data/cosmos/DocumentCollection.java | 0 .../com/azure/data/cosmos/ExcludedPath.java | 0 .../com/azure/data/cosmos/FeedOptions.java | 0 .../com/azure/data/cosmos/FeedResponse.java | 0 .../azure/data/cosmos/ForbiddenException.java | 2 +- .../com/azure/data/cosmos/GoneException.java | 2 +- .../java/com/azure/data/cosmos/HashIndex.java | 0 .../azure/data/cosmos/ISessionContainer.java | 0 .../com/azure/data/cosmos/IncludedPath.java | 0 .../java/com/azure/data/cosmos/Index.java | 0 .../java/com/azure/data/cosmos/IndexKind.java | 0 .../azure/data/cosmos/IndexingDirective.java | 0 .../com/azure/data/cosmos/IndexingMode.java | 0 .../com/azure/data/cosmos/IndexingPolicy.java | 0 .../cosmos/InternalServerErrorException.java | 2 +- .../cosmos/InvalidPartitionException.java | 4 +- .../azure/data/cosmos/JsonSerializable.java | 0 .../azure/data/cosmos/LockedException.java | 2 +- .../cosmos/MethodNotAllowedException.java | 2 +- .../azure/data/cosmos/NotFoundException.java | 2 +- .../cosmos/PartitionIsMigratingException.java | 4 +- .../com/azure/data/cosmos/PartitionKey.java | 0 .../data/cosmos/PartitionKeyDefinition.java | 0 .../cosmos/PartitionKeyDefinitionVersion.java | 0 .../PartitionKeyRangeGoneException.java | 4 +- ...PartitionKeyRangeIsSplittingException.java | 4 +- .../com/azure/data/cosmos/PartitionKind.java | 0 .../com/azure/data/cosmos/PermissionMode.java | 0 .../cosmos/PreconditionFailedException.java | 2 +- .../com/azure/data/cosmos/RangeIndex.java | 0 .../RequestEntityTooLargeException.java | 2 +- .../cosmos/RequestRateTooLargeException.java | 2 +- .../data/cosmos/RequestTimeoutException.java | 2 +- .../java/com/azure/data/cosmos/Resource.java | 0 .../com/azure/data/cosmos/RetryOptions.java | 0 .../azure/data/cosmos/RetryWithException.java | 2 +- .../cosmos/SerializationFormattingPolicy.java | 0 .../cosmos/ServiceUnavailableException.java | 2 +- .../com/azure/data/cosmos/SpatialIndex.java | 0 .../com/azure/data/cosmos/SpatialSpec.java | 0 .../com/azure/data/cosmos/SpatialType.java | 0 .../com/azure/data/cosmos/SqlParameter.java | 0 .../azure/data/cosmos/SqlParameterList.java | 0 .../com/azure/data/cosmos/SqlQuerySpec.java | 0 .../com/azure/data/cosmos/TokenResolver.java | 0 .../azure/data/cosmos/TriggerOperation.java | 0 .../com/azure/data/cosmos/TriggerType.java | 0 .../data/cosmos/UnauthorizedException.java | 2 +- .../java/com/azure/data/cosmos/Undefined.java | 0 .../java/com/azure/data/cosmos/UniqueKey.java | 0 .../azure/data/cosmos/UniqueKeyPolicy.java | 0 .../internal/AuthorizationTokenProvider.java | 0 .../internal/AuthorizationTokenType.java | 0 .../cosmos/internal/BackoffRetryUtility.java | 0 .../BaseAuthorizationTokenProvider.java | 2 +- ...eDatabaseAccountConfigurationProvider.java | 0 .../com/azure/data/cosmos/internal/Bytes.java | 0 ...ringSessionContainerClientRetryPolicy.java | 0 .../cosmos/internal/ClientRetryPolicy.java | 2 +- .../azure/data/cosmos/internal/Configs.java | 2 +- .../azure/data/cosmos/internal/Constants.java | 0 .../internal/ContentSerializationFormat.java | 0 .../DatabaseAccountConfigurationProvider.java | 0 .../cosmos/internal}/DatabaseForTest.java | 14 +- .../DocumentServiceRequestContext.java | 6 +- .../cosmos/internal/EnumerationDirection.java | 0 .../data/cosmos/internal/Exceptions.java | 0 .../cosmos/internal/FanoutOperationState.java | 0 .../internal/GlobalEndpointManager.java | 0 .../data/cosmos/internal/HttpConstants.java | 0 .../internal/IAuthorizationTokenProvider.java | 0 .../internal/ICollectionRoutingMapCache.java | 0 .../internal/IDocumentClientRetryPolicy.java | 0 .../data/cosmos/internal/IRetryPolicy.java | 0 .../cosmos/internal/IRetryPolicyFactory.java | 0 .../cosmos/internal/IRoutingMapProvider.java | 0 .../data/cosmos/internal/ISessionToken.java | 0 .../azure/data/cosmos/internal/Integers.java | 0 .../cosmos/internal/InternalConstants.java | 0 .../InvalidPartitionExceptionRetryPolicy.java | 0 .../data/cosmos/internal/JavaStreamUtils.java | 0 .../data/cosmos/internal/LifeCycleUtils.java | 0 .../com/azure/data/cosmos/internal/Lists.java | 0 .../com/azure/data/cosmos/internal/Longs.java | 0 .../data/cosmos/internal/MediaReadMode.java | 0 .../internal/MigrateCollectionDirective.java | 0 .../data/cosmos/internal/MutableVolatile.java | 0 .../cosmos/internal/ObservableHelper.java | 0 .../com/azure/data/cosmos/internal/Offer.java | 0 .../data/cosmos/internal/OperationType.java | 0 .../PartitionKeyMismatchRetryPolicy.java | 0 .../cosmos/internal/PartitionKeyRange.java | 0 .../PartitionKeyRangeGoneRetryPolicy.java | 0 .../azure/data/cosmos/internal/PathInfo.java | 0 .../data/cosmos/internal/PathParser.java | 0 .../com/azure/data/cosmos/internal/Paths.java | 0 .../data/cosmos/internal/PathsHelper.java | 0 .../data/cosmos/internal/Permission.java | 0 .../azure/data/cosmos/internal/Quadruple.java | 0 .../internal/QueryCompatibilityMode.java | 0 .../data/cosmos/internal/QueryMetrics.java | 0 .../internal/QueryMetricsConstants.java | 0 .../cosmos/internal/QueryMetricsUtils.java | 0 .../internal/QueryPreparationTimes.java | 0 .../data/cosmos/internal/RMResources.java | 0 .../data/cosmos/internal/ReadFeedKeyType.java | 0 .../cosmos/internal/RemoteStorageType.java | 0 ...enameCollectionAwareClientRetryPolicy.java | 0 .../ReplicatedResourceClientUtils.java | 0 .../cosmos/internal/ReplicationPolicy.java | 0 .../cosmos/internal/RequestChargeTracker.java | 0 .../data/cosmos/internal/RequestOptions.java | 0 .../ResetSessionTokenRetryPolicyFactory.java | 0 .../data/cosmos/internal/ResourceId.java | 0 .../cosmos/internal/ResourceResponse.java | 3 - .../internal/ResourceThrottleRetryPolicy.java | 0 .../ResourceTokenAuthorizationHelper.java | 0 .../data/cosmos/internal/ResourceType.java | 0 .../data/cosmos/internal/RetryPolicy.java | 0 .../data/cosmos/internal/RetryUtils.java | 0 .../cosmos/internal/RuntimeConstants.java | 0 .../internal/RuntimeExecutionTimes.java | 0 .../cosmos/internal/RxDocumentClientImpl.java | 8 +- .../internal/RxDocumentServiceRequest.java | 2 +- .../internal/RxDocumentServiceResponse.java | 4 +- .../cosmos/internal/RxGatewayStoreModel.java | 4 +- .../data/cosmos/internal/RxStoreModel.java | 0 .../cosmos/internal/SessionContainer.java | 0 .../cosmos/internal/SessionTokenHelper.java | 0 .../data/cosmos/internal/StoredProcedure.java | 0 .../internal/StoredProcedureResponse.java | 0 .../azure/data/cosmos/internal/Strings.java | 0 .../cosmos/internal}/TestConfigurations.java | 2 +- .../azure/data/cosmos/internal/Trigger.java | 0 .../com/azure/data/cosmos/internal/User.java | 0 .../cosmos/internal/UserAgentContainer.java | 0 .../cosmos/internal/UserDefinedFunction.java | 0 .../com/azure/data/cosmos/internal/Utils.java | 0 .../cosmos/internal/VectorSessionToken.java | 0 .../internal/WebExceptionRetryPolicy.java | 2 +- .../cosmos/internal/caches/AsyncCache.java | 0 .../cosmos/internal/caches/AsyncLazy.java | 1 - .../internal/caches/IEqualityComparer.java | 0 .../caches/IPartitionKeyRangeCache.java | 2 +- .../caches/RxClientCollectionCache.java | 0 .../internal/caches/RxCollectionCache.java | 0 .../caches/RxPartitionKeyRangeCache.java | 4 +- .../changefeed/ChangeFeedContextClient.java | 4 +- .../internal/changefeed/ServiceItemLease.java | 3 +- .../implementation/AutoCheckpointer.java | 2 +- .../ChangeFeedContextClientImpl.java | 4 +- .../ChangeFeedObserverContextImpl.java | 2 +- .../ChangeFeedProcessorBuilderImpl.java | 6 +- ...onWrappingChangeFeedObserverDecorator.java | 2 +- .../PartitionProcessorFactoryImpl.java | 2 +- .../PartitionProcessorImpl.java | 4 +- .../PartitionSupervisorFactoryImpl.java | 2 +- .../PartitionSupervisorImpl.java | 4 +- .../changefeed/implementation/WorkerTask.java | 1 - .../internal}/directconnectivity/Address.java | 2 +- .../AddressInformation.java | 2 +- .../directconnectivity/AddressResolver.java | 12 +- .../directconnectivity/AddressSelector.java | 2 +- .../BarrierRequestHelper.java | 4 +- .../directconnectivity/ConsistencyReader.java | 8 +- .../directconnectivity/ConsistencyWriter.java | 2 +- .../directconnectivity/CustomHeaders.java | 2 +- .../directconnectivity/ErrorUtils.java | 3 +- .../GatewayAddressCache.java | 8 +- .../GatewayServiceConfigurationReader.java | 4 +- .../GlobalAddressResolver.java | 8 +- .../GoneAndRetryWithRetryPolicy.java | 8 +- .../directconnectivity/HttpClientUtils.java | 2 +- .../HttpTransportClient.java | 14 +- .../directconnectivity/HttpUtils.java | 2 +- .../directconnectivity/IAddressCache.java | 2 +- .../directconnectivity/IAddressResolver.java | 2 +- .../directconnectivity/IStoreClient.java | 2 +- .../directconnectivity/Protocol.java | 2 +- .../QueryRequestPerformanceActivity.java | 2 +- .../directconnectivity/QuorumReader.java | 4 +- .../directconnectivity/ReadMode.java | 2 +- .../ReplicatedResourceClient.java | 2 +- .../directconnectivity/RequestHelper.java | 4 +- .../directconnectivity/ResourceOperation.java | 2 +- .../directconnectivity/ResponseUtils.java | 2 +- .../RntbdTransportClient.java | 16 +- .../directconnectivity/ServerProperties.java | 2 +- .../directconnectivity/ServerStoreModel.java | 4 +- .../directconnectivity/ServiceConfig.java | 2 +- .../directconnectivity/StoreClient.java | 4 +- .../StoreClientFactory.java | 2 +- .../directconnectivity/StoreReader.java | 10 +- .../directconnectivity/StoreResponse.java | 2 +- .../directconnectivity/StoreResult.java | 4 +- .../directconnectivity/TimeoutHelper.java | 2 +- .../directconnectivity/TransportClient.java | 2 +- .../TransportException.java | 2 +- .../directconnectivity/WFConstants.java | 2 +- .../WebExceptionUtility.java | 2 +- .../rntbd/RntbdClientChannelHandler.java | 2 +- .../rntbd/RntbdClientChannelPool.java | 6 +- .../rntbd/RntbdConstants.java | 2 +- .../rntbd/RntbdContext.java | 8 +- .../rntbd/RntbdContextDecoder.java | 2 +- .../rntbd/RntbdContextException.java | 4 +- .../rntbd/RntbdContextNegotiator.java | 2 +- .../rntbd/RntbdContextRequest.java | 10 +- .../rntbd/RntbdContextRequestDecoder.java | 2 +- .../rntbd/RntbdContextRequestEncoder.java | 2 +- .../rntbd/RntbdEndpoint.java | 4 +- .../directconnectivity/rntbd/RntbdFramer.java | 2 +- .../rntbd/RntbdMetrics.java | 2 +- .../rntbd/RntbdObjectMapper.java | 2 +- .../rntbd/RntbdReporter.java | 2 +- .../rntbd/RntbdRequest.java | 4 +- .../rntbd/RntbdRequestArgs.java | 2 +- .../rntbd/RntbdRequestDecoder.java | 2 +- .../rntbd/RntbdRequestEncoder.java | 2 +- .../rntbd/RntbdRequestFrame.java | 6 +- .../rntbd/RntbdRequestFramer.java | 2 +- .../rntbd/RntbdRequestHeaders.java | 24 +- .../rntbd/RntbdRequestManager.java | 24 +- .../rntbd/RntbdRequestRecord.java | 4 +- .../rntbd/RntbdRequestTimer.java | 2 +- .../rntbd/RntbdResponse.java | 6 +- .../rntbd/RntbdResponseDecoder.java | 2 +- .../rntbd/RntbdResponseHeaders.java | 8 +- .../rntbd/RntbdResponseStatus.java | 2 +- .../rntbd/RntbdServiceEndpoint.java | 4 +- .../directconnectivity/rntbd/RntbdToken.java | 4 +- .../rntbd/RntbdTokenStream.java | 4 +- .../rntbd/RntbdTokenType.java | 2 +- .../directconnectivity/rntbd/RntbdUUID.java | 2 +- .../internal/http/BufferedHttpResponse.java | 0 .../data/cosmos/internal/http/HttpClient.java | 0 .../internal/http/HttpClientConfig.java | 0 .../data/cosmos/internal/http/HttpHeader.java | 0 .../cosmos/internal/http/HttpHeaders.java | 0 .../cosmos/internal/http/HttpRequest.java | 0 .../cosmos/internal/http/HttpResponse.java | 0 .../internal/http/ReactorNettyClient.java | 0 ...ggregateDocumentQueryExecutionContext.java | 2 +- .../query/CompositeContinuationToken.java | 0 .../DefaultDocumentQueryExecutionContext.java | 4 +- .../internal/query/DocumentProducer.java | 6 +- .../DocumentQueryExecutionContextBase.java | 6 +- .../DocumentQueryExecutionContextFactory.java | 4 +- .../internal/query/ExceptionHelper.java | 0 .../data/cosmos/internal/query/Fetcher.java | 4 +- .../internal/query/IDocumentQueryClient.java | 0 .../IDocumentQueryExecutionComponent.java | 0 .../query/IDocumentQueryExecutionContext.java | 0 .../cosmos/internal/query/ItemComparator.java | 0 .../data/cosmos/internal/query/ItemType.java | 0 .../cosmos/internal/query/ItemTypeHelper.java | 0 .../query/OrderByContinuationToken.java | 0 .../query/OrderByDocumentProducer.java | 4 +- .../OrderByDocumentQueryExecutionContext.java | 4 +- .../cosmos/internal/query/OrderByUtils.java | 4 +- .../data/cosmos/internal/query/Paginator.java | 0 ...ParallelDocumentQueryExecutionContext.java | 2 +- ...llelDocumentQueryExecutionContextBase.java | 2 +- .../internal/query/ParallelQueryConfig.java | 0 .../query/PartitionedQueryExecutionInfo.java | 0 ...PartitionedQueryExecutionInfoInternal.java | 0 ...ipelinedDocumentQueryExecutionContext.java | 2 +- .../ProxyDocumentQueryExecutionContext.java | 2 +- .../data/cosmos/internal/query/QueryInfo.java | 0 .../data/cosmos/internal/query/QueryItem.java | 0 .../data/cosmos/internal/query/SortOrder.java | 0 .../internal/query/TakeContinuationToken.java | 0 .../TopDocumentQueryExecutionContext.java | 0 .../cosmos/internal/query/TriFunction.java | 0 .../query/aggregation/AggregateOperator.java | 0 .../query/aggregation/Aggregator.java | 0 .../query/aggregation/AverageAggregator.java | 0 .../query/aggregation/CountAggregator.java | 0 .../query/aggregation/MaxAggregator.java | 0 .../query/aggregation/MinAggregator.java | 0 .../query/aggregation/SumAggregator.java | 0 .../query/metrics/ClientSideMetrics.java | 0 .../query/metrics/FetchExecutionRange.java | 0 .../FetchExecutionRangeAccumulator.java | 0 .../query/metrics/QueryMetricsTextWriter.java | 0 .../query/metrics/QueryMetricsWriter.java | 0 .../query/metrics/SchedulingStopwatch.java | 0 .../query/metrics/SchedulingTimeSpan.java | 0 .../internal/query/metrics/TextTable.java | 0 .../query/orderbyquery/OrderByRowResult.java | 0 .../orderbyquery/OrderbyRowComparer.java | 0 .../routing/BoolPartitionKeyComponent.java | 0 .../routing/CaseInsensitiveHashMap.java | 0 .../routing/CollectionRoutingMap.java | 0 .../routing/IPartitionKeyComponent.java | 0 .../internal/routing/IServerIdentity.java | 0 .../routing/InMemoryCollectionRoutingMap.java | 0 .../InfinityPartitionKeyComponent.java | 0 .../data/cosmos/internal/routing/Int128.java | 0 .../internal/routing/LocationCache.java | 0 .../internal/routing/LocationHelper.java | 0 .../MaxNumberPartitionKeyComponent.java | 0 .../MaxStringPartitionKeyComponent.java | 0 .../MinNumberPartitionKeyComponent.java | 0 .../MinStringPartitionKeyComponent.java | 0 .../internal/routing/MurmurHash3_128.java | 0 .../internal/routing/MurmurHash3_32.java | 0 .../routing/NullPartitionKeyComponent.java | 0 .../routing/NumberPartitionKeyComponent.java | 0 .../PartitionKeyAndResourceTokenPair.java | 0 .../routing/PartitionKeyComponentType.java | 0 .../routing/PartitionKeyInternal.java | 0 .../routing/PartitionKeyInternalHelper.java | 0 .../routing/PartitionKeyRangeIdentity.java | 0 .../data/cosmos/internal/routing/Range.java | 0 .../internal/routing/RoutingMapProvider.java | 0 .../routing/RoutingMapProviderHelper.java | 0 .../routing/StringPartitionKeyComponent.java | 0 .../data/cosmos/internal/routing/UInt128.java | 0 .../UndefinedPartitionKeyComponent.java | 0 .../com/azure/data/cosmos/BridgeUtils.java | 0 .../com/azure/data/cosmos/ConflictTests.java | 0 .../data/cosmos/ConnectionPolicyTest.java | 2 +- .../cosmos/CosmosClientExceptionTest.java | 0 .../data/cosmos/CosmosPartitionKeyTests.java | 12 +- .../data/cosmos/DocumentCollectionTests.java | 0 .../com/azure/data/cosmos/DocumentTests.java | 0 .../azure/data/cosmos/GatewayTestUtils.java | 0 .../azure/data/cosmos/IncludedPathTest.java | 0 .../data/cosmos/JsonSerializableTests.java | 0 .../data/cosmos/PartitionKeyHashingTests.java | 0 .../com/azure/data/cosmos/PermissionTest.java | 0 .../azure/data/cosmos/ResourceIdTests.java | 0 .../internal/ClientRetryPolicyTest.java | 0 .../data/cosmos/internal}/ConfigsBuilder.java | 5 +- .../data/cosmos/internal/ConfigsTests.java | 2 +- .../cosmos/internal/ConsistencyTests1.java | 6 +- .../cosmos/internal/ConsistencyTests2.java | 4 +- .../cosmos/internal/ConsistencyTestsBase.java | 5 +- .../DocumentQuerySpyWireContentTest.java | 5 +- ...ocumentServiceRequestContextValidator.java | 5 +- .../DocumentServiceRequestValidator.java | 6 +- .../cosmos/internal}/FailureValidator.java | 6 +- .../internal}/FeedResponseListValidator.java | 3 +- .../internal}/FeedResponseValidator.java | 3 +- .../internal}/HttpClientUnderTestWrapper.java | 2 +- .../cosmos/internal/LocationHelperTest.java | 0 .../cosmos/internal/NetworkFailureTest.java | 2 +- .../data/cosmos/internal/PathsHelperTest.java | 0 ...eCollectionAwareClientRetryPolicyTest.java | 2 +- .../internal}/ResourceResponseValidator.java | 8 +- .../cosmos/internal}/ResourceValidator.java | 4 +- .../data/cosmos/internal}/RetryAnalyzer.java | 4 +- .../internal/RetryCreateDocumentTest.java | 4 +- .../cosmos/internal/RetryThrottleTest.java | 4 +- .../data/cosmos/internal/RetryUtilsTest.java | 5 +- .../RxDocumentServiceRequestTest.java | 0 .../internal/RxGatewayStoreModelTest.java | 2 +- .../cosmos/internal/SessionContainerTest.java | 0 .../cosmos/internal/SessionTokenTest.java | 0 .../cosmos/internal/ShouldRetryValidator.java | 2 +- .../internal/SpyClientUnderTestFactory.java | 2 +- .../internal}/StoreResponseBuilder.java | 5 +- .../data/cosmos/internal/TestSuiteBase.java | 23 +- .../azure/data/cosmos/internal/TestUtils.java | 6 +- .../data/cosmos/internal/TimeTokenTest.java | 0 .../internal/caches/AsyncCacheTest.java | 0 .../AddressResolverTest.java | 6 +- .../AddressSelectorTest.java | 10 +- .../AddressSelectorWrapper.java | 8 +- .../directconnectivity/AddressValidator.java | 6 +- .../BarrierRequestHelperTest.java | 7 +- .../ConsistencyReaderTest.java | 17 +- .../ConsistencyReaderUnderTest.java | 7 +- .../ConsistencyWriterTest.java | 11 +- .../DCDocumentCrudTest.java | 11 +- .../directconnectivity/EndpointMock.java | 5 +- .../directconnectivity/ExceptionBuilder.java | 2 +- .../Function1WithCheckedException.java | 2 +- .../Function2WithCheckedException.java | 2 +- .../GatewayAddressCacheTest.java | 14 +- ...GatewayServiceConfigurationReaderTest.java | 5 +- .../GatewayServiceConfiguratorReaderMock.java | 3 +- .../GlobalAddressResolverTest.java | 3 - .../GoneAndRetryWithRetryPolicyTest.java | 3 +- .../HttpClientMockWrapper.java | 3 +- .../HttpTransportClientTest.java | 8 +- .../directconnectivity/HttpUtilsTest.java | 4 +- .../MultiStoreResultValidator.java | 4 +- .../MurmurHash3_32Test.java | 2 +- .../PartitionKeyInternalTest.java | 2 +- .../directconnectivity/PartitionKeyTest.java | 2 +- .../PartitionReplicasAddressesValidator.java | 7 +- .../directconnectivity/QuorumReaderTest.java | 13 +- .../directconnectivity/ReflectionUtils.java | 4 - .../ReplicaAddressFactory.java | 6 +- ...catedResourceClientPartitionSplitTest.java | 13 +- .../ReplicatedResourceClientTest.java | 6 +- .../RntbdTransportClientTest.java | 41 +-- .../StoreReaderDotNetTest.java | 19 +- .../directconnectivity/StoreReaderTest.java | 15 +- .../StoreReaderUnderTest.java | 6 +- .../directconnectivity/StoreResponseTest.java | 3 +- .../StoreResponseValidator.java | 2 +- .../StoreResultValidator.java | 4 +- .../directconnectivity/TimeoutHelperTest.java | 3 +- .../TransportClientWrapper.java | 7 +- .../WebExceptionUtilityTest.java | 3 +- .../InMemoryCollectionRoutingMapTest.java | 0 .../internal/routing/LocationCacheTest.java | 7 +- .../routing/PartitionKeyInternalUtils.java | 0 .../routing/RoutingMapProviderHelperTest.java | 0 .../StringPartitionKeyComponentTest.java | 0 .../data/cosmos/rx/AggregateQueryTests.java | 1 + .../rx/BackPressureCrossPartitionTest.java | 3 +- .../data/cosmos/rx/BackPressureTest.java | 3 +- .../azure/data/cosmos/rx/ChangeFeedTest.java | 5 +- .../data/cosmos/rx/CollectionCrudTest.java | 3 +- .../data/cosmos/rx/CollectionQueryTest.java | 2 + .../data/cosmos/rx/DatabaseCrudTest.java | 1 + .../data/cosmos/rx/DatabaseQueryTest.java | 2 + .../data/cosmos/rx/DocumentCrudTest.java | 1 + .../rx/MultiMasterConflictResolutionTest.java | 2 + .../cosmos/rx/MultiOrderByQueryTests.java | 2 + .../azure/data/cosmos/rx/OfferQueryTest.java | 5 +- .../data/cosmos/rx/OfferReadReplaceTest.java | 4 +- .../cosmos/rx/OrderbyDocumentQueryTest.java | 4 +- .../cosmos/rx/ParallelDocumentQueryTest.java | 4 +- .../azure/data/cosmos/rx/ParsingEnvTest.java | 2 +- .../data/cosmos/rx/PermissionCrudTest.java | 1 + .../data/cosmos/rx/PermissionQueryTest.java | 4 +- .../azure/data/cosmos/rx/ProxyHostTest.java | 1 + .../cosmos/rx/ReadFeedCollectionsTest.java | 2 + .../data/cosmos/rx/ReadFeedDatabasesTest.java | 2 + .../data/cosmos/rx/ReadFeedDocumentsTest.java | 3 + .../data/cosmos/rx/ReadFeedOffersTest.java | 3 +- .../cosmos/rx/ReadFeedPermissionsTest.java | 4 +- .../data/cosmos/rx/ReadFeedPkrTests.java | 1 + .../rx/ReadFeedStoredProceduresTest.java | 2 + .../data/cosmos/rx/ReadFeedTriggersTest.java | 2 + .../data/cosmos/rx/ReadFeedUdfsTest.java | 2 + .../data/cosmos/rx/ReadFeedUsersTest.java | 2 + .../data/cosmos/rx/ResourceTokenTest.java | 38 +- .../rx/SinglePartitionDocumentQueryTest.java | 6 +- .../SinglePartitionReadFeedDocumentsTest.java | 2 + .../cosmos/rx/StoredProcedureCrudTest.java | 1 + .../cosmos/rx/StoredProcedureQueryTest.java | 3 + .../azure/data/cosmos/rx/TestSuiteBase.java | 6 +- .../data/cosmos/rx/TokenResolverTest.java | 8 +- .../azure/data/cosmos/rx/TopQueryTests.java | 3 +- .../data/cosmos/rx/TriggerQueryTest.java | 3 + .../azure/data/cosmos/rx/UniqueIndexTest.java | 2 + .../azure/data/cosmos/rx/UserCrudTest.java | 1 + .../rx/UserDefinedFunctionQueryTest.java | 6 +- .../azure/data/cosmos/rx/UserQueryTest.java | 5 +- .../src/test/resources/sampleConflict.json | 0 524 files changed, 583 insertions(+), 1720 deletions(-) delete mode 100644 commons-test-utils/pom.xml delete mode 100644 commons-test-utils/src/main/tests/java/com/azure/data/cosmos/ConfigsBuilderTest.java delete mode 100644 commons-test-utils/src/main/tests/resources/log4j.properties delete mode 100644 commons/pom.xml delete mode 100644 commons/src/main/java/com/azure/data/cosmos/package-info.java delete mode 100644 commons/src/test/resources/log4j.properties delete mode 100644 direct-impl/pom.xml delete mode 100644 direct-impl/src/test/resources/log4j.properties delete mode 100644 gateway/pom.xml delete mode 100644 gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/RetryPolicy.java delete mode 100644 gateway/src/test/resources/log4j.properties rename {commons => sdk}/src/main/java/com/azure/data/cosmos/AccessCondition.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/AccessConditionType.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/Attachment.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/BadRequestException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/BridgeInternal.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java (99%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CompositePath.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/Conflict.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ConflictException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ConnectionMode.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosClientException.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosError.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosResourceType.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosResponse.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/DataType.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/Database.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/DatabaseAccount.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/Document.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/DocumentCollection.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ExcludedPath.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/FeedOptions.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/FeedResponse.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ForbiddenException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/GoneException.java (98%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/HashIndex.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/ISessionContainer.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/IncludedPath.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/Index.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/IndexKind.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/IndexingDirective.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/IndexingMode.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/IndexingPolicy.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java (98%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java (96%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/JsonSerializable.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/LockedException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/NotFoundException.java (98%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java (96%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/PartitionKey.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java (95%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java (96%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/PartitionKind.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/PermissionMode.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/RangeIndex.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java (98%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/Resource.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/RetryOptions.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/RetryWithException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/SpatialIndex.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/SpatialSpec.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/SpatialType.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/SqlParameter.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/SqlParameterList.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/TokenResolver.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/TriggerOperation.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/TriggerType.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/UnauthorizedException.java (97%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/Undefined.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/UniqueKey.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java (99%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Bytes.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java (99%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Configs.java (99%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Constants.java (100%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java (100%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/DatabaseForTest.java (92%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java (96%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Exceptions.java (100%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Integers.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Lists.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Longs.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java (100%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Offer.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/OperationType.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/PathInfo.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/PathParser.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Paths.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Permission.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Quadruple.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/RMResources.java (100%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java (100%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/ResourceId.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java (98%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/ResourceType.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java (99%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java (98%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java (99%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Strings.java (100%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos/rx => sdk/src/main/java/com/azure/data/cosmos/internal}/TestConfigurations.java (99%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Trigger.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/User.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/Utils.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java (97%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java (99%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java (100%) rename {commons/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/Address.java (98%) rename {commons/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/AddressInformation.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/AddressResolver.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/AddressSelector.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/BarrierRequestHelper.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/ConsistencyReader.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/ConsistencyWriter.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/CustomHeaders.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/ErrorUtils.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/GatewayAddressCache.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/GatewayServiceConfigurationReader.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/GoneAndRetryWithRetryPolicy.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/HttpClientUtils.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/HttpTransportClient.java (99%) rename {commons/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/HttpUtils.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/IAddressCache.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/IAddressResolver.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/IStoreClient.java (97%) rename {commons/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/Protocol.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/QueryRequestPerformanceActivity.java (95%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/QuorumReader.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/ReadMode.java (95%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/ReplicatedResourceClient.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/RequestHelper.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/ResourceOperation.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/ResponseUtils.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/RntbdTransportClient.java (95%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/ServerProperties.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/ServerStoreModel.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/ServiceConfig.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/StoreClient.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/StoreClientFactory.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/StoreReader.java (99%) rename {commons/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/StoreResponse.java (98%) rename {commons/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/StoreResult.java (99%) rename {commons/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/TimeoutHelper.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/TransportClient.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/TransportException.java (97%) rename {commons/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/WFConstants.java (99%) rename {gateway/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/WebExceptionUtility.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdClientChannelHandler.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdClientChannelPool.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdConstants.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdContext.java (95%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdContextDecoder.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdContextException.java (93%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdContextNegotiator.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdContextRequest.java (91%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdContextRequestDecoder.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdContextRequestEncoder.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdEndpoint.java (95%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdFramer.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdMetrics.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdObjectMapper.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdReporter.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdRequest.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdRequestArgs.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdRequestDecoder.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdRequestEncoder.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdRequestFrame.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdRequestFramer.java (95%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdRequestHeaders.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdRequestManager.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdRequestRecord.java (95%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdRequestTimer.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdResponse.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdResponseDecoder.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdResponseHeaders.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdResponseStatus.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdServiceEndpoint.java (98%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdToken.java (97%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdTokenStream.java (96%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdTokenType.java (99%) rename {direct-impl/src/main/java/com/azure/data/cosmos => sdk/src/main/java/com/azure/data/cosmos/internal}/directconnectivity/rntbd/RntbdUUID.java (98%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java (99%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java (97%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java (100%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java (100%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java (100%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java (100%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/Range.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java (100%) rename {gateway => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java (100%) rename {direct-impl => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java (100%) rename {commons => sdk}/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java (100%) rename {commons-test-utils/src/main => sdk/src/test}/java/com/azure/data/cosmos/BridgeUtils.java (100%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/ConflictTests.java (100%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java (97%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java (100%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java (100%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/DocumentTests.java (100%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java (100%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/IncludedPathTest.java (100%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java (100%) rename {direct-impl => sdk}/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java (100%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/PermissionTest.java (100%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/ResourceIdTests.java (100%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java (100%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/ConfigsBuilder.java (92%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java (97%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos/rx => sdk/src/test/java/com/azure/data/cosmos/internal}/DocumentServiceRequestContextValidator.java (95%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos/rx => sdk/src/test/java/com/azure/data/cosmos/internal}/DocumentServiceRequestValidator.java (95%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos/rx => sdk/src/test/java/com/azure/data/cosmos/internal}/FailureValidator.java (98%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos/rx => sdk/src/test/java/com/azure/data/cosmos/internal}/FeedResponseListValidator.java (99%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos/rx => sdk/src/test/java/com/azure/data/cosmos/internal}/FeedResponseValidator.java (98%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity => sdk/src/test/java/com/azure/data/cosmos/internal}/HttpClientUnderTestWrapper.java (97%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java (100%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java (100%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java (99%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos/rx => sdk/src/test/java/com/azure/data/cosmos/internal}/ResourceResponseValidator.java (97%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos/rx => sdk/src/test/java/com/azure/data/cosmos/internal}/ResourceValidator.java (96%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/RetryAnalyzer.java (95%) rename {direct-impl => sdk}/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java (97%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java (100%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java (98%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java (100%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java (100%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java (98%) rename {commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity => sdk/src/test/java/com/azure/data/cosmos/internal}/StoreResponseBuilder.java (95%) rename commons-test-utils/src/main/java/com/azure/data/cosmos/rx/Utils.java => sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java (96%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java (100%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java (100%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/AddressResolverTest.java (99%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/AddressSelectorTest.java (93%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/AddressSelectorWrapper.java (97%) rename sdk/src/test/java/com/azure/data/cosmos/{ => internal}/directconnectivity/AddressValidator.java (93%) rename sdk/src/test/java/com/azure/data/cosmos/{ => internal}/directconnectivity/BarrierRequestHelperTest.java (97%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/ConsistencyReaderTest.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/ConsistencyReaderUnderTest.java (93%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/ConsistencyWriterTest.java (97%) rename sdk/src/test/java/com/azure/data/cosmos/{ => internal}/directconnectivity/DCDocumentCrudTest.java (97%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/EndpointMock.java (97%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/ExceptionBuilder.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/Function1WithCheckedException.java (95%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/Function2WithCheckedException.java (95%) rename sdk/src/test/java/com/azure/data/cosmos/{ => internal}/directconnectivity/GatewayAddressCacheTest.java (98%) rename sdk/src/test/java/com/azure/data/cosmos/{ => internal}/directconnectivity/GatewayServiceConfigurationReaderTest.java (97%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/GatewayServiceConfiguratorReaderMock.java (96%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/GoneAndRetryWithRetryPolicyTest.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/HttpClientMockWrapper.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/HttpTransportClientTest.java (98%) rename {commons/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/HttpUtilsTest.java (93%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/MultiStoreResultValidator.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/MurmurHash3_32Test.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/PartitionKeyInternalTest.java (99%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/PartitionKeyTest.java (98%) rename sdk/src/test/java/com/azure/data/cosmos/{ => internal}/directconnectivity/PartitionReplicasAddressesValidator.java (94%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/QuorumReaderTest.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/ReplicaAddressFactory.java (89%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java (94%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/ReplicatedResourceClientTest.java (94%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/RntbdTransportClientTest.java (96%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/StoreReaderDotNetTest.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/StoreReaderTest.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/StoreReaderUnderTest.java (91%) rename {commons/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/StoreResponseTest.java (95%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/StoreResponseValidator.java (99%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/StoreResultValidator.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/TimeoutHelperTest.java (94%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/TransportClientWrapper.java (98%) rename {direct-impl/src/test/java/com/azure/data/cosmos => sdk/src/test/java/com/azure/data/cosmos/internal}/directconnectivity/WebExceptionUtilityTest.java (97%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java (100%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java (98%) rename {direct-impl => sdk}/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java (100%) rename {gateway => sdk}/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java (100%) rename {commons => sdk}/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java (100%) rename {commons => sdk}/src/test/resources/sampleConflict.json (100%) diff --git a/benchmark/pom.xml b/benchmark/pom.xml index a4edcd0e7a072..528436328ce84 100644 --- a/benchmark/pom.xml +++ b/benchmark/pom.xml @@ -115,10 +115,6 @@ com.microsoft.azure azure-cosmos - - com.microsoft.azure - azure-cosmos-commons-test-utils - com.beust jcommander diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java index d0121bf048b3f..a28bba1464b8a 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java @@ -28,8 +28,8 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.benchmark.Configuration.Operation; +import com.azure.data.cosmos.internal.ResourceResponse; import com.codahale.metrics.ConsoleReporter; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricFilter; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java index 001ef47925016..78590124f2d0c 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java @@ -26,13 +26,13 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.SqlParameterList; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.internal.RequestOptions; -import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.SqlParameter; +import com.azure.data.cosmos.SqlParameterList; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.NotFoundException; +import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.internal.Utils; import org.apache.commons.lang3.RandomUtils; import reactor.core.publisher.BaseSubscriber; diff --git a/benchmark/src/main/resources/log4j.properties b/benchmark/src/main/resources/log4j.properties index 34cead5b2f2ae..7a31b9cb1817a 100644 --- a/benchmark/src/main/resources/log4j.properties +++ b/benchmark/src/main/resources/log4j.properties @@ -3,7 +3,7 @@ # Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=INFO, A1 -log4j.category.com.azure.data.cosmos.directconnectivity.rntbd=WARN +log4j.category.com.azure.data.cosmos.internal.directconnectivity.rntbd=WARN log4j.category.io.netty=INFO log4j.category.io.reactivex=INFO # A1 is set to be a ConsoleAppender. diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java index 8636a48a2bb67..80e223094d114 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java @@ -33,7 +33,7 @@ import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.RequestOptions; -import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.TestConfigurations; import com.beust.jcommander.JCommander; import com.google.common.base.CaseFormat; import com.google.common.base.Strings; diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java index 8c3822b47cea1..88bd336a70395 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java @@ -50,13 +50,13 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.internal.DatabaseForTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.TestConfigurations; import reactor.core.publisher.Flux; public class Utils { diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java index da8396f10c132..7376259cd324a 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java @@ -33,7 +33,7 @@ import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.RequestOptions; -import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.TestConfigurations; import com.beust.jcommander.JCommander; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; diff --git a/commons-test-utils/pom.xml b/commons-test-utils/pom.xml deleted file mode 100644 index 3b1098b8325ae..0000000000000 --- a/commons-test-utils/pom.xml +++ /dev/null @@ -1,159 +0,0 @@ - - - 4.0.0 - - com.microsoft.azure - azure-cosmos-parent - 3.0.0-a1-SNAPSHOT - - azure-cosmos-commons-test-utils - Common Test Components for Testing Async SDK for SQL API of Azure Cosmos DB Service - Common Test Components for Testing Async SDK for SQL API of Azure Cosmos DB Service - jar - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.0 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - - - org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.8 - false - - - none - default-cli - - - - true - - - - - - - - org.apache.maven.plugins - maven-surefire-report-plugin - 2.22.0 - - - org.codehaus.mojo - findbugs-maven-plugin - 3.0.4 - - - org.apache.maven.plugins - maven-jxr-plugin - 2.1 - - - - - - com.microsoft.azure - azure-cosmos-commons - - - com.google.guava - guava - ${guava.version} - - - io.projectreactor - reactor-core - - - log4j - log4j - ${log4j.version} - - - org.assertj - assertj-core - ${assertj.version} - - - org.hamcrest - hamcrest-core - ${hamcrest.version} - - - org.mockito - mockito-core - ${mockito.version} - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.slf4j - slf4j-log4j12 - ${slf4j.version} - - - org.testng - testng - ${testng.version} - - - diff --git a/commons-test-utils/src/main/tests/java/com/azure/data/cosmos/ConfigsBuilderTest.java b/commons-test-utils/src/main/tests/java/com/azure/data/cosmos/ConfigsBuilderTest.java deleted file mode 100644 index 4e38ffcade804..0000000000000 --- a/commons-test-utils/src/main/tests/java/com/azure/data/cosmos/ConfigsBuilderTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.azure.data.cosmos; - -import com.azure.data.cosmos.directconnectivity.Protocol; -import com.azure.data.cosmos.internal.internal.Configs; -import org.testng.annotations.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ConfigsBuilderTest { - - @Test(groups = { "unit" }) - public void defaultProtocol() { - Configs config = ConfigsBuilder.instance().build(); - assertThat(config.getProtocol()).isEqualTo(Protocol.Https); - } - - @Test(groups = { "unit" }) - public void tcp() { - Configs config = ConfigsBuilder.instance().withProtocol(Protocol.Tcp).build(); - assertThat(config.getProtocol()).isEqualTo(Protocol.Tcp); - } - - @Test(groups = { "unit" }) - public void https() { - Configs config = ConfigsBuilder.instance().withProtocol(Protocol.Https).build(); - assertThat(config.getProtocol()).isEqualTo(Protocol.Https); - } -} diff --git a/commons-test-utils/src/main/tests/resources/log4j.properties b/commons-test-utils/src/main/tests/resources/log4j.properties deleted file mode 100644 index 1f3287c67a55f..0000000000000 --- a/commons-test-utils/src/main/tests/resources/log4j.properties +++ /dev/null @@ -1,15 +0,0 @@ -# this is the log4j configuration for tests - -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=INFO, A1 - -# Set HTTP components' logger to INFO - -log4j.category.io.netty=INFO -log4j.category.io.reactivex=INFO -# A1 is set to be a ConsoleAppender. -log4j.appender.A1=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%d %5X{pid} [%t] %-5p %c - %m%n diff --git a/commons/pom.xml b/commons/pom.xml deleted file mode 100644 index 8b9ce774a5b31..0000000000000 --- a/commons/pom.xml +++ /dev/null @@ -1,223 +0,0 @@ - - - 4.0.0 - - com.microsoft.azure - azure-cosmos-parent - 3.0.0-a1-SNAPSHOT - - azure-cosmos-commons - Common Components for Async SDK for SQL API of Azure Cosmos DB Service - Common Components for Async SDK for SQL API of Azure Cosmos DB Service - jar - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.0 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - - - org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.8 - false - - - none - default-cli - - - - true - - - - - - - - org.apache.maven.plugins - maven-surefire-report-plugin - 2.22.0 - - - org.codehaus.mojo - findbugs-maven-plugin - 3.0.4 - - - org.apache.maven.plugins - maven-jxr-plugin - 2.1 - - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - - - com.fasterxml.uuid - java-uuid-generator - ${java-uuid-generator.version} - - - commons-io - commons-io - ${commons-io.version} - - - commons-validator - commons-validator - ${commons-validator.version} - - - io.netty - netty-codec-http - ${netty.version} - - - io.netty - netty-handler - ${netty.version} - - - io.netty - netty-transport - ${netty.version} - - - io.netty - netty-handler-proxy - ${netty.version} - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - org.apache.commons - commons-collections4 - 4.2 - - - org.apache.commons - commons-text - ${commons-text.version} - - - org.testng - testng - ${testng.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.hamcrest - hamcrest-core - ${hamcrest.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - - - org.slf4j - slf4j-log4j12 - ${slf4j.version} - test - - - log4j - log4j - ${log4j.version} - test - - - io.projectreactor - reactor-core - - - io.projectreactor.addons - reactor-adapter - ${reactor-addons.version} - test - - - io.projectreactor - reactor-test - test - - - io.reactivex.rxjava2 - rxjava - ${rxjava2.version} - - - com.google.guava - guava - ${guava.version} - test - - - io.projectreactor.netty - reactor-netty - - - diff --git a/commons/src/main/java/com/azure/data/cosmos/package-info.java b/commons/src/main/java/com/azure/data/cosmos/package-info.java deleted file mode 100644 index e7385efdf3309..0000000000000 --- a/commons/src/main/java/com/azure/data/cosmos/package-info.java +++ /dev/null @@ -1,28 +0,0 @@ - -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -/** - * This package provides Java SDK Common Resources for Azure Cosmos DB. - */ -package com.azure.data.cosmos; \ No newline at end of file diff --git a/commons/src/test/resources/log4j.properties b/commons/src/test/resources/log4j.properties deleted file mode 100644 index 09c5242466d25..0000000000000 --- a/commons/src/test/resources/log4j.properties +++ /dev/null @@ -1,16 +0,0 @@ -# this is the log4j configuration for tests - -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=INFO, A1 - -# Set HTTP components' logger to INFO - -log4j.category.io.netty=INFO -log4j.category.io.reactivex=INFO -log4j.category.com.azure.data.cosmos=INFO -# A1 is set to be a ConsoleAppender. -log4j.appender.A1=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%d %5X{pid} [%t] %-5p %c - %m%n diff --git a/direct-impl/pom.xml b/direct-impl/pom.xml deleted file mode 100644 index 44c305467bf2d..0000000000000 --- a/direct-impl/pom.xml +++ /dev/null @@ -1,341 +0,0 @@ - - - 4.0.0 - com.microsoft.azure - azure-cosmos-direct - Azure Cosmos DB Async SDK Direct Internal Implementation - 3.0.0-a1-SNAPSHOT - Azure Cosmos DB Async SDK Direct Internal Implementation - https://docs.microsoft.com/en-us/azure/cosmos-db - jar - - UTF-8 - unit - 3.0.0-a1-SNAPSHOT - 27.0.1-jre - 4.0.5 - - - - - unit - - default - unit - - - true - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - - - - - - fast - - simple - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - long - - long - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - direct - - direct - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - multi-master - - multi-master - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - emulator - - emulator - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - non-emulator - - non-emulator - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.0 - - unit - - **/*.java - - - - surefire.testng.verbose - 2 - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - 2.22.0 - - - **/*.java - - ${test.groups} - - - surefire.testng.verbose - 2 - - - - - - - integration-test - verify - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.0 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - - - org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 - - - - - - maven-javadoc-plugin - 3.0.1 - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - empty-javadoc-jar - package - - jar - - - empty-javadoc - ${basedir}/javadoc - - - - empty-sources-jar - package - - jar - - - empty-sources - ${basedir}/sources - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.8 - false - - - none - default-cli - - - - true - - - - - - - - org.apache.maven.plugins - maven-surefire-report-plugin - 2.22.0 - - - org.codehaus.mojo - findbugs-maven-plugin - 3.0.4 - - - org.apache.maven.plugins - maven-jxr-plugin - 2.1 - - - - - - com.microsoft.azure - azure-cosmos-gateway - ${cosmosdb-sdk.version} - - - com.microsoft.azure - azure-cosmos-commons-test-utils - ${cosmosdb-sdk.version} - test - - - com.google.guava - guava - ${guava.version} - - - io.dropwizard.metrics - metrics-core - ${metrics.version} - - - - - MIT License - http://www.opensource.org/licenses/mit-license.php - - - - scm:git:https://github.com/Azure/azure-cosmosdb-java.git - scm:git:https://github.com/Azure/azure-cosmosdb-java.git - https://github.com/Azure/azure-cosmosdb-java.git - - - - Azure Cosmos DB Developer Platform Devs - docdbdevplatdevs@microsoft.com - Microsoft - http://www.microsoft.com/ - - - diff --git a/direct-impl/src/test/resources/log4j.properties b/direct-impl/src/test/resources/log4j.properties deleted file mode 100644 index 09c5242466d25..0000000000000 --- a/direct-impl/src/test/resources/log4j.properties +++ /dev/null @@ -1,16 +0,0 @@ -# this is the log4j configuration for tests - -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=INFO, A1 - -# Set HTTP components' logger to INFO - -log4j.category.io.netty=INFO -log4j.category.io.reactivex=INFO -log4j.category.com.azure.data.cosmos=INFO -# A1 is set to be a ConsoleAppender. -log4j.appender.A1=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%d %5X{pid} [%t] %-5p %c - %m%n diff --git a/examples/pom.xml b/examples/pom.xml index e8f52dac5361e..72b825a563ae5 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -116,10 +116,6 @@ com.microsoft.azure azure-cosmos - - - com.microsoft.azure - azure-cosmos-commons-test-utils com.google.guava diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java index 343b7a2f63d1e..b3ee13b0501dc 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java @@ -35,7 +35,6 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.SerializationFormattingPolicy; import org.apache.commons.lang3.RandomStringUtils; -import reactor.core.publisher.Mono; import java.time.Duration; diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java index 3c96d8ddf58e8..116acabea9ef1 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java @@ -33,8 +33,8 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.internal.StoredProcedure; import com.azure.data.cosmos.rx.examples.multimaster.Helpers; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java index 194dfc34b31d0..5fd7eab71d6e1 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java @@ -27,13 +27,13 @@ import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.internal.DatabaseForTest; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.TestConfigurations; import org.testng.annotations.AfterSuite; import reactor.core.publisher.Flux; diff --git a/gateway/pom.xml b/gateway/pom.xml deleted file mode 100644 index 0a506a584c772..0000000000000 --- a/gateway/pom.xml +++ /dev/null @@ -1,149 +0,0 @@ - - - 4.0.0 - - com.microsoft.azure - azure-cosmos-parent - 3.0.0-a1-SNAPSHOT - - azure-cosmos-gateway - Common Gateway Components for Async SDK for SQL API of Azure Cosmos DB Service - Common Gateway Components for Async SDK for SQL API of Azure Cosmos DB Service - jar - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.0 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.8 - - - - org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8 - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.8 - false - - - none - default-cli - - - - true - - - - - - - - org.apache.maven.plugins - maven-surefire-report-plugin - 2.22.0 - - - org.codehaus.mojo - findbugs-maven-plugin - 3.0.4 - - - org.apache.maven.plugins - maven-jxr-plugin - 2.1 - - - - - - com.microsoft.azure - azure-cosmos-commons - - - com.microsoft.azure - azure-cosmos-commons-test-utils - test - - - org.testng - testng - ${testng.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - org.slf4j - slf4j-log4j12 - ${slf4j.version} - test - - - log4j - log4j - ${log4j.version} - test - - - com.google.guava - guava - ${guava.version} - test - - - io.projectreactor.netty - reactor-netty - - - io.reactivex.rxjava2 - rxjava - ${rxjava2.version} - - - io.projectreactor.addons - reactor-adapter - - - diff --git a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/RetryPolicy.java b/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/RetryPolicy.java deleted file mode 100644 index 4f65575443ffd..0000000000000 --- a/gateway/src/main/java/com/microsoft/azure/cosmosdb/internal/RetryPolicy.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.microsoft.azure.cosmosdb.internal; - -import com.azure.data.cosmos.CosmosClientException; - -/** - * Used internally to define the interface for retry policy in the Azure Cosmos - * DB database service Java SDK. - */ -public interface RetryPolicy { - boolean shouldRetry(CosmosClientException exception); - - long getRetryAfterInMilliseconds(); -} diff --git a/gateway/src/test/resources/log4j.properties b/gateway/src/test/resources/log4j.properties deleted file mode 100644 index 1f3287c67a55f..0000000000000 --- a/gateway/src/test/resources/log4j.properties +++ /dev/null @@ -1,15 +0,0 @@ -# this is the log4j configuration for tests - -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=INFO, A1 - -# Set HTTP components' logger to INFO - -log4j.category.io.netty=INFO -log4j.category.io.reactivex=INFO -# A1 is set to be a ConsoleAppender. -log4j.appender.A1=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%d %5X{pid} [%t] %-5p %c - %m%n diff --git a/pom.xml b/pom.xml index 526f1bd558412..053caac4bba66 100644 --- a/pom.xml +++ b/pom.xml @@ -32,11 +32,7 @@ Java Async SDK (with Reactive Extension RX support) for Azure Cosmos DB SQL API https://docs.microsoft.com/en-us/azure/cosmos-db - commons - gateway - commons-test-utils sdk - direct-impl benchmark examples @@ -350,34 +346,6 @@ tofile="${collectedArtifactsForReleaseLocation}/azure-cosmos-${sdk-version}-javadoc.jar"/> - - - - - - - - - - - - - - - - @@ -414,26 +382,6 @@ azure-cosmos ${project.parent.version} - - com.microsoft.azure - azure-cosmos-commons - ${project.parent.version} - - - com.microsoft.azure - azure-cosmos-gateway - ${project.parent.version} - - - com.microsoft.azure - azure-cosmos-direct - ${cosmosdb-sdk-direct-impl.version} - - - com.microsoft.azure - azure-cosmos-commons-test-utils - ${project.parent.version} - io.projectreactor reactor-bom diff --git a/sdk/pom.xml b/sdk/pom.xml index 015c95248568c..6660f0a860581 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -159,23 +159,6 @@ SOFTWARE. - - com.microsoft.azure - azure-cosmos-commons - - - com.microsoft.azure - azure-cosmos-gateway - - - com.microsoft.azure - azure-cosmos-direct - - - com.microsoft.azure - azure-cosmos-commons-test-utils - test - com.fasterxml.jackson.core jackson-databind @@ -191,6 +174,11 @@ SOFTWARE. commons-io ${commons-io.version} + + commons-validator + commons-validator + ${commons-validator.version} + io.projectreactor reactor-core @@ -220,6 +208,16 @@ SOFTWARE. commons-lang3 ${commons-lang3.version} + + org.apache.commons + commons-collections4 + 4.2 + + + org.apache.commons + commons-text + ${commons-text.version} + org.testng testng @@ -248,7 +246,6 @@ SOFTWARE. com.google.guava guava ${guava.version} - test io.projectreactor @@ -260,9 +257,24 @@ SOFTWARE. rxjava ${rxjava2.version} + + io.projectreactor.netty + reactor-netty + io.projectreactor.addons reactor-adapter + + io.dropwizard.metrics + metrics-core + ${metrics.version} + + + org.mockito + mockito-core + ${mockito.version} + test + diff --git a/commons/src/main/java/com/azure/data/cosmos/AccessCondition.java b/sdk/src/main/java/com/azure/data/cosmos/AccessCondition.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/AccessCondition.java rename to sdk/src/main/java/com/azure/data/cosmos/AccessCondition.java diff --git a/commons/src/main/java/com/azure/data/cosmos/AccessConditionType.java b/sdk/src/main/java/com/azure/data/cosmos/AccessConditionType.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/AccessConditionType.java rename to sdk/src/main/java/com/azure/data/cosmos/AccessConditionType.java diff --git a/commons/src/main/java/com/azure/data/cosmos/Attachment.java b/sdk/src/main/java/com/azure/data/cosmos/Attachment.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/Attachment.java rename to sdk/src/main/java/com/azure/data/cosmos/Attachment.java diff --git a/commons/src/main/java/com/azure/data/cosmos/BadRequestException.java b/sdk/src/main/java/com/azure/data/cosmos/BadRequestException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/BadRequestException.java rename to sdk/src/main/java/com/azure/data/cosmos/BadRequestException.java index c5ea16caabcd8..7785b882f7a6b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/BadRequestException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/BadRequestException.java @@ -22,9 +22,9 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java b/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/BridgeInternal.java rename to sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java diff --git a/commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java index 4c5ca0234cdc5..61d90296d2767 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; -import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverFactory; import com.azure.data.cosmos.internal.changefeed.implementation.ChangeFeedProcessorBuilderImpl; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java index ea0981425dec8..aba333b661700 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java @@ -22,8 +22,6 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.changefeed.CheckpointFrequency; - import java.time.Duration; import java.time.OffsetDateTime; diff --git a/commons/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java b/sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java similarity index 99% rename from commons/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java rename to sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java index 5a918bcfae9f1..11607a8372519 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java @@ -22,11 +22,11 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.StoreResult; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.directconnectivity.StoreResult; import org.apache.commons.lang3.StringUtils; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java b/sdk/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java rename to sdk/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CompositePath.java b/sdk/src/main/java/com/azure/data/cosmos/CompositePath.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CompositePath.java rename to sdk/src/main/java/com/azure/data/cosmos/CompositePath.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java b/sdk/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java rename to sdk/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java diff --git a/commons/src/main/java/com/azure/data/cosmos/Conflict.java b/sdk/src/main/java/com/azure/data/cosmos/Conflict.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/Conflict.java rename to sdk/src/main/java/com/azure/data/cosmos/Conflict.java diff --git a/commons/src/main/java/com/azure/data/cosmos/ConflictException.java b/sdk/src/main/java/com/azure/data/cosmos/ConflictException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/ConflictException.java rename to sdk/src/main/java/com/azure/data/cosmos/ConflictException.java index 26bbc48897e3e..a7bbd09d2ab37 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ConflictException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ConflictException.java @@ -22,9 +22,9 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; diff --git a/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java b/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java rename to sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java diff --git a/commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java diff --git a/commons/src/main/java/com/azure/data/cosmos/ConnectionMode.java b/sdk/src/main/java/com/azure/data/cosmos/ConnectionMode.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/ConnectionMode.java rename to sdk/src/main/java/com/azure/data/cosmos/ConnectionMode.java diff --git a/commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java diff --git a/commons/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java b/sdk/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java rename to sdk/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java diff --git a/commons/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClientException.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosClientException.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosClientException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index e60a4697c1773..13a61147e7407 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -26,9 +26,6 @@ import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.internal.Paths; import com.azure.data.cosmos.internal.RequestOptions; -import com.azure.data.cosmos.internal.StoredProcedure; -import com.azure.data.cosmos.internal.Trigger; -import com.azure.data.cosmos.internal.UserDefinedFunction; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosError.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosError.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosError.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosError.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosResourceType.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosResourceType.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosResourceType.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosResourceType.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java diff --git a/commons/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java diff --git a/commons/src/main/java/com/azure/data/cosmos/DataType.java b/sdk/src/main/java/com/azure/data/cosmos/DataType.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/DataType.java rename to sdk/src/main/java/com/azure/data/cosmos/DataType.java diff --git a/commons/src/main/java/com/azure/data/cosmos/Database.java b/sdk/src/main/java/com/azure/data/cosmos/Database.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/Database.java rename to sdk/src/main/java/com/azure/data/cosmos/Database.java diff --git a/commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java b/sdk/src/main/java/com/azure/data/cosmos/DatabaseAccount.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/DatabaseAccount.java rename to sdk/src/main/java/com/azure/data/cosmos/DatabaseAccount.java diff --git a/commons/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java b/sdk/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java rename to sdk/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java b/sdk/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java rename to sdk/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java diff --git a/commons/src/main/java/com/azure/data/cosmos/Document.java b/sdk/src/main/java/com/azure/data/cosmos/Document.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/Document.java rename to sdk/src/main/java/com/azure/data/cosmos/Document.java diff --git a/commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java b/sdk/src/main/java/com/azure/data/cosmos/DocumentCollection.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/DocumentCollection.java rename to sdk/src/main/java/com/azure/data/cosmos/DocumentCollection.java diff --git a/commons/src/main/java/com/azure/data/cosmos/ExcludedPath.java b/sdk/src/main/java/com/azure/data/cosmos/ExcludedPath.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/ExcludedPath.java rename to sdk/src/main/java/com/azure/data/cosmos/ExcludedPath.java diff --git a/commons/src/main/java/com/azure/data/cosmos/FeedOptions.java b/sdk/src/main/java/com/azure/data/cosmos/FeedOptions.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/FeedOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/FeedOptions.java diff --git a/commons/src/main/java/com/azure/data/cosmos/FeedResponse.java b/sdk/src/main/java/com/azure/data/cosmos/FeedResponse.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/FeedResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/FeedResponse.java diff --git a/commons/src/main/java/com/azure/data/cosmos/ForbiddenException.java b/sdk/src/main/java/com/azure/data/cosmos/ForbiddenException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/ForbiddenException.java rename to sdk/src/main/java/com/azure/data/cosmos/ForbiddenException.java index bb92a2f5ca602..9cc3142107948 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ForbiddenException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ForbiddenException.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/GoneException.java b/sdk/src/main/java/com/azure/data/cosmos/GoneException.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/GoneException.java rename to sdk/src/main/java/com/azure/data/cosmos/GoneException.java index 68a0d2fb7e6c2..8979ee64c4058 100644 --- a/commons/src/main/java/com/azure/data/cosmos/GoneException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/GoneException.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/HashIndex.java b/sdk/src/main/java/com/azure/data/cosmos/HashIndex.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/HashIndex.java rename to sdk/src/main/java/com/azure/data/cosmos/HashIndex.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/ISessionContainer.java b/sdk/src/main/java/com/azure/data/cosmos/ISessionContainer.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/ISessionContainer.java rename to sdk/src/main/java/com/azure/data/cosmos/ISessionContainer.java diff --git a/commons/src/main/java/com/azure/data/cosmos/IncludedPath.java b/sdk/src/main/java/com/azure/data/cosmos/IncludedPath.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/IncludedPath.java rename to sdk/src/main/java/com/azure/data/cosmos/IncludedPath.java diff --git a/commons/src/main/java/com/azure/data/cosmos/Index.java b/sdk/src/main/java/com/azure/data/cosmos/Index.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/Index.java rename to sdk/src/main/java/com/azure/data/cosmos/Index.java diff --git a/commons/src/main/java/com/azure/data/cosmos/IndexKind.java b/sdk/src/main/java/com/azure/data/cosmos/IndexKind.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/IndexKind.java rename to sdk/src/main/java/com/azure/data/cosmos/IndexKind.java diff --git a/commons/src/main/java/com/azure/data/cosmos/IndexingDirective.java b/sdk/src/main/java/com/azure/data/cosmos/IndexingDirective.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/IndexingDirective.java rename to sdk/src/main/java/com/azure/data/cosmos/IndexingDirective.java diff --git a/commons/src/main/java/com/azure/data/cosmos/IndexingMode.java b/sdk/src/main/java/com/azure/data/cosmos/IndexingMode.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/IndexingMode.java rename to sdk/src/main/java/com/azure/data/cosmos/IndexingMode.java diff --git a/commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/IndexingPolicy.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/IndexingPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/IndexingPolicy.java diff --git a/commons/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java b/sdk/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java rename to sdk/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java index 5920bab2a7a8a..407ba1dab51d5 100644 --- a/commons/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java b/sdk/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java similarity index 96% rename from commons/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java rename to sdk/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java index fb082096cd5f9..8231f73701d60 100644 --- a/commons/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java @@ -22,10 +22,10 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; -import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; diff --git a/commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java b/sdk/src/main/java/com/azure/data/cosmos/JsonSerializable.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/JsonSerializable.java rename to sdk/src/main/java/com/azure/data/cosmos/JsonSerializable.java diff --git a/commons/src/main/java/com/azure/data/cosmos/LockedException.java b/sdk/src/main/java/com/azure/data/cosmos/LockedException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/LockedException.java rename to sdk/src/main/java/com/azure/data/cosmos/LockedException.java index ed4997899325b..36c22c3c965d2 100644 --- a/commons/src/main/java/com/azure/data/cosmos/LockedException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/LockedException.java @@ -22,9 +22,9 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; diff --git a/commons/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java b/sdk/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java rename to sdk/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java index cc7786f4dc8df..f81f09bf57527 100644 --- a/commons/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/NotFoundException.java b/sdk/src/main/java/com/azure/data/cosmos/NotFoundException.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/NotFoundException.java rename to sdk/src/main/java/com/azure/data/cosmos/NotFoundException.java index f64010738b35d..bf3c5752004f9 100644 --- a/commons/src/main/java/com/azure/data/cosmos/NotFoundException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/NotFoundException.java @@ -22,9 +22,9 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java b/sdk/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java similarity index 96% rename from commons/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java rename to sdk/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java index 49162efd1f9bd..3589cf67d5235 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java @@ -22,10 +22,10 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; -import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKey.java b/sdk/src/main/java/com/azure/data/cosmos/PartitionKey.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/PartitionKey.java rename to sdk/src/main/java/com/azure/data/cosmos/PartitionKey.java diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java b/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java rename to sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java b/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java rename to sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java b/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java similarity index 95% rename from commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java rename to sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java index 895934bf4e43a..cc1e9cc2c340b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; -import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java b/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java similarity index 96% rename from commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java rename to sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java index f66d030eafcfa..40c596fd31035 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java @@ -22,10 +22,10 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; -import com.azure.data.cosmos.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; diff --git a/commons/src/main/java/com/azure/data/cosmos/PartitionKind.java b/sdk/src/main/java/com/azure/data/cosmos/PartitionKind.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/PartitionKind.java rename to sdk/src/main/java/com/azure/data/cosmos/PartitionKind.java diff --git a/commons/src/main/java/com/azure/data/cosmos/PermissionMode.java b/sdk/src/main/java/com/azure/data/cosmos/PermissionMode.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/PermissionMode.java rename to sdk/src/main/java/com/azure/data/cosmos/PermissionMode.java diff --git a/commons/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java b/sdk/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java rename to sdk/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java index 0b8942e5b101d..d1bffd27c4f12 100644 --- a/commons/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java @@ -22,9 +22,9 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; diff --git a/commons/src/main/java/com/azure/data/cosmos/RangeIndex.java b/sdk/src/main/java/com/azure/data/cosmos/RangeIndex.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/RangeIndex.java rename to sdk/src/main/java/com/azure/data/cosmos/RangeIndex.java diff --git a/commons/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java b/sdk/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java rename to sdk/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java index de826ceab0c64..ae4b889f81e77 100644 --- a/commons/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java @@ -22,9 +22,9 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.util.Map; diff --git a/commons/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java b/sdk/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java rename to sdk/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java index 219878c192706..af5e25c77da89 100644 --- a/commons/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java b/sdk/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java rename to sdk/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java index d9431f86aacba..5acea29c958c0 100644 --- a/commons/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/Resource.java b/sdk/src/main/java/com/azure/data/cosmos/Resource.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/Resource.java rename to sdk/src/main/java/com/azure/data/cosmos/Resource.java diff --git a/commons/src/main/java/com/azure/data/cosmos/RetryOptions.java b/sdk/src/main/java/com/azure/data/cosmos/RetryOptions.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/RetryOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/RetryOptions.java diff --git a/commons/src/main/java/com/azure/data/cosmos/RetryWithException.java b/sdk/src/main/java/com/azure/data/cosmos/RetryWithException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/RetryWithException.java rename to sdk/src/main/java/com/azure/data/cosmos/RetryWithException.java index 31d8b317ecbf2..de0f66c62ca3b 100644 --- a/commons/src/main/java/com/azure/data/cosmos/RetryWithException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/RetryWithException.java @@ -23,8 +23,8 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java diff --git a/commons/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java b/sdk/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java rename to sdk/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java index 8e9ab2dd3434a..39e712676ff3a 100644 --- a/commons/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java b/sdk/src/main/java/com/azure/data/cosmos/SpatialIndex.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/SpatialIndex.java rename to sdk/src/main/java/com/azure/data/cosmos/SpatialIndex.java diff --git a/commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java b/sdk/src/main/java/com/azure/data/cosmos/SpatialSpec.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/SpatialSpec.java rename to sdk/src/main/java/com/azure/data/cosmos/SpatialSpec.java diff --git a/commons/src/main/java/com/azure/data/cosmos/SpatialType.java b/sdk/src/main/java/com/azure/data/cosmos/SpatialType.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/SpatialType.java rename to sdk/src/main/java/com/azure/data/cosmos/SpatialType.java diff --git a/commons/src/main/java/com/azure/data/cosmos/SqlParameter.java b/sdk/src/main/java/com/azure/data/cosmos/SqlParameter.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/SqlParameter.java rename to sdk/src/main/java/com/azure/data/cosmos/SqlParameter.java diff --git a/commons/src/main/java/com/azure/data/cosmos/SqlParameterList.java b/sdk/src/main/java/com/azure/data/cosmos/SqlParameterList.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/SqlParameterList.java rename to sdk/src/main/java/com/azure/data/cosmos/SqlParameterList.java diff --git a/commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java b/sdk/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java rename to sdk/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java diff --git a/commons/src/main/java/com/azure/data/cosmos/TokenResolver.java b/sdk/src/main/java/com/azure/data/cosmos/TokenResolver.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/TokenResolver.java rename to sdk/src/main/java/com/azure/data/cosmos/TokenResolver.java diff --git a/commons/src/main/java/com/azure/data/cosmos/TriggerOperation.java b/sdk/src/main/java/com/azure/data/cosmos/TriggerOperation.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/TriggerOperation.java rename to sdk/src/main/java/com/azure/data/cosmos/TriggerOperation.java diff --git a/commons/src/main/java/com/azure/data/cosmos/TriggerType.java b/sdk/src/main/java/com/azure/data/cosmos/TriggerType.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/TriggerType.java rename to sdk/src/main/java/com/azure/data/cosmos/TriggerType.java diff --git a/commons/src/main/java/com/azure/data/cosmos/UnauthorizedException.java b/sdk/src/main/java/com/azure/data/cosmos/UnauthorizedException.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/UnauthorizedException.java rename to sdk/src/main/java/com/azure/data/cosmos/UnauthorizedException.java index 71d4ee151a6c1..69d77ceb7d0fb 100644 --- a/commons/src/main/java/com/azure/data/cosmos/UnauthorizedException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/UnauthorizedException.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import java.net.URI; diff --git a/commons/src/main/java/com/azure/data/cosmos/Undefined.java b/sdk/src/main/java/com/azure/data/cosmos/Undefined.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/Undefined.java rename to sdk/src/main/java/com/azure/data/cosmos/Undefined.java diff --git a/commons/src/main/java/com/azure/data/cosmos/UniqueKey.java b/sdk/src/main/java/com/azure/data/cosmos/UniqueKey.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/UniqueKey.java rename to sdk/src/main/java/com/azure/data/cosmos/UniqueKey.java diff --git a/commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java b/sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java b/sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java b/sdk/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java b/sdk/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java similarity index 99% rename from gateway/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java index b537fd1b557f6..5b6bd3439f0e2 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.directconnectivity.HttpUtils; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import org.apache.commons.lang3.StringUtils; import javax.crypto.Mac; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java b/sdk/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Bytes.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Bytes.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Bytes.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Bytes.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java similarity index 99% rename from gateway/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java index cb4722343f61f..032f439056100 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.RetryOptions; -import com.azure.data.cosmos.directconnectivity.WebExceptionUtility; +import com.azure.data.cosmos.internal.directconnectivity.WebExceptionUtility; import org.apache.commons.collections4.list.UnmodifiableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Configs.java similarity index 99% rename from commons/src/main/java/com/azure/data/cosmos/internal/Configs.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Configs.java index 4f32c496e2732..0913c35ba1ee0 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/Configs.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/Configs.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Constants.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Constants.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Constants.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Constants.java diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java similarity index 92% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java index fd8aa47c9774e..4b37c8e9f1555 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/DatabaseForTest.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java @@ -21,9 +21,13 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.SqlParameter; +import com.azure.data.cosmos.SqlParameterList; +import com.azure.data.cosmos.SqlQuerySpec; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -35,8 +39,6 @@ import java.time.format.DateTimeFormatter; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; - public class DatabaseForTest { private static Logger logger = LoggerFactory.getLogger(DatabaseForTest.class); public static final String SHARED_DB_ID_PREFIX = "RxJava.SDKTest.SharedDatabase"; @@ -96,7 +98,7 @@ public static DatabaseForTest create(DatabaseManager client) { Database db = client.createDatabase(dbDef).single().block().getResource(); DatabaseForTest dbForTest = DatabaseForTest.from(db); - assertThat(dbForTest).isNotNull(); + assert(dbForTest != null); return dbForTest; } @@ -108,7 +110,7 @@ public static void cleanupStaleTestDatabases(DatabaseManager client) { .flatMap(page -> Flux.fromIterable(page.results())).collectList().block(); for (Database db : dbs) { - assertThat(db.id()).startsWith(DatabaseForTest.SHARED_DB_ID_PREFIX); + assert(db.id().startsWith(DatabaseForTest.SHARED_DB_ID_PREFIX)); DatabaseForTest dbForTest = DatabaseForTest.from(db); diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java similarity index 96% rename from commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java index 8e368d7b9a2b7..bc056e69e3a97 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java @@ -26,9 +26,9 @@ import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.directconnectivity.StoreResponse; -import com.azure.data.cosmos.directconnectivity.StoreResult; -import com.azure.data.cosmos.directconnectivity.TimeoutHelper; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.directconnectivity.StoreResult; +import com.azure.data.cosmos.internal.directconnectivity.TimeoutHelper; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import java.net.URL; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java b/sdk/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Exceptions.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Exceptions.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Exceptions.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Exceptions.java diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java b/sdk/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java b/sdk/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java b/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java b/sdk/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java b/sdk/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Integers.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Integers.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Integers.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Integers.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java b/sdk/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Lists.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Lists.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Lists.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Lists.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Longs.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Longs.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Longs.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Longs.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java b/sdk/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java b/sdk/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java b/sdk/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Offer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Offer.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Offer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Offer.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/OperationType.java b/sdk/src/main/java/com/azure/data/cosmos/internal/OperationType.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/OperationType.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/OperationType.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java b/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/PathInfo.java b/sdk/src/main/java/com/azure/data/cosmos/internal/PathInfo.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/PathInfo.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/PathInfo.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/PathParser.java b/sdk/src/main/java/com/azure/data/cosmos/internal/PathParser.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/PathParser.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/PathParser.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Paths.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Paths.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Paths.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Paths.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Permission.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Permission.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Permission.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Permission.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Quadruple.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Quadruple.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Quadruple.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Quadruple.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java b/sdk/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java b/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java b/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java b/sdk/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RMResources.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RMResources.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/RMResources.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RMResources.java diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/ResourceId.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceId.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/ResourceId.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ResourceId.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java index b0c66f5a90921..78dde448d51bc 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java @@ -25,9 +25,6 @@ import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.internal.Constants; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import org.apache.commons.lang3.StringUtils; import java.time.Duration; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/ResourceType.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceType.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/ResourceType.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ResourceType.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java index 0fa8465ed6c7c..cd7d6cb429d93 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java @@ -45,14 +45,14 @@ import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.TokenResolver; -import com.azure.data.cosmos.directconnectivity.GatewayServiceConfigurationReader; -import com.azure.data.cosmos.directconnectivity.ServerStoreModel; -import com.azure.data.cosmos.directconnectivity.StoreClient; -import com.azure.data.cosmos.directconnectivity.StoreClientFactory; import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import com.azure.data.cosmos.internal.caches.RxCollectionCache; import com.azure.data.cosmos.internal.caches.RxPartitionKeyRangeCache; +import com.azure.data.cosmos.internal.directconnectivity.GatewayServiceConfigurationReader; import com.azure.data.cosmos.internal.directconnectivity.GlobalAddressResolver; +import com.azure.data.cosmos.internal.directconnectivity.ServerStoreModel; +import com.azure.data.cosmos.internal.directconnectivity.StoreClient; +import com.azure.data.cosmos.internal.directconnectivity.StoreClientFactory; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpClientConfig; import com.azure.data.cosmos.internal.query.DocumentQueryExecutionContextFactory; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java similarity index 99% rename from commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java index 96d1142e21fc2..89577ae39c051 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java index 1b64cdee62658..a8a43a7af15f0 100644 --- a/commons/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java @@ -31,8 +31,8 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.directconnectivity.Address; -import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.directconnectivity.Address; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java similarity index 99% rename from gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java index 583936a30b9dc..9eebe2bea3653 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java @@ -28,8 +28,8 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.directconnectivity.HttpUtils; -import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpHeaders; import com.azure.data.cosmos.internal.http.HttpRequest; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java b/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Strings.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Strings.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Strings.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Strings.java diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java b/sdk/src/main/java/com/azure/data/cosmos/internal/TestConfigurations.java similarity index 99% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/TestConfigurations.java index 81ca2a45bb4a9..ce78c7d99d395 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/TestConfigurations.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/TestConfigurations.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.rx; +package com.azure.data.cosmos.internal; import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Trigger.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Trigger.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Trigger.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Trigger.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/User.java b/sdk/src/main/java/com/azure/data/cosmos/internal/User.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/User.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/User.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java b/sdk/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/Utils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Utils.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/Utils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Utils.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java b/sdk/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java similarity index 97% rename from gateway/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java index 8b145e42d50d7..f48f280481c06 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.directconnectivity.WebExceptionUtility; +import com.azure.data.cosmos.internal.directconnectivity.WebExceptionUtility; import org.apache.commons.lang3.time.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java similarity index 99% rename from gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java index d42e157e8f7b7..234c7b25b982e 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java @@ -24,7 +24,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import reactor.core.publisher.Mono; import java.util.concurrent.Callable; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java index 5057a560a2018..07d99280dff9e 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java @@ -22,9 +22,9 @@ */ package com.azure.data.cosmos.internal.caches; -import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; import com.azure.data.cosmos.internal.IRoutingMapProvider; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import com.azure.data.cosmos.internal.routing.Range; import reactor.core.publisher.Mono; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java index a76199b3b968b..6085c00b72e06 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java @@ -26,11 +26,11 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; -import com.azure.data.cosmos.internal.PartitionKeyRange; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java index b1b8fadfea04e..eacfd90aea4b0 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java @@ -24,9 +24,9 @@ import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.CosmosDatabaseResponse; @@ -36,8 +36,8 @@ import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.PartitionKeyRange; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java index 336577103e4eb..2ba022de1737c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java @@ -24,7 +24,6 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.Document; -//import com.azure.data.cosmos.internal.changefeed.internal.Constants; import com.azure.data.cosmos.internal.Constants; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @@ -35,6 +34,8 @@ import java.util.HashMap; import java.util.Map; +//import com.azure.data.cosmos.internal.changefeed.internal.Constants; + /** * Document service lease. */ diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java index 6a24632d086db..ebe5b71241160 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java @@ -22,10 +22,10 @@ */ package com.azure.data.cosmos.internal.changefeed.implementation; +import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverCloseReason; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; -import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.internal.changefeed.CheckpointFrequency; import java.time.Duration; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java index eb1ab95444607..b08b27dd9b5db 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java @@ -25,9 +25,9 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosContainerRequestOptions; import com.azure.data.cosmos.CosmosContainerResponse; -import com.azure.data.cosmos.CosmosContainerProperties; import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.CosmosDatabaseResponse; @@ -37,8 +37,8 @@ import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java index cbf3fe6939d09..4454a1a493d54 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; import com.azure.data.cosmos.internal.changefeed.PartitionCheckpointer; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java index 0fe7ad21152f8..43e8be64aee3a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java @@ -22,14 +22,14 @@ */ package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; -import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverFactory; import com.azure.data.cosmos.ChangeFeedProcessor; import com.azure.data.cosmos.ChangeFeedProcessorOptions; import com.azure.data.cosmos.CosmosContainer; +import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.internal.changefeed.Bootstrapper; import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverFactory; import com.azure.data.cosmos.internal.changefeed.CheckpointFrequency; import com.azure.data.cosmos.internal.changefeed.HealthMonitor; import com.azure.data.cosmos.internal.changefeed.LeaseStoreManager; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java index d908f6f25c328..f228389e59514 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java @@ -22,10 +22,10 @@ */ package com.azure.data.cosmos.internal.changefeed.implementation; +import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverCloseReason; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; -import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.internal.changefeed.exceptions.ObserverException; import java.util.List; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java index 6d0a1d00d2d8a..87e6bc3405883 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java @@ -22,10 +22,10 @@ */ package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; import com.azure.data.cosmos.ChangeFeedProcessorOptions; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; import com.azure.data.cosmos.internal.changefeed.Lease; import com.azure.data.cosmos.internal.changefeed.LeaseCheckpointer; import com.azure.data.cosmos.internal.changefeed.PartitionCheckpointer; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java index ef454fc40f0de..1b978f9907f3b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java @@ -22,14 +22,14 @@ */ package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; -import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.changefeed.CancellationToken; import com.azure.data.cosmos.internal.changefeed.ChangeFeedContextClient; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; +import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; import com.azure.data.cosmos.internal.changefeed.PartitionCheckpointer; import com.azure.data.cosmos.internal.changefeed.PartitionProcessor; import com.azure.data.cosmos.internal.changefeed.ProcessorSettings; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java index c9414d8a71cb4..2f86448ca9e60 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java @@ -22,9 +22,9 @@ */ package com.azure.data.cosmos.internal.changefeed.implementation; +import com.azure.data.cosmos.ChangeFeedProcessorOptions; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverFactory; -import com.azure.data.cosmos.ChangeFeedProcessorOptions; import com.azure.data.cosmos.internal.changefeed.Lease; import com.azure.data.cosmos.internal.changefeed.LeaseManager; import com.azure.data.cosmos.internal.changefeed.LeaseRenewer; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java index 870c35061074e..e2945bef2f7db 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java @@ -22,11 +22,11 @@ */ package com.azure.data.cosmos.internal.changefeed.implementation; +import com.azure.data.cosmos.internal.changefeed.CancellationToken; +import com.azure.data.cosmos.internal.changefeed.CancellationTokenSource; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserver; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverCloseReason; import com.azure.data.cosmos.internal.changefeed.ChangeFeedObserverContext; -import com.azure.data.cosmos.internal.changefeed.CancellationToken; -import com.azure.data.cosmos.internal.changefeed.CancellationTokenSource; import com.azure.data.cosmos.internal.changefeed.Lease; import com.azure.data.cosmos.internal.changefeed.LeaseRenewer; import com.azure.data.cosmos.internal.changefeed.PartitionProcessor; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java index caa3a083870cc..be23b47ae7107 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos.internal.changefeed.implementation; import com.azure.data.cosmos.internal.changefeed.Lease; -import com.azure.data.cosmos.internal.changefeed.LeaseManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Address.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Address.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/directconnectivity/Address.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Address.java index 18baa1c64c32c..bdfc3c190d4e8 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Address.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Address.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Resource; diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/AddressInformation.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressInformation.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/directconnectivity/AddressInformation.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressInformation.java index 606288ca2072c..044832816380c 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/AddressInformation.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressInformation.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import java.util.Objects; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java index 043aca5d1ef4f..a5bb8e5ad241f 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressResolver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java @@ -21,20 +21,20 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.PartitionKeyRangeGoneException; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.BadRequestException; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.InvalidPartitionException; import com.azure.data.cosmos.NotFoundException; +import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ICollectionRoutingMapCache; import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.ResourceId; import com.azure.data.cosmos.internal.ResourceType; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelector.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelector.java index d3e085d3f3515..05c72415d6671 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/AddressSelector.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelector.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelper.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelper.java index bfe5e4dd465b0..2eca282760cfd 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelper.java @@ -21,12 +21,12 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.PathsHelper; import com.azure.data.cosmos.internal.RMResources; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java index ebc83142ac6ee..17898bbc60764 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyReader.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java @@ -21,19 +21,19 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.RequestTimeoutException; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; @@ -403,7 +403,7 @@ public int getMinReplicaSetSize(RxDocumentServiceRequest entity) { } } - StoreReader createStoreReader(TransportClient transportClient, + public StoreReader createStoreReader(TransportClient transportClient, AddressSelector addressSelector, ISessionContainer sessionContainer) { return new StoreReader(transportClient, @@ -411,7 +411,7 @@ StoreReader createStoreReader(TransportClient transportClient, sessionContainer); } - QuorumReader createQuorumReader(TransportClient transportClient, + public QuorumReader createQuorumReader(TransportClient transportClient, AddressSelector addressSelector, StoreReader storeReader, GatewayServiceConfigurationReader serviceConfigurationReader, diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java index 62493cb91e5c1..40e43cab17e97 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriter.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/CustomHeaders.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/CustomHeaders.java similarity index 96% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/CustomHeaders.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/CustomHeaders.java index 5842c88da2a56..7f89468297bb2 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/CustomHeaders.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/CustomHeaders.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; public final class CustomHeaders { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ErrorUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ErrorUtils.java similarity index 96% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ErrorUtils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ErrorUtils.java index ccb40aa15f6dc..0408e7e7b9dc7 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ErrorUtils.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ErrorUtils.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.http.HttpRequest; import com.azure.data.cosmos.internal.http.HttpResponse; @@ -32,7 +32,6 @@ import reactor.core.publisher.Mono; import java.net.URI; -import java.nio.charset.StandardCharsets; public class ErrorUtils { private static final Logger logger = LoggerFactory.getLogger(ErrorUtils.class); diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java index 4926462b93264..4c858afab2585 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java @@ -21,19 +21,19 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKeyRangeGoneException; -import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.Paths; import com.azure.data.cosmos.internal.PathsHelper; import com.azure.data.cosmos.internal.RMResources; @@ -243,7 +243,7 @@ public Mono tryGetAddresses(RxDocumentServiceRequest reque }); } - Mono> getServerAddressesViaGatewayAsync( + public Mono> getServerAddressesViaGatewayAsync( RxDocumentServiceRequest request, String collectionRid, List partitionKeyRangeIds, @@ -404,7 +404,7 @@ private Mono getAddressesForRangeId( }); } - Mono> getMasterAddressesViaGatewayAsync( + public Mono> getMasterAddressesViaGatewayAsync( RxDocumentServiceRequest request, ResourceType resourceType, String resourceAddress, diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java index 87a7bdf766631..7e480a92438f8 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReader.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java @@ -21,17 +21,17 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.DatabaseAccount; -import com.azure.data.cosmos.internal.ReplicationPolicy; import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.GlobalEndpointManager; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.ReplicationPolicy; import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.http.HttpClient; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java index ef9d095f266bc..791bbbe0a140d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java @@ -26,15 +26,9 @@ import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.directconnectivity.AddressInformation; -import com.azure.data.cosmos.directconnectivity.AddressResolver; -import com.azure.data.cosmos.directconnectivity.GatewayAddressCache; -import com.azure.data.cosmos.directconnectivity.GatewayServiceConfigurationReader; -import com.azure.data.cosmos.directconnectivity.IAddressResolver; -import com.azure.data.cosmos.directconnectivity.Protocol; import com.azure.data.cosmos.internal.GlobalEndpointManager; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.caches.RxCollectionCache; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java index 7dab50fe5479d..5cfeb3ae1cea4 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java @@ -21,18 +21,18 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.InvalidPartitionException; +import com.azure.data.cosmos.PartitionIsMigratingException; import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.RetryWithException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IRetryPolicy; -import com.azure.data.cosmos.InvalidPartitionException; -import com.azure.data.cosmos.PartitionIsMigratingException; -import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.Quadruple; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.time.StopWatch; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientUtils.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientUtils.java index 2495fc154d231..87e53b3647c40 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUtils.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientUtils.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClient.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClient.java index 24664a29ce060..8e1cbdad9cdc5 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/HttpTransportClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClient.java @@ -21,17 +21,22 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConflictException; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.ForbiddenException; import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.InternalServerErrorException; +import com.azure.data.cosmos.InvalidPartitionException; import com.azure.data.cosmos.LockedException; import com.azure.data.cosmos.MethodNotAllowedException; +import com.azure.data.cosmos.NotFoundException; +import com.azure.data.cosmos.PartitionIsMigratingException; import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.PreconditionFailedException; import com.azure.data.cosmos.RequestEntityTooLargeException; import com.azure.data.cosmos.RequestRateTooLargeException; @@ -42,15 +47,10 @@ import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Integers; -import com.azure.data.cosmos.InternalServerErrorException; -import com.azure.data.cosmos.InvalidPartitionException; import com.azure.data.cosmos.internal.Lists; import com.azure.data.cosmos.internal.Longs; import com.azure.data.cosmos.internal.MutableVolatile; -import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.PartitionIsMigratingException; -import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.PathsHelper; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.ResourceType; diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/HttpUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtils.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/directconnectivity/HttpUtils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtils.java index 39966eedadf34..1d3bc513800f5 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/HttpUtils.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtils.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.Constants.UrlEncodingInfo; import com.azure.data.cosmos.internal.HttpConstants; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressCache.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressCache.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressCache.java index b42b7a364de65..9a507d14f0305 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressCache.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressResolver.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressResolver.java similarity index 96% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressResolver.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressResolver.java index f051489d74d9f..e8a783002b926 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IAddressResolver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressResolver.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import reactor.core.publisher.Mono; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IStoreClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IStoreClient.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IStoreClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IStoreClient.java index 054db339f5f03..e06cd8c72e993 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/IStoreClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IStoreClient.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.IRetryPolicy; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Protocol.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Protocol.java similarity index 96% rename from commons/src/main/java/com/azure/data/cosmos/directconnectivity/Protocol.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Protocol.java index c954146856ac6..326f48939b542 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/Protocol.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Protocol.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import org.apache.commons.text.WordUtils; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QueryRequestPerformanceActivity.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QueryRequestPerformanceActivity.java similarity index 95% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QueryRequestPerformanceActivity.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QueryRequestPerformanceActivity.java index 06ac246bd0df4..e0805afffc0ed 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QueryRequestPerformanceActivity.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QueryRequestPerformanceActivity.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; // TODO troubleshooting info // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/258624 diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReader.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReader.java index 39fd468c16dc4..923f70a6ab604 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/QuorumReader.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReader.java @@ -21,15 +21,15 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.JavaStreamUtils; import com.azure.data.cosmos.internal.MutableVolatile; import com.azure.data.cosmos.internal.Quadruple; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReadMode.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReadMode.java similarity index 95% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReadMode.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReadMode.java index dcd2fa6ea4287..2368f4b5d5668 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReadMode.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReadMode.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; public enum ReadMode { Primary, // Test hook diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java index f0ffa9683344c..629121b8b2c27 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RequestHelper.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RequestHelper.java index ae119d14832eb..ad18b133b6d0b 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RequestHelper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RequestHelper.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResourceOperation.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResourceOperation.java similarity index 96% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResourceOperation.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResourceOperation.java index 5bf87fb41b639..230fa1d6ae0b7 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResourceOperation.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResourceOperation.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResponseUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResponseUtils.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResponseUtils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResponseUtils.java index 4383194fd9e74..6cecf893b76bc 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ResponseUtils.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResponseUtils.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.http.HttpHeaders; import com.azure.data.cosmos.internal.http.HttpRequest; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java similarity index 95% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java index 666432c1ed545..28cb645ee9f5b 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java @@ -22,17 +22,17 @@ * */ -package com.azure.data.cosmos.directconnectivity; - -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdEndpoint; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdMetrics; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdObjectMapper; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestArgs; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestRecord; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdServiceEndpoint; +package com.azure.data.cosmos.internal.directconnectivity; + import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdEndpoint; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdMetrics; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdObjectMapper; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdRequestArgs; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdRequestRecord; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdServiceEndpoint; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerProperties.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerProperties.java similarity index 96% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerProperties.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerProperties.java index 71379b780c5f6..bf79099d9e495 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerProperties.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerProperties.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; final public class ServerProperties { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerStoreModel.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerStoreModel.java index 395ded73c5de6..2c0731145e505 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServerStoreModel.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerStoreModel.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.BadRequestException; +import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceConfig.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServiceConfig.java similarity index 96% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceConfig.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServiceConfig.java index efd483ad8f8c4..c3c4c5c31bd7d 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/ServiceConfig.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServiceConfig.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; class ServiceConfig { final static ServiceConfig instance = new ServiceConfig(); diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java index 141dfd0b24edf..c495a6b00ee0e 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java @@ -21,11 +21,12 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.BackoffRetryUtility; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.Exceptions; @@ -33,7 +34,6 @@ import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.IRetryPolicy; import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.ResourceType; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClientFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClientFactory.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClientFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClientFactory.java index 82563a9ae0e43..6888f4908506d 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreClientFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClientFactory.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java index f2815bcb4c499..fd6fd838a503c 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/StoreReader.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java @@ -21,23 +21,23 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.BadRequestException; +import com.azure.data.cosmos.InternalServerErrorException; +import com.azure.data.cosmos.PartitionIsMigratingException; import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ISessionToken; import com.azure.data.cosmos.internal.Integers; -import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.MutableVolatile; import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.PartitionIsMigratingException; -import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.SessionTokenHelper; diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java similarity index 98% rename from commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java index 94d1d7dfb95e0..dad95e7bd76ce 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.internal.HttpConstants; diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResult.java similarity index 99% rename from commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResult.java index a855e5d20c705..e48054103547c 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResult.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResult.java @@ -21,14 +21,14 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ISessionToken; -import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.Strings; diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/TimeoutHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelper.java similarity index 97% rename from commons/src/main/java/com/azure/data/cosmos/directconnectivity/TimeoutHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelper.java index 269c76f164b79..c497f87dc20ae 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/TimeoutHelper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelper.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.RequestTimeoutException; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportClient.java similarity index 96% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportClient.java index a4c0c259c809a..2af1c428b5528 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportClient.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import reactor.core.publisher.Mono; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportException.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportException.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportException.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportException.java index 55e01323910da..306a820700c42 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/TransportException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportException.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; // TODO: DANOBLE: Use a TransportException derivative wherever CorruptFrameException is thrown in RntbdTransportClient // * Continue to throw IllegalArgumentException, IllegalStateException, and NullPointerException. diff --git a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/WFConstants.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WFConstants.java similarity index 99% rename from commons/src/main/java/com/azure/data/cosmos/directconnectivity/WFConstants.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WFConstants.java index f8cce3d41b647..d99a09217abdd 100644 --- a/commons/src/main/java/com/azure/data/cosmos/directconnectivity/WFConstants.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WFConstants.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; public class WFConstants { public static class BackendHeaders { diff --git a/gateway/src/main/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtility.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtility.java similarity index 98% rename from gateway/src/main/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtility.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtility.java index 0da7d3d68d975..5363972807f46 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtility.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtility.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.Utils; import io.netty.channel.ChannelException; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelHandler.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHandler.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelHandler.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHandler.java index 198c8600feeb4..a91f7859fefdc 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelHandler.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHandler.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelPool.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelPool.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelPool.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelPool.java index 021c3e5a409f3..132b3fc16b481 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdClientChannelPool.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelPool.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; @@ -45,8 +45,8 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdReporter.reportIssue; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdReporter.reportIssueUnless; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdReporter.reportIssue; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdReporter.reportIssueUnless; import static com.google.common.base.Preconditions.checkState; @JsonSerialize(using = RntbdClientChannelPool.JsonSerializer.class) diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdConstants.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdConstants.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdConstants.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdConstants.java index 14258b00e5d8e..a6bc01c32f95a 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdConstants.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdConstants.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContext.java similarity index 95% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContext.java index a826b3d29fad3..10f2fd894fb5f 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContext.java @@ -22,9 +22,9 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; -import com.azure.data.cosmos.directconnectivity.ServerProperties; +import com.azure.data.cosmos.internal.directconnectivity.ServerProperties; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -35,8 +35,8 @@ import java.util.HashMap; import java.util.UUID; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.CurrentProtocolVersion; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdContextHeader; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.CurrentProtocolVersion; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdContextHeader; import static com.google.common.base.Preconditions.checkState; public final class RntbdContext { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextDecoder.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextDecoder.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextDecoder.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextDecoder.java index 46d9f49e85405..d874549ccd907 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextDecoder.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextDecoder.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextException.java similarity index 93% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextException.java index ec9deab03e578..992e7664040f1 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextException.java @@ -22,11 +22,11 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosError; -import com.azure.data.cosmos.directconnectivity.TransportException; +import com.azure.data.cosmos.internal.directconnectivity.TransportException; import com.fasterxml.jackson.databind.node.ObjectNode; import io.netty.handler.codec.http.HttpResponseStatus; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextNegotiator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextNegotiator.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextNegotiator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextNegotiator.java index 2cf24b7678c77..58aa970ee3e73 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextNegotiator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextNegotiator.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.azure.data.cosmos.internal.UserAgentContainer; import com.azure.data.cosmos.internal.Utils; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequest.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequest.java similarity index 91% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequest.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequest.java index 26b2eb117596d..eb439ab06c67f 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequest.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequest.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.azure.data.cosmos.internal.UserAgentContainer; import com.fasterxml.jackson.annotation.JsonProperty; @@ -34,11 +34,11 @@ import java.nio.charset.StandardCharsets; import java.util.UUID; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.CurrentProtocolVersion; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdContextRequestHeader; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResourceType; import static com.azure.data.cosmos.internal.HttpConstants.Versions; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.CurrentProtocolVersion; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdContextRequestHeader; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdResourceType; public final class RntbdContextRequest { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestDecoder.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestDecoder.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java index 8efccde8d0cfe..473b98fc8ace8 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestDecoder.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestEncoder.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestEncoder.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java index 1df05d5031b4a..02d1f1b13a803 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdContextRequestEncoder.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdEndpoint.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdEndpoint.java similarity index 95% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdEndpoint.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdEndpoint.java index ed5e4f89fcb7a..d7c10dd127988 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdEndpoint.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdEndpoint.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.azure.data.cosmos.internal.UserAgentContainer; import io.netty.handler.logging.LogLevel; @@ -31,7 +31,7 @@ import java.net.URI; import java.util.stream.Stream; -import static com.azure.data.cosmos.directconnectivity.RntbdTransportClient.Options; +import static com.azure.data.cosmos.internal.directconnectivity.RntbdTransportClient.Options; import static com.google.common.base.Preconditions.checkNotNull; public interface RntbdEndpoint extends AutoCloseable { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdFramer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdFramer.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdFramer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdFramer.java index 271fadcb9912f..c856587132d0b 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdFramer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdFramer.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.CorruptedFrameException; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdMetrics.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdMetrics.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdMetrics.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdMetrics.java index a5a04a23ad00a..e7aee53bc5d63 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdMetrics.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdMetrics.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.codahale.metrics.Gauge; import com.codahale.metrics.Meter; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdObjectMapper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdObjectMapper.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdObjectMapper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdObjectMapper.java index 62fcba8dec08f..5b67ecf321514 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdObjectMapper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdObjectMapper.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdReporter.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdReporter.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdReporter.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdReporter.java index d6f01112287f5..c47aa2f9e4933 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdReporter.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdReporter.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequest.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequest.java similarity index 96% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequest.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequest.java index 3658385650684..777e439396358 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequest.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequest.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -30,7 +30,7 @@ import java.util.UUID; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdRequestHeader; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdRequestHeader; import static com.google.common.base.Preconditions.checkNotNull; public final class RntbdRequest { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestArgs.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestArgs.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestArgs.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestArgs.java index b04cdce7f3ee2..bf350c0e9b048 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestArgs.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestArgs.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.fasterxml.jackson.annotation.JsonIgnore; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestDecoder.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestDecoder.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestDecoder.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestDecoder.java index 92fb9b4adc455..53837fcfb2ac2 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestDecoder.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestDecoder.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestEncoder.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestEncoder.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestEncoder.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestEncoder.java index 4dc7ef56fe654..d96fd9c9df3ba 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestEncoder.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestEncoder.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFrame.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFrame.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFrame.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFrame.java index 815d8d846bb33..d650ce5be4a59 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFrame.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFrame.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; @@ -31,8 +31,8 @@ import java.util.Locale; import java.util.UUID; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResourceType; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdResourceType; final class RntbdRequestFrame { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFramer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFramer.java similarity index 95% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFramer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFramer.java index 344d077381f45..1dda4f7d544ad 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestFramer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFramer.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestHeaders.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestHeaders.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestHeaders.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestHeaders.java index 9d27a78f1aa82..4a07dbb95744a 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestHeaders.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestHeaders.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.azure.data.cosmos.ConsistencyLevel; @@ -47,18 +47,18 @@ import java.util.Map; import java.util.function.Supplier; -import static com.azure.data.cosmos.directconnectivity.WFConstants.BackendHeaders; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdConsistencyLevel; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdContentSerializationFormat; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdEnumerationDirection; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdFanoutOperationState; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdIndexingDirective; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdMigrateCollectionDirective; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdReadFeedKeyType; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdRemoteStorageType; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdRequestHeader; import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; +import static com.azure.data.cosmos.internal.directconnectivity.WFConstants.BackendHeaders; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdConsistencyLevel; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdContentSerializationFormat; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdEnumerationDirection; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdFanoutOperationState; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdIndexingDirective; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdMigrateCollectionDirective; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdOperationType; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdReadFeedKeyType; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdRemoteStorageType; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdRequestHeader; import static com.google.common.base.Preconditions.checkNotNull; @JsonFilter("RntbdToken") diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestManager.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestManager.java index 186c99766c3e2..5f270c5136925 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestManager.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestManager.java @@ -21,32 +21,32 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.ConflictException; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosError; -import com.azure.data.cosmos.ConflictException; import com.azure.data.cosmos.ForbiddenException; import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.InternalServerErrorException; +import com.azure.data.cosmos.InvalidPartitionException; import com.azure.data.cosmos.LockedException; import com.azure.data.cosmos.MethodNotAllowedException; +import com.azure.data.cosmos.NotFoundException; +import com.azure.data.cosmos.PartitionIsMigratingException; import com.azure.data.cosmos.PartitionKeyRangeGoneException; +import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.PreconditionFailedException; import com.azure.data.cosmos.RequestEntityTooLargeException; import com.azure.data.cosmos.RequestRateTooLargeException; import com.azure.data.cosmos.RequestTimeoutException; import com.azure.data.cosmos.RetryWithException; import com.azure.data.cosmos.ServiceUnavailableException; -import com.azure.data.cosmos.directconnectivity.StoreResponse; import com.azure.data.cosmos.UnauthorizedException; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; -import com.azure.data.cosmos.BadRequestException; -import com.azure.data.cosmos.InternalServerErrorException; -import com.azure.data.cosmos.InvalidPartitionException; -import com.azure.data.cosmos.NotFoundException; -import com.azure.data.cosmos.PartitionIsMigratingException; -import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; import com.google.common.base.Strings; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; @@ -76,10 +76,10 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdReporter.reportIssue; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdReporter.reportIssueUnless; import static com.azure.data.cosmos.internal.HttpConstants.StatusCodes; import static com.azure.data.cosmos.internal.HttpConstants.SubStatusCodes; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdReporter.reportIssue; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdReporter.reportIssueUnless; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java similarity index 95% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java index ce0b34d831dc9..405a9673019ab 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestRecord.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java @@ -21,11 +21,11 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.RequestTimeoutException; -import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; import io.netty.util.Timeout; import io.netty.util.TimerTask; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestTimer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestTimer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java index 707bb44c33f27..54d6ae366dd1e 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdRequestTimer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.util.HashedWheelTimer; import io.netty.util.Timeout; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponse.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponse.java index bfe7a0f9ed1ed..fcb19bb4647da 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponse.java @@ -22,9 +22,9 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; -import com.azure.data.cosmos.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -45,7 +45,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static java.lang.Math.min; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseDecoder.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseDecoder.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseDecoder.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseDecoder.java index ca735c4de860c..5c26cdfe0d490 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseDecoder.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseDecoder.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseHeaders.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseHeaders.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseHeaders.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseHeaders.java index af19df8f67139..de97775a2a527 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseHeaders.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseHeaders.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.annotation.JsonProperty; @@ -41,10 +41,10 @@ import java.util.function.BiConsumer; import java.util.function.Function; -import static com.azure.data.cosmos.directconnectivity.WFConstants.BackendHeaders; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdIndexingDirective; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; import static com.azure.data.cosmos.internal.HttpConstants.HttpHeaders; +import static com.azure.data.cosmos.internal.directconnectivity.WFConstants.BackendHeaders; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdIndexingDirective; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdResponseHeader; @JsonFilter("RntbdToken") class RntbdResponseHeaders extends RntbdTokenStream { diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseStatus.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseStatus.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseStatus.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseStatus.java index 4988bf1aaf4e9..c5c3ad68f36de 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdResponseStatus.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseStatus.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java index ad9128736795c..c9a131243f08c 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdServiceEndpoint.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java @@ -22,12 +22,12 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.GoneException; -import com.azure.data.cosmos.directconnectivity.RntbdTransportClient.Options; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.directconnectivity.RntbdTransportClient.Options; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdToken.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdToken.java similarity index 97% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdToken.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdToken.java index c02e68fd1268f..513bc27b67924 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdToken.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdToken.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; @@ -33,7 +33,7 @@ import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import io.netty.buffer.ByteBuf; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdHeader; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdHeader; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenStream.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenStream.java similarity index 96% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenStream.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenStream.java index 9e47a16210709..7ddd442819527 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenStream.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenStream.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -31,7 +31,7 @@ import java.util.stream.Collector; -import static com.azure.data.cosmos.directconnectivity.rntbd.RntbdConstants.RntbdHeader; +import static com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdConstants.RntbdHeader; import static com.google.common.base.Preconditions.checkNotNull; @SuppressWarnings("UnstableApiUsage") diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenType.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenType.java similarity index 99% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenType.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenType.java index a88a944963bc5..c92562376cb10 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdTokenType.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenType.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import com.google.common.base.Strings; import com.google.common.base.Utf8; diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdUUID.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdUUID.java similarity index 98% rename from direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdUUID.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdUUID.java index 37ed4f14f7bcd..c8a6dc9bd3056 100644 --- a/direct-impl/src/main/java/com/azure/data/cosmos/directconnectivity/rntbd/RntbdUUID.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdUUID.java @@ -22,7 +22,7 @@ * */ -package com.azure.data.cosmos.directconnectivity.rntbd; +package com.azure.data.cosmos.internal.directconnectivity.rntbd; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java b/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java b/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java b/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java b/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java index 1c00989f57a33..6f52e5c998975 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java @@ -26,11 +26,11 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.Undefined; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.internal.query.aggregation.AggregateOperator; import com.azure.data.cosmos.internal.query.aggregation.Aggregator; import com.azure.data.cosmos.internal.query.aggregation.AverageAggregator; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java index 1aabf7b8a54a0..f2f18806e2e08 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java @@ -25,8 +25,6 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.BackoffRetryUtility; @@ -34,8 +32,10 @@ import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; import com.azure.data.cosmos.internal.InvalidPartitionExceptionRetryPolicy; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.PartitionKeyRangeGoneRetryPolicy; import com.azure.data.cosmos.internal.PathsHelper; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Strings; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java index 80f06f6fe1942..e3cc355c71255 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java @@ -27,14 +27,14 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.JsonSerializable; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.QueryMetrics; -import com.azure.data.cosmos.internal.QueryMetricsConstants; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; import com.azure.data.cosmos.internal.ObservableHelper; +import com.azure.data.cosmos.internal.PartitionKeyRange; +import com.azure.data.cosmos.internal.QueryMetrics; +import com.azure.data.cosmos.internal.QueryMetricsConstants; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java similarity index 99% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java index 49f7b0cb75f0d..61cb796dde8f5 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java @@ -26,12 +26,12 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.SqlParameterList; -import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.SqlParameterList; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.ReplicatedResourceClientUtils; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RuntimeConstants.MediaTypes; @@ -49,8 +49,6 @@ import java.util.Map; import java.util.UUID; -import static com.azure.data.cosmos.CommonsBridgeInternal.partitionKeyRangeIdInternal; - /** * While this class is public, but it is not part of our published public APIs. * This is meant to be internally used only by our sdk. diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java index 9531ae30c84a9..7c52b54ae4044 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java @@ -22,15 +22,15 @@ */ package com.azure.data.cosmos.internal.query; +import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java similarity index 97% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java index 564b836d1e426..73ccbd5b52066 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java @@ -23,7 +23,9 @@ package com.azure.data.cosmos.internal.query; -import com.azure.data.cosmos.*; +import com.azure.data.cosmos.BridgeInternal; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java index 0695f55fd6e0c..d5b4cec4e74bd 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java @@ -25,11 +25,11 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.PartitionKeyRange; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Utils; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java index 4868801c15f3c..32514f32a46a7 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java @@ -26,12 +26,12 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.PartitionKeyRange; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java index 532b2db6f443e..2cd35c048a347 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java @@ -22,9 +22,9 @@ */ package com.azure.data.cosmos.internal.query; -import com.azure.data.cosmos.internal.QueryMetrics; -import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.BadRequestException; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceId; import com.azure.data.cosmos.internal.query.orderbyquery.OrderByRowResult; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java index 7c820fa0b542c..074f84dfd0171 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java @@ -26,11 +26,11 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.RequestChargeTracker; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java index 43236c5165c0c..52625723d24c2 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java @@ -26,11 +26,11 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IDocumentClientRetryPolicy; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.Strings; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java index c2182d3a54dd4..606d95618af60 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java @@ -24,9 +24,9 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.Utils; import reactor.core.publisher.Flux; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java index d754f6c2e9ab0..6601b759d38eb 100644 --- a/gateway/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java @@ -26,11 +26,11 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.internal.Exceptions; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.Utils; import org.slf4j.Logger; diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/Range.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/Range.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/Range.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java diff --git a/gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java similarity index 100% rename from gateway/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java diff --git a/direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java similarity index 100% rename from direct-impl/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java diff --git a/commons/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java similarity index 100% rename from commons/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/BridgeUtils.java b/sdk/src/test/java/com/azure/data/cosmos/BridgeUtils.java similarity index 100% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/BridgeUtils.java rename to sdk/src/test/java/com/azure/data/cosmos/BridgeUtils.java diff --git a/commons/src/test/java/com/azure/data/cosmos/ConflictTests.java b/sdk/src/test/java/com/azure/data/cosmos/ConflictTests.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/ConflictTests.java rename to sdk/src/test/java/com/azure/data/cosmos/ConflictTests.java diff --git a/commons/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java b/sdk/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java similarity index 97% rename from commons/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java rename to sdk/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java index 097b4e31e8c99..ee9878c43ccb5 100644 --- a/commons/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java rename to sdk/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java index 82e3908bf3b55..959f2810ab803 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java @@ -22,21 +22,11 @@ */ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.Paths; -import com.azure.data.cosmos.internal.RequestOptions; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpClientConfig; import com.azure.data.cosmos.internal.http.HttpHeaders; import com.azure.data.cosmos.internal.http.HttpRequest; -import com.azure.data.cosmos.rx.FeedResponseListValidator; -import com.azure.data.cosmos.rx.TestConfigurations; import com.azure.data.cosmos.rx.TestSuiteBase; import io.netty.handler.codec.http.HttpMethod; import org.testng.annotations.AfterClass; diff --git a/commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java b/sdk/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java rename to sdk/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java diff --git a/commons/src/test/java/com/azure/data/cosmos/DocumentTests.java b/sdk/src/test/java/com/azure/data/cosmos/DocumentTests.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/DocumentTests.java rename to sdk/src/test/java/com/azure/data/cosmos/DocumentTests.java diff --git a/gateway/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java b/sdk/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java similarity index 100% rename from gateway/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java rename to sdk/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java diff --git a/commons/src/test/java/com/azure/data/cosmos/IncludedPathTest.java b/sdk/src/test/java/com/azure/data/cosmos/IncludedPathTest.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/IncludedPathTest.java rename to sdk/src/test/java/com/azure/data/cosmos/IncludedPathTest.java diff --git a/commons/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java b/sdk/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java rename to sdk/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java b/sdk/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java similarity index 100% rename from direct-impl/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java rename to sdk/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java diff --git a/commons/src/test/java/com/azure/data/cosmos/PermissionTest.java b/sdk/src/test/java/com/azure/data/cosmos/PermissionTest.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/PermissionTest.java rename to sdk/src/test/java/com/azure/data/cosmos/PermissionTest.java diff --git a/commons/src/test/java/com/azure/data/cosmos/ResourceIdTests.java b/sdk/src/test/java/com/azure/data/cosmos/ResourceIdTests.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/ResourceIdTests.java rename to sdk/src/test/java/com/azure/data/cosmos/ResourceIdTests.java diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java similarity index 100% rename from gateway/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/ConfigsBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsBuilder.java similarity index 92% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/ConfigsBuilder.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsBuilder.java index 7ce6c9dc8b50a..f2eba61d20dda 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/ConfigsBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsBuilder.java @@ -21,10 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.directconnectivity.Protocol; -import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import org.mockito.Mockito; /** diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java similarity index 97% rename from commons/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java index 1a06987926f2d..2e7d95c474d87 100644 --- a/commons/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java index 6dbd216ba97e3..30c7127d1d666 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java @@ -32,9 +32,9 @@ import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKind; -import com.azure.data.cosmos.rx.FailureValidator; -import com.azure.data.cosmos.rx.ResourceResponseValidator; -import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.ResourceResponseValidator; +import com.azure.data.cosmos.internal.TestConfigurations; import org.testng.SkipException; import org.testng.annotations.Test; import reactor.core.publisher.Flux; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java index df7048f27c722..5a37940dbc4cd 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java @@ -34,10 +34,8 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; -import com.azure.data.cosmos.rx.FailureValidator; -import com.azure.data.cosmos.rx.TestConfigurations; import org.apache.commons.lang3.Range; import org.testng.annotations.Test; import reactor.core.publisher.Flux; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java index 6d26342c51c1f..4ab441b19f369 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java @@ -38,12 +38,9 @@ import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKind; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.azure.data.cosmos.internal.routing.Range; -import com.azure.data.cosmos.rx.FailureValidator; -import com.azure.data.cosmos.rx.ResourceResponseValidator; -import com.azure.data.cosmos.rx.TestConfigurations; import org.apache.commons.collections4.map.UnmodifiableMap; import org.apache.commons.lang3.StringUtils; import org.testng.SkipException; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java index 9ed9aed385d3d..543da492abc08 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java @@ -32,7 +32,6 @@ import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.SpyClientBuilder; import com.azure.data.cosmos.internal.http.HttpRequest; -import com.azure.data.cosmos.rx.Utils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; @@ -60,11 +59,11 @@ public class DocumentQuerySpyWireContentTest extends TestSuiteBase { private SpyClientUnderTestFactory.ClientUnderTest client; public String getSinglePartitionCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.id(), createdSinglePartitionCollection.id()); + return TestUtils.getCollectionNameLink(createdDatabase.id(), createdSinglePartitionCollection.id()); } public String getMultiPartitionCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.id(), createdMultiPartitionCollection.id()); + return TestUtils.getCollectionNameLink(createdDatabase.id(), createdMultiPartitionCollection.id()); } @Factory(dataProvider = "clientBuilders") diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestContextValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestContextValidator.java similarity index 95% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestContextValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestContextValidator.java index 807b0da136b64..1075d78b8d5bf 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestContextValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestContextValidator.java @@ -21,10 +21,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.rx; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.directconnectivity.StoreResponse; -import com.azure.data.cosmos.internal.DocumentServiceRequestContext; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; import java.util.ArrayList; import java.util.List; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestValidator.java similarity index 95% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestValidator.java index 2f55d6f53ed4f..b599a39ea5528 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/DocumentServiceRequestValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestValidator.java @@ -20,11 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.rx; - -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +package com.azure.data.cosmos.internal; import java.util.ArrayList; import java.util.List; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/FailureValidator.java similarity index 98% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/FailureValidator.java index f7a1ff3b40af8..c45ccbc696ce7 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FailureValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/FailureValidator.java @@ -20,14 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.rx; +package com.azure.data.cosmos.internal; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosError; -import com.azure.data.cosmos.directconnectivity.WFConstants; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.RMResources; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import java.util.ArrayList; import java.util.List; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java similarity index 99% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java index 152b4e9ac1cbf..31380c1e2f7b8 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseListValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java @@ -20,14 +20,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.rx; +package com.azure.data.cosmos.internal; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.Resource; import com.fasterxml.jackson.databind.node.ArrayNode; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseValidator.java similarity index 98% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseValidator.java index 7aeec1e6680cd..20a190603c25d 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/FeedResponseValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseValidator.java @@ -20,11 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.rx; +package com.azure.data.cosmos.internal; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.internal.HttpConstants; import java.util.ArrayList; import java.util.List; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUnderTestWrapper.java b/sdk/src/test/java/com/azure/data/cosmos/internal/HttpClientUnderTestWrapper.java similarity index 97% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUnderTestWrapper.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/HttpClientUnderTestWrapper.java index 6a50b555bafe0..d7543eaafc597 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/HttpClientUnderTestWrapper.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/HttpClientUnderTestWrapper.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpRequest; diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java similarity index 100% rename from gateway/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java index 464d7bf4f6723..46f6ea1967e6d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.FailureValidator; import org.mockito.Mockito; import org.testng.annotations.AfterClass; import org.testng.annotations.Factory; diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java similarity index 99% rename from gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java index 1d145a0ae702e..169557c82f532 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.NotFoundException; -import com.azure.data.cosmos.directconnectivity.WFConstants; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import io.netty.handler.timeout.ReadTimeoutException; import org.mockito.Mockito; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java similarity index 97% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java index a3d61ec42d33e..6f4174777e031 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceResponseValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java @@ -20,24 +20,18 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.rx; +package com.azure.data.cosmos.internal; import com.azure.data.cosmos.Attachment; import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.IndexingMode; -import com.azure.data.cosmos.internal.Offer; -import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.SpatialSpec; import com.azure.data.cosmos.SpatialType; -import com.azure.data.cosmos.internal.StoredProcedure; -import com.azure.data.cosmos.internal.Trigger; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; -import com.azure.data.cosmos.internal.UserDefinedFunction; import org.assertj.core.api.Condition; import java.time.Instant; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceValidator.java similarity index 96% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ResourceValidator.java index b5a927d58b293..78a019628e461 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/ResourceValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceValidator.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.rx; +package com.azure.data.cosmos.internal; import com.azure.data.cosmos.Resource; @@ -29,7 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; -interface ResourceValidator { +public interface ResourceValidator { void validate(T v); diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/RetryAnalyzer.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryAnalyzer.java similarity index 95% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/RetryAnalyzer.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/RetryAnalyzer.java index b256707d13ebe..1289516c55037 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/RetryAnalyzer.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryAnalyzer.java @@ -22,9 +22,9 @@ */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.TestConfigurations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java index 3620b59fa2c5a..c3c5547c94915 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java @@ -30,8 +30,8 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.rx.FailureValidator; -import com.azure.data.cosmos.rx.ResourceResponseValidator; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.ResourceResponseValidator; import com.google.common.collect.ImmutableMap; import org.mockito.Mockito; import org.mockito.stubbing.Answer; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java index df6a96f1f23ed..8361ff9fbf718 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java @@ -32,8 +32,8 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.RetryOptions; -import com.azure.data.cosmos.rx.ResourceResponseValidator; -import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.ResourceResponseValidator; +import com.azure.data.cosmos.internal.TestConfigurations; import org.mockito.stubbing.Answer; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java similarity index 97% rename from direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java index 5812c55fe5928..9d4a156948f42 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java @@ -23,9 +23,8 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.GoneException; -import com.azure.data.cosmos.directconnectivity.StoreResponse; -import com.azure.data.cosmos.directconnectivity.StoreResponseBuilder; -import com.azure.data.cosmos.directconnectivity.StoreResponseValidator; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponseValidator; import com.azure.data.cosmos.internal.IRetryPolicy.ShouldRetryResult; import io.reactivex.subscribers.TestSubscriber; import org.mockito.Matchers; diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java similarity index 98% rename from gateway/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java index 1d09d160ad126..f451bc37838dc 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpRequest; -import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.FailureValidator; import io.netty.handler.timeout.ReadTimeoutException; import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java similarity index 100% rename from gateway/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java similarity index 100% rename from gateway/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java similarity index 98% rename from gateway/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java index 8b506df50f8e3..9416d990abbac 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.FailureValidator; import java.time.Duration; import java.util.ArrayList; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java index 0ebd0656078dc..20fa70001d066 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.SpyClientBuilder; -import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import com.azure.data.cosmos.internal.directconnectivity.ReflectionUtils; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpHeaders; diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponseBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/internal/StoreResponseBuilder.java similarity index 95% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponseBuilder.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/StoreResponseBuilder.java index 3e9e95d0c614a..a42cf98178fcb 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/directconnectivity/StoreResponseBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/StoreResponseBuilder.java @@ -21,9 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import java.math.BigDecimal; import java.util.AbstractMap; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index bdb9c5c3c59ba..11cdb831f745f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -33,7 +33,6 @@ import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DataType; import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DatabaseForTest; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.DocumentCollection; @@ -48,12 +47,7 @@ import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; import com.azure.data.cosmos.Undefined; -import com.azure.data.cosmos.directconnectivity.Protocol; -import com.azure.data.cosmos.rx.FailureValidator; -import com.azure.data.cosmos.rx.FeedResponseListValidator; -import com.azure.data.cosmos.rx.ResourceResponseValidator; -import com.azure.data.cosmos.rx.TestConfigurations; -import com.azure.data.cosmos.rx.Utils; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -160,7 +154,6 @@ public Flux> createDatabase(Database databaseDefiniti @Override public Flux> deleteDatabase(String id) { - return client.deleteDatabase("dbs/" + id, null); } } @@ -443,7 +436,7 @@ public static Document createDocument(AsyncDocumentClient client, String databas } public static Document createDocument(AsyncDocumentClient client, String databaseId, String collectionId, Document document, RequestOptions options) { - return client.createDocument(Utils.getCollectionNameLink(databaseId, collectionId), document, options, false).single().block().getResource(); + return client.createDocument(TestUtils.getCollectionNameLink(databaseId, collectionId), document, options, false).single().block().getResource(); } public Flux> bulkInsert(AsyncDocumentClient client, @@ -533,7 +526,7 @@ public static void deleteCollectionIfExists(AsyncDocumentClient client, String d String.format("SELECT * FROM root r where r.id = '%s'", collectionId), null).single().block() .results(); if (!res.isEmpty()) { - deleteCollection(client, Utils.getCollectionNameLink(databaseId, collectionId)); + deleteCollection(client, TestUtils.getCollectionNameLink(databaseId, collectionId)); } } @@ -545,10 +538,10 @@ public static void deleteDocumentIfExists(AsyncDocumentClient client, String dat FeedOptions options = new FeedOptions(); options.partitionKey(new PartitionKey(docId)); List res = client - .queryDocuments(Utils.getCollectionNameLink(databaseId, collectionId), String.format("SELECT * FROM root r where r.id = '%s'", docId), options) + .queryDocuments(TestUtils.getCollectionNameLink(databaseId, collectionId), String.format("SELECT * FROM root r where r.id = '%s'", docId), options) .single().block().results(); if (!res.isEmpty()) { - deleteDocument(client, Utils.getDocumentNameLink(databaseId, collectionId, docId)); + deleteDocument(client, TestUtils.getDocumentNameLink(databaseId, collectionId, docId)); } } @@ -557,7 +550,7 @@ public static void safeDeleteDocument(AsyncDocumentClient client, String documen try { client.deleteDocument(documentLink, options).single().block(); } catch (Exception e) { - CosmosClientException dce = com.azure.data.cosmos.internal.Utils.as(e, CosmosClientException.class); + CosmosClientException dce = Utils.as(e, CosmosClientException.class); if (dce == null || dce.statusCode() != 404) { throw e; } @@ -574,7 +567,7 @@ public static void deleteUserIfExists(AsyncDocumentClient client, String databas .queryUsers("dbs/" + databaseId, String.format("SELECT * FROM root r where r.id = '%s'", userId), null) .single().block().results(); if (!res.isEmpty()) { - deleteUser(client, Utils.getUserNameLink(databaseId, userId)); + deleteUser(client, TestUtils.getUserNameLink(databaseId, userId)); } } @@ -623,7 +616,7 @@ static protected void safeDeleteDatabase(AsyncDocumentClient client, Database da static protected void safeDeleteDatabase(AsyncDocumentClient client, String databaseId) { if (client != null) { try { - client.deleteDatabase(Utils.getDatabaseNameLink(databaseId), null).single().block(); + client.deleteDatabase(TestUtils.getDatabaseNameLink(databaseId), null).single().block(); } catch (Exception e) { } } diff --git a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/Utils.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java similarity index 96% rename from commons-test-utils/src/main/java/com/azure/data/cosmos/rx/Utils.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java index 8c9a897eb508f..607b030714b9c 100644 --- a/commons-test-utils/src/main/java/com/azure/data/cosmos/rx/Utils.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java @@ -20,11 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.rx; +package com.azure.data.cosmos.internal; import com.azure.data.cosmos.Database; -public class Utils { +public class TestUtils { private static final String DATABASES_PATH_SEGMENT = "dbs"; private static final String COLLECTIONS_PATH_SEGMENT = "colls"; private static final String DOCUMENTS_PATH_SEGMENT = "docs"; @@ -57,6 +57,6 @@ public static String getUserNameLink(String databaseId, String userId) { return DATABASES_PATH_SEGMENT + "/" + databaseId + "/" + USERS_PATH_SEGMENT + "/" + userId; } - private Utils() { + private TestUtils() { } } diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java similarity index 100% rename from gateway/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java similarity index 99% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java index df7ea57d585b1..d2fd5b7d63d4c 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.DocumentCollection; @@ -37,6 +37,10 @@ import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.caches.RxCollectionCache; +import com.azure.data.cosmos.internal.directconnectivity.AddressInformation; +import com.azure.data.cosmos.internal.directconnectivity.AddressResolver; +import com.azure.data.cosmos.internal.directconnectivity.IAddressCache; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import com.azure.data.cosmos.internal.routing.IServerIdentity; import com.azure.data.cosmos.internal.routing.InMemoryCollectionRoutingMap; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorTest.java similarity index 93% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorTest.java index 2b1043a7dbb39..c9b786e5246c5 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorTest.java @@ -21,10 +21,18 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.internal.directconnectivity.AddressInformation; +import com.azure.data.cosmos.internal.directconnectivity.AddressSelector; +import com.azure.data.cosmos.internal.directconnectivity.IAddressResolver; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.directconnectivity.AddressInformation; +import com.azure.data.cosmos.internal.directconnectivity.AddressSelector; +import com.azure.data.cosmos.internal.directconnectivity.IAddressResolver; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import com.google.common.collect.ImmutableList; import org.mockito.Matchers; import org.mockito.Mockito; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorWrapper.java similarity index 97% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorWrapper.java index c7e72fb0dcfe9..6bd4741c34195 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/AddressSelectorWrapper.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorWrapper.java @@ -21,10 +21,16 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.internal.directconnectivity.AddressInformation; +import com.azure.data.cosmos.internal.directconnectivity.AddressSelector; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.directconnectivity.AddressInformation; +import com.azure.data.cosmos.internal.directconnectivity.AddressSelector; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.tuple.ImmutablePair; diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/AddressValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressValidator.java similarity index 93% rename from sdk/src/test/java/com/azure/data/cosmos/directconnectivity/AddressValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressValidator.java index 7284988311ec2..92578c444c7a6 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/AddressValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressValidator.java @@ -20,8 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.internal.directconnectivity.Address; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.directconnectivity.Address; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import org.assertj.core.api.Condition; import java.util.ArrayList; diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java similarity index 97% rename from sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java index 061db1e08477c..a5e6788486ae5 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/BarrierRequestHelperTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java @@ -21,18 +21,21 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.directconnectivity.BarrierRequestHelper; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentClientImpl; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.directconnectivity.BarrierRequestHelper; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.TestConfigurations; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java index 87f40978033db..c0d7ddf54c1af 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java @@ -21,26 +21,15 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.RequestRateTooLargeException; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.DocumentServiceRequestContext; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.ISessionToken; +import com.azure.data.cosmos.internal.directconnectivity.*; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.NotFoundException; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.RequestChargeTracker; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.Utils; -import com.azure.data.cosmos.internal.VectorSessionToken; -import com.azure.data.cosmos.rx.FailureValidator; import com.google.common.collect.ImmutableList; import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderUnderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java similarity index 93% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderUnderTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java index 7e2a8408a3096..29df907718c12 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyReaderUnderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java @@ -21,9 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.directconnectivity.*; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import org.mockito.Mockito; @@ -61,7 +62,7 @@ public StoreReaderUnderTest getSpyStoreReader() { } @Override - QuorumReader createQuorumReader(TransportClient transportClient, + public QuorumReader createQuorumReader(TransportClient transportClient, AddressSelector addressSelector, StoreReader storeReader, GatewayServiceConfigurationReader serviceConfigurationReader, @@ -76,7 +77,7 @@ QuorumReader createQuorumReader(TransportClient transportClient, } @Override - StoreReader createStoreReader(TransportClient transportClient, + public StoreReader createStoreReader(TransportClient transportClient, AddressSelector addressSelector, ISessionContainer sessionContainer) { this.origStoreReader = new StoreReaderUnderTest(transportClient, addressSelector, sessionContainer); diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java similarity index 97% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java index 334033c396825..3713bb9e7fd5d 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ConsistencyWriterTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java @@ -21,19 +21,18 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.PartitionKeyRangeGoneException; import com.azure.data.cosmos.RequestTimeoutException; -import com.azure.data.cosmos.internal.DocumentServiceRequestContext; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.directconnectivity.AddressSelector; +import com.azure.data.cosmos.internal.directconnectivity.ConsistencyWriter; +import com.azure.data.cosmos.internal.directconnectivity.GatewayServiceConfigurationReader; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.PartitionIsMigratingException; import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.Utils; -import com.azure.data.cosmos.rx.FailureValidator; import com.google.common.collect.ImmutableList; import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java similarity index 97% rename from sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java index b064991e51995..9230206614d4c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.AsyncDocumentClient.Builder; import com.azure.data.cosmos.BridgeInternal; @@ -43,10 +43,11 @@ import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; import com.azure.data.cosmos.internal.TestSuiteBase; -import com.azure.data.cosmos.rx.DocumentServiceRequestValidator; -import com.azure.data.cosmos.rx.FeedResponseListValidator; -import com.azure.data.cosmos.rx.ResourceResponseValidator; -import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.DocumentServiceRequestValidator; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.ResourceResponseValidator; +import com.azure.data.cosmos.internal.TestConfigurations; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import org.mockito.stubbing.Answer; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/EndpointMock.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/EndpointMock.java similarity index 97% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/EndpointMock.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/EndpointMock.java index 1d67ee7c21c18..0fba8367fc990 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/EndpointMock.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/EndpointMock.java @@ -21,10 +21,13 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.StoreResponseBuilder; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.google.common.collect.ImmutableList; import org.apache.commons.collections.map.HashedMap; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ExceptionBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ExceptionBuilder.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ExceptionBuilder.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ExceptionBuilder.java index 4535a4c89f3ae..e76abf34edbc4 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ExceptionBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ExceptionBuilder.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function1WithCheckedException.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function1WithCheckedException.java similarity index 95% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function1WithCheckedException.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function1WithCheckedException.java index cc1f731c279ad..f84b0cf704b74 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function1WithCheckedException.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function1WithCheckedException.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; @FunctionalInterface public interface Function1WithCheckedException{ diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function2WithCheckedException.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function2WithCheckedException.java similarity index 95% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function2WithCheckedException.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function2WithCheckedException.java index f6f0b5c926a00..b0e7b6cc0019c 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/Function2WithCheckedException.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function2WithCheckedException.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; @FunctionalInterface public interface Function2WithCheckedException{ diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java similarity index 98% rename from sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java index 2442d66357e8e..cb0f54695e096 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayAddressCacheTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java @@ -20,27 +20,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.AsyncDocumentClient.Builder; -import com.azure.data.cosmos.ConfigsBuilder; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.internal.RequestOptions; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentClientImpl; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.TestSuiteBase; +import com.azure.data.cosmos.internal.directconnectivity.*; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpClientConfig; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; -import com.azure.data.cosmos.rx.TestConfigurations; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import io.reactivex.subscribers.TestSubscriber; diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java similarity index 97% rename from sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java index 745835ff61407..d530ec3177379 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfigurationReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.AsyncDocumentClient.Builder; @@ -31,11 +31,12 @@ import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; import com.azure.data.cosmos.internal.TestSuiteBase; +import com.azure.data.cosmos.internal.directconnectivity.GatewayServiceConfigurationReader; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpHeaders; import com.azure.data.cosmos.internal.http.HttpRequest; import com.azure.data.cosmos.internal.http.HttpResponse; -import com.azure.data.cosmos.rx.TestConfigurations; +import com.azure.data.cosmos.internal.TestConfigurations; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufUtil; import io.reactivex.subscribers.TestSubscriber; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java similarity index 96% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java index 5cf0a6b75ffba..9b0c4968078c3 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GatewayServiceConfiguratorReaderMock.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java @@ -21,11 +21,12 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.DatabaseAccount; import com.azure.data.cosmos.internal.ReplicationPolicy; +import com.azure.data.cosmos.internal.directconnectivity.GatewayServiceConfigurationReader; import org.mockito.Mockito; import reactor.core.publisher.Mono; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java index 1c64e9fb1c5ab..1847d8e817f8e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java @@ -27,9 +27,6 @@ import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.directconnectivity.GatewayAddressCache; -import com.azure.data.cosmos.directconnectivity.GatewayServiceConfigurationReader; -import com.azure.data.cosmos.directconnectivity.Protocol; import com.azure.data.cosmos.internal.GlobalEndpointManager; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java index cbfa51e14a9e5..4601b7df252e1 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/GoneAndRetryWithRetryPolicyTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java @@ -22,7 +22,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.BadRequestException; @@ -35,6 +35,7 @@ import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.directconnectivity.GoneAndRetryWithRetryPolicy; import org.testng.annotations.Test; import reactor.core.publisher.Mono; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpClientMockWrapper.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientMockWrapper.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpClientMockWrapper.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientMockWrapper.java index a6ae047c493fd..2f19b24068f02 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpClientMockWrapper.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientMockWrapper.java @@ -21,8 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpHeaders; import com.azure.data.cosmos.internal.http.HttpRequest; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClientTest.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClientTest.java index 7b4616bc61d9f..517a3fca3fb41 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/HttpTransportClientTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClientTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.ConflictException; @@ -37,6 +37,8 @@ import com.azure.data.cosmos.RetryWithException; import com.azure.data.cosmos.ServiceUnavailableException; import com.azure.data.cosmos.UnauthorizedException; +import com.azure.data.cosmos.internal.directconnectivity.HttpTransportClient; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.InternalServerErrorException; @@ -48,11 +50,13 @@ import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.UserAgentContainer; +import com.azure.data.cosmos.internal.directconnectivity.HttpTransportClient; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpHeaders; import com.azure.data.cosmos.internal.http.HttpRequest; import com.azure.data.cosmos.internal.http.HttpResponse; -import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.FailureValidator; import io.netty.channel.ConnectTimeoutException; import io.reactivex.subscribers.TestSubscriber; import org.assertj.core.api.Assertions; diff --git a/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtilsTest.java similarity index 93% rename from commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtilsTest.java index a727b4036229d..9a3e804c3f799 100644 --- a/commons/src/test/java/com/azure/data/cosmos/directconnectivity/HttpUtilsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtilsTest.java @@ -20,9 +20,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.http.HttpHeaders; import com.azure.data.cosmos.internal.http.HttpResponse; import org.mockito.Mockito; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MultiStoreResultValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MultiStoreResultValidator.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MultiStoreResultValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MultiStoreResultValidator.java index 918d28b89383d..fe1652ca17eaf 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MultiStoreResultValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MultiStoreResultValidator.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.FailureValidator; import com.google.common.base.Predicates; import org.apache.commons.lang3.mutable.MutableObject; import org.assertj.core.description.Description; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MurmurHash3_32Test.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MurmurHash3_32Test.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MurmurHash3_32Test.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MurmurHash3_32Test.java index d8099967a2ef9..05cd764baa415 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/MurmurHash3_32Test.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MurmurHash3_32Test.java @@ -22,7 +22,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.internal.routing.MurmurHash3_32; import com.google.common.hash.HashFunction; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java similarity index 99% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java index 58c714560fbbc..7e3ddece36567 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyInternalTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java @@ -22,7 +22,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.CommonsBridgeInternal; import com.azure.data.cosmos.PartitionKeyDefinition; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java index db5c22acae358..8c56da5cc5757 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionKeyTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; diff --git a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionReplicasAddressesValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionReplicasAddressesValidator.java similarity index 94% rename from sdk/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionReplicasAddressesValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionReplicasAddressesValidator.java index 0a3e2f4fd37c4..9a7e053035fb7 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/directconnectivity/PartitionReplicasAddressesValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionReplicasAddressesValidator.java @@ -20,7 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; + +import com.azure.data.cosmos.internal.directconnectivity.Address; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.directconnectivity.Address; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import java.util.ArrayList; import java.util.Collection; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java index 0ddeaa8ef9d7c..639888ddb5e2c 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/QuorumReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java @@ -21,19 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.DocumentServiceRequestContext; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.RequestChargeTracker; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.rx.DocumentServiceRequestContextValidator; -import com.azure.data.cosmos.rx.DocumentServiceRequestValidator; +import com.azure.data.cosmos.internal.*; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; import io.reactivex.subscribers.TestSubscriber; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java index e6efbb9bf03f3..814cac509c1dc 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java @@ -25,10 +25,6 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClient; -import com.azure.data.cosmos.directconnectivity.HttpTransportClient; -import com.azure.data.cosmos.directconnectivity.ServerStoreModel; -import com.azure.data.cosmos.directconnectivity.StoreClient; -import com.azure.data.cosmos.directconnectivity.TransportClient; import com.azure.data.cosmos.internal.RxDocumentClientImpl; import com.azure.data.cosmos.internal.http.HttpClient; import org.apache.commons.lang3.reflect.FieldUtils; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicaAddressFactory.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicaAddressFactory.java similarity index 89% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicaAddressFactory.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicaAddressFactory.java index fcc53b36e0353..ecba77dc0d190 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicaAddressFactory.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicaAddressFactory.java @@ -21,8 +21,12 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.internal.directconnectivity.AddressInformation; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.directconnectivity.AddressInformation; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import org.apache.commons.lang3.RandomStringUtils; import java.util.ArrayList; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java similarity index 94% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java index 4290a003925a2..1db2a0d577ee1 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java @@ -21,22 +21,13 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.DocumentServiceRequestContext; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; -import com.azure.data.cosmos.internal.OperationType; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.SessionContainer; -import com.azure.data.cosmos.rx.FailureValidator; import io.reactivex.subscribers.TestSubscriber; import org.assertj.core.api.Assertions; import org.mockito.Mockito; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientTest.java similarity index 94% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientTest.java index b67ddb000c98f..19bb302ee0762 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/ReplicatedResourceClientTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientTest.java @@ -22,16 +22,18 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; +import com.azure.data.cosmos.internal.directconnectivity.*; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.directconnectivity.*; import io.reactivex.subscribers.TestSubscriber; import org.assertj.core.api.Assertions; import org.mockito.Matchers; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java similarity index 96% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java index bc2fb9c95269a..094e599e2bd36 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/RntbdTransportClientTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ConflictException; import com.azure.data.cosmos.CosmosClientException; @@ -37,33 +37,30 @@ import com.azure.data.cosmos.RetryWithException; import com.azure.data.cosmos.ServiceUnavailableException; import com.azure.data.cosmos.UnauthorizedException; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContext; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContextNegotiator; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdContextRequest; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdEndpoint; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequest; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestArgs; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestEncoder; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestManager; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestRecord; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdRequestTimer; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdResponse; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdResponseDecoder; -import com.azure.data.cosmos.directconnectivity.rntbd.RntbdUUID; +import com.azure.data.cosmos.internal.directconnectivity.RntbdTransportClient; +import com.azure.data.cosmos.internal.directconnectivity.ServerProperties; +import com.azure.data.cosmos.internal.directconnectivity.RntbdTransportClient; +import com.azure.data.cosmos.internal.directconnectivity.ServerProperties; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdContext; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdContextNegotiator; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdContextRequest; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdEndpoint; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdRequest; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdRequestArgs; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdRequestEncoder; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdRequestManager; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdRequestRecord; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdRequestTimer; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdResponse; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdResponseDecoder; +import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdUUID; import com.azure.data.cosmos.BadRequestException; -import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.InvalidPartitionException; import com.azure.data.cosmos.NotFoundException; -import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.PartitionIsMigratingException; import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; -import com.azure.data.cosmos.internal.Paths; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.UserAgentContainer; -import com.azure.data.cosmos.internal.Utils; -import com.azure.data.cosmos.rx.FailureValidator; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import io.netty.buffer.ByteBuf; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java index 16ac64e9d50e4..78d5352117376 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderDotNetTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java @@ -21,29 +21,16 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.ServiceUnavailableException; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.ReplicationPolicy; -import com.azure.data.cosmos.internal.AuthorizationTokenType; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.DocumentServiceRequestContext; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; +import com.azure.data.cosmos.internal.directconnectivity.StoreReader; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.InvalidPartitionException; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.RequestChargeTracker; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.RxDocumentServiceResponse; -import com.azure.data.cosmos.internal.SessionContainer; -import com.azure.data.cosmos.internal.Strings; -import com.azure.data.cosmos.rx.FailureValidator; import io.reactivex.subscribers.TestSubscriber; import org.apache.commons.lang3.StringUtils; import org.mockito.Matchers; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java index cbedf41768d15..eb8270a92a447 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; @@ -29,20 +29,11 @@ import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.PartitionKeyRangeGoneException; import com.azure.data.cosmos.RequestRateTooLargeException; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.DocumentServiceRequestContext; -import com.azure.data.cosmos.internal.HttpConstants; -import com.azure.data.cosmos.internal.ISessionToken; +import com.azure.data.cosmos.internal.directconnectivity.StoreReader; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.NotFoundException; -import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.PartitionIsMigratingException; import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; -import com.azure.data.cosmos.internal.RequestChargeTracker; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.Utils; -import com.azure.data.cosmos.internal.VectorSessionToken; -import com.azure.data.cosmos.rx.FailureValidator; import com.google.common.collect.ImmutableList; import io.reactivex.subscribers.TestSubscriber; import org.assertj.core.api.AssertionsForClassTypes; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java similarity index 91% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java index 659058e1d20fd..9a643567cd604 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreReaderUnderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java @@ -21,10 +21,14 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.directconnectivity.AddressSelector; +import com.azure.data.cosmos.internal.directconnectivity.ReadMode; +import com.azure.data.cosmos.internal.directconnectivity.StoreReader; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; +import com.azure.data.cosmos.internal.directconnectivity.*; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.tuple.Pair; import reactor.core.publisher.Mono; diff --git a/commons/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseTest.java similarity index 95% rename from commons/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseTest.java index e6208e4ecb067..0659edbb8f1bf 100644 --- a/commons/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseTest.java @@ -21,8 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; import org.apache.commons.io.IOUtils; import org.testng.annotations.Test; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseValidator.java similarity index 99% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseValidator.java index 0d930285adcef..d30e68de2fa64 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResponseValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseValidator.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.HttpConstants; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResultValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResultValidator.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResultValidator.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResultValidator.java index 05303ffad5fdc..1a8afa6d324a7 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/StoreResultValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResultValidator.java @@ -21,10 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.rx.FailureValidator; +import com.azure.data.cosmos.internal.FailureValidator; import java.net.URI; import java.util.ArrayList; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TimeoutHelperTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelperTest.java similarity index 94% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TimeoutHelperTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelperTest.java index 0435980577842..ed66930532334 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TimeoutHelperTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelperTest.java @@ -21,8 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.internal.directconnectivity.TimeoutHelper; import org.testng.annotations.Test; import java.time.Duration; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TransportClientWrapper.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TransportClientWrapper.java similarity index 98% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TransportClientWrapper.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TransportClientWrapper.java index 6d0f54a273305..2319209fbc23f 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/TransportClientWrapper.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TransportClientWrapper.java @@ -21,12 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.*; import org.apache.commons.lang3.tuple.Pair; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtilityTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtilityTest.java similarity index 97% rename from direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtilityTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtilityTest.java index 039dfaddc1218..11fffa33b1b5f 100644 --- a/direct-impl/src/test/java/com/azure/data/cosmos/directconnectivity/WebExceptionUtilityTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtilityTest.java @@ -21,8 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos.directconnectivity; +package com.azure.data.cosmos.internal.directconnectivity; +import com.azure.data.cosmos.internal.directconnectivity.WebExceptionUtility; import io.netty.channel.ChannelException; import io.netty.channel.ConnectTimeoutException; import io.netty.handler.timeout.ReadTimeoutException; diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java similarity index 100% rename from gateway/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java similarity index 98% rename from gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java index 2d952d8f41adc..0ce61cf39f4d7 100644 --- a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java @@ -29,12 +29,7 @@ import com.azure.data.cosmos.DatabaseAccount; import com.azure.data.cosmos.DatabaseAccountLocation; import com.azure.data.cosmos.DatabaseAccountManagerInternal; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.GlobalEndpointManager; -import com.azure.data.cosmos.internal.OperationType; -import com.azure.data.cosmos.internal.ResourceType; -import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.*; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import org.apache.commons.collections4.list.UnmodifiableList; diff --git a/direct-impl/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java b/sdk/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java similarity index 100% rename from direct-impl/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java diff --git a/gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java similarity index 100% rename from gateway/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java diff --git a/commons/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java similarity index 100% rename from commons/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java index 934bb0abef8fc..ebfcfceede647 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java @@ -30,6 +30,7 @@ import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FeedResponseListValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java index ef9bbeb9874ed..1c69d9c4d6a3b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java @@ -40,6 +40,7 @@ import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.RxDocumentClientUnderTest; +import com.azure.data.cosmos.internal.TestUtils; import io.reactivex.subscribers.TestSubscriber; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -75,7 +76,7 @@ public class BackPressureCrossPartitionTest extends TestSuiteBase { private int numberOfPartitions; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); + return TestUtils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } static protected CosmosContainerProperties getCollectionDefinition() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java index 595488345b39f..103eb852b99b3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java @@ -36,6 +36,7 @@ import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.RxDocumentClientUnderTest; +import com.azure.data.cosmos.internal.TestUtils; import io.reactivex.subscribers.TestSubscriber; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -64,7 +65,7 @@ public class BackPressureTest extends TestSuiteBase { private CosmosClient client; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); + return TestUtils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } private static CosmosContainerProperties getSinglePartitionCollectionDefinition() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java index edec9a5e57483..1d7fe9736be5c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java @@ -31,9 +31,8 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.internal.RequestOptions; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.internal.TestSuiteBase; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; @@ -68,7 +67,7 @@ public class ChangeFeedTest extends TestSuiteBase { private AsyncDocumentClient client; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); + return TestUtils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } static protected DocumentCollection getCollectionDefinition() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java index ed4d79dba1c25..9fba4bc3c1a71 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java @@ -43,7 +43,8 @@ import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.RetryAnalyzer; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.RetryAnalyzer; import com.azure.data.cosmos.SpatialSpec; import com.azure.data.cosmos.SpatialType; import org.testng.annotations.AfterClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java index dab43ae26428a..3e4a71a71c85e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java @@ -31,6 +31,8 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java index df82cc766a22f..a651197fbf2b3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java @@ -30,6 +30,7 @@ import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.CosmosDatabaseResponse; import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.internal.FailureValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java index 8736cc614fa42..7e5d94953edf4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java @@ -29,6 +29,8 @@ import com.azure.data.cosmos.CosmosDatabaseProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java index 8277ce0fe73dd..6ae3c8c730f65 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java @@ -33,6 +33,7 @@ import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.PartitionKey; +import com.azure.data.cosmos.internal.FailureValidator; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java index b751066eb5d14..cf3879466ee7c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java @@ -35,6 +35,8 @@ import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.CosmosDatabaseForTest; import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.TestUtils; import com.azure.data.cosmos.internal.Utils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java index 612949bca5826..7aecad17ddea4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java @@ -35,6 +35,8 @@ import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.FeedResponseListValidator; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.collections4.ComparatorUtils; import org.testng.annotations.AfterClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java index a9815bb274d19..13ad6ed077108 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java @@ -25,11 +25,10 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.AsyncDocumentClient.Builder; import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.TestSuiteBase; import org.assertj.core.util.Strings; @@ -57,7 +56,7 @@ public class OfferQueryTest extends TestSuiteBase { private AsyncDocumentClient client; private String getDatabaseLink() { - return Utils.getDatabaseNameLink(databaseId); + return TestUtils.getDatabaseNameLink(databaseId); } @Factory(dataProvider = "clientBuilders") diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java index 4eb3568514dd8..7cc185e867544 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java @@ -24,10 +24,8 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.internal.Offer; -import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java index 7b72e8ff0ed32..b671e35bcf8e9 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java @@ -34,7 +34,7 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.RetryAnalyzer; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.CompositeContinuationToken; import com.azure.data.cosmos.internal.query.OrderByContinuationToken; @@ -563,7 +563,7 @@ private static CosmosItemProperties getDocumentDefinition(Map ke private static String toJson(Object object){ try { - return com.azure.data.cosmos.internal.Utils.getSimpleObjectMapper().writeValueAsString(object); + return Utils.getSimpleObjectMapper().writeValueAsString(object); } catch (JsonProcessingException e) { throw new IllegalStateException(e); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java index f9f735d8b73c5..7cb82188c3b99 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java @@ -32,7 +32,7 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.QueryMetrics; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.CompositeContinuationToken; @@ -63,7 +63,7 @@ public class ParallelDocumentQueryTest extends TestSuiteBase { private CosmosClient client; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); + return TestUtils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } @Factory(dataProvider = "clientBuildersWithDirect") diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java index b6416e5371c37..91828d54395d4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.rx; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java index 858a59a8312f6..141de2536d86d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java @@ -33,6 +33,7 @@ import com.azure.data.cosmos.CosmosUser; import com.azure.data.cosmos.CosmosUserProperties; import com.azure.data.cosmos.PermissionMode; +import com.azure.data.cosmos.internal.FailureValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java index d235d0e832e98..c734b0c7bb639 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java @@ -25,13 +25,11 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; -import com.azure.data.cosmos.internal.User; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java index 2c4b90a64aacf..e7a7315141be9 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java @@ -31,6 +31,7 @@ import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.internal.TestConfigurations; import com.azure.data.cosmos.rx.proxy.HttpProxyServer; import org.apache.log4j.Level; import org.apache.log4j.LogManager; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java index 2d3de3cf4ab9f..fa12d9f70a001 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java @@ -32,6 +32,8 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java index 8a2472a4a366f..d450701123a01 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java @@ -28,6 +28,8 @@ import com.azure.data.cosmos.CosmosDatabaseRequestOptions; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java index c06cff2f77054..ffbf27c83ed3a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java @@ -30,6 +30,9 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java index 48c31595f5181..dc3bfeb1a23a6 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java @@ -24,11 +24,10 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java index addf634935ef9..daff264fc38e0 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java @@ -24,13 +24,11 @@ import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.internal.User; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java index 5d7a824e8efd1..80096c246f619 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java @@ -30,6 +30,7 @@ import com.azure.data.cosmos.CosmosDatabase; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FeedResponseListValidator; import com.azure.data.cosmos.internal.PartitionKeyRange; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java index dde5f00e8de37..416b310838ca8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java @@ -29,6 +29,8 @@ import com.azure.data.cosmos.CosmosStoredProcedureProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java index 3c9a9b4865d11..da71bc3506dcf 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java @@ -31,6 +31,8 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java index 1d4ec7b797092..c53783e06ca10 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java @@ -30,6 +30,8 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java index e0cc377c8caba..50ab2ff1c57ff 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java @@ -29,6 +29,8 @@ import com.azure.data.cosmos.CosmosUserProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import com.azure.data.cosmos.internal.RequestOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java index 4c5937ccbf289..aa7472cd620f0 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java @@ -26,16 +26,12 @@ import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DatabaseForTest; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.internal.Permission; import com.azure.data.cosmos.PermissionMode; -import com.azure.data.cosmos.internal.RequestOptions; -import com.azure.data.cosmos.internal.ResourceResponse; -import com.azure.data.cosmos.internal.User; import com.azure.data.cosmos.internal.TestSuiteBase; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; @@ -170,7 +166,7 @@ public Object[][] collectionAndPermissionData() { return new Object[][]{ //This test will try to read collection from its own permission and validate it, both with request Id and name. {createdCollection.selfLink(), createdCollPermission}, - {Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()), createdDocPermissionWithName}, + {TestUtils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()), createdDocPermissionWithName}, }; } @@ -179,29 +175,29 @@ public Object[][] documentAndPermissionData() { return new Object[][]{ //These tests will try to read document from its own permission and validate it, both with request Id and name. {createdDocument.selfLink(), createdDocPermission, createdDocument.id(), null}, - {Utils.getDocumentNameLink(createdDatabase.id(), createdCollection.id(), createdDocument.id()), createdDocPermissionWithName, createdDocument.id(), null}, + {TestUtils.getDocumentNameLink(createdDatabase.id(), createdCollection.id(), createdDocument.id()), createdDocPermissionWithName, createdDocument.id(), null}, //These tests will try to read document from its permission having partition key 1 and validate it, both with request Id and name. {createdDocumentWithPartitionKey.selfLink(), createdDocPermissionWithPartitionKey, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, - {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), createdDocPermissionWithPartitionKeyWithName + {TestUtils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), createdDocPermissionWithPartitionKeyWithName , createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, //These tests will try to read document from its permission having partition key 2 and validate it, both with request Id and name. {createdDocumentWithPartitionKey2.selfLink(), createdDocPermissionWithPartitionKey2, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2}, - {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), + {TestUtils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), createdDocPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2}, // These tests will try to read document from its parent collection permission and validate it, both with request Id and name. {createdDocument.selfLink(), createdCollPermission, createdDocument.id(), null}, - {Utils.getDocumentNameLink(createdDatabase.id(), createdCollection.id(), createdDocument.id()), createdCollPermissionWithName, createdDocument.id(), null}, + {TestUtils.getDocumentNameLink(createdDatabase.id(), createdCollection.id(), createdDocument.id()), createdCollPermissionWithName, createdDocument.id(), null}, //This test will try to read document from collection permission having partition key 1 and validate it, both with request Id and name. {createdDocumentWithPartitionKey.selfLink(), createdColPermissionWithPartitionKey, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, - {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), createdColPermissionWithPartitionKeyWithName, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, + {TestUtils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), createdColPermissionWithPartitionKeyWithName, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, //This test will try to read document from collection permission having partition key 2 and validate it, both with request Id and name. {createdDocumentWithPartitionKey2.selfLink(), createdColPermissionWithPartitionKey2, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2}, - {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), createdColPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2} + {TestUtils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), createdColPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2} }; } @@ -212,7 +208,7 @@ public Object[][] documentAndPermissionDataForResourceNotFound() { //This test will try to read document from its resource token directly and validate it. {createdDocumentWithPartitionKey2.selfLink(), createdColPermissionWithPartitionKey, PARTITION_KEY_VALUE}, //This test will try to read document from its parent collection resource token directly and validate it. - {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), + {TestUtils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), createdColPermissionWithPartitionKeyWithName, PARTITION_KEY_VALUE} }; } @@ -223,13 +219,13 @@ public Object[][] documentAndMultipleCollPermissionData() { //These tests will try to read document from partition 1 with two collection permissions having different partition keys and validate it, both with request Id and name. {createdDocumentWithPartitionKey.selfLink(), createdColPermissionWithPartitionKey, createdColPermissionWithPartitionKey2, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, - {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), createdColPermissionWithPartitionKeyWithName + {TestUtils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), createdColPermissionWithPartitionKeyWithName , createdColPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey.id(), PARTITION_KEY_VALUE}, //These tests will try to read document from partition 1 with two collection permissions having different partition keys and validate it, both with request Id and name. {createdDocumentWithPartitionKey2.selfLink(), createdColPermissionWithPartitionKey, createdColPermissionWithPartitionKey2, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2}, - {Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), createdColPermissionWithPartitionKeyWithName + {TestUtils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey2.id()), createdColPermissionWithPartitionKeyWithName , createdColPermissionWithPartitionKey2WithName, createdDocumentWithPartitionKey2.id(), PARTITION_KEY_VALUE_2} }; } @@ -435,7 +431,7 @@ private Permission getCollPermissionWithName() { Permission permission = new Permission(); permission.id(PERMISSION_FOR_COLL_WITH_NAME); permission.setPermissionMode(PermissionMode.READ); - permission.setResourceLink(Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id())); + permission.setResourceLink(TestUtils.getCollectionNameLink(createdDatabase.id(), createdCollection.id())); return permission; } @@ -450,7 +446,7 @@ private Permission getDocPermissionWithName() { Permission permission = new Permission(); permission.id(PERMISSION_FOR_DOC_WITH_NAME); permission.setPermissionMode(PermissionMode.READ); - permission.setResourceLink(Utils.getDocumentNameLink(createdDatabase.id(),createdCollection.id(),createdDocument.id())); + permission.setResourceLink(TestUtils.getDocumentNameLink(createdDatabase.id(),createdCollection.id(),createdDocument.id())); return permission; } @@ -462,7 +458,7 @@ private Permission getDocPermissionWithPartitionKey() { } private Permission getDocPermissionWithPartitionKeyWithName() { - String permissionStr = String.format(PERMISSION_DEFINITION, Utils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), + String permissionStr = String.format(PERMISSION_DEFINITION, TestUtils.getDocumentNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id(), createdDocumentWithPartitionKey.id()), PARTITION_KEY_VALUE); Permission permission = new Permission(permissionStr); permission.id("PermissionForDocWithPartitionKeyWithName"); @@ -478,7 +474,7 @@ private Permission getDocPermissionWithPartitionKey2() { } private Permission getDocPermissionWithPartitionKey2WithName() { - String permissionStr = String.format(PERMISSION_DEFINITION, Utils.getDocumentNameLink(createdDatabase.id(),createdCollectionWithPartitionKey.id(),createdDocumentWithPartitionKey2.id()), + String permissionStr = String.format(PERMISSION_DEFINITION, TestUtils.getDocumentNameLink(createdDatabase.id(),createdCollectionWithPartitionKey.id(),createdDocumentWithPartitionKey2.id()), PARTITION_KEY_VALUE_2); Permission permission = new Permission(permissionStr); permission.id("PermissionForDocWithPartitionKey2WithName"); @@ -493,7 +489,7 @@ private Permission getColPermissionWithPartitionKey() { } private Permission getColPermissionWithPartitionKeyWithName() { - String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, Utils.getCollectionNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id()), + String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, TestUtils.getCollectionNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id()), PARTITION_KEY_VALUE); Permission permission = new Permission(permissionStr); permission.id("PermissionForColWithPartitionKeyWithName"); @@ -509,7 +505,7 @@ private Permission getColPermissionWithPartitionKey2() { } private Permission getColPermissionWithPartitionKey2WithName() { - String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, Utils.getCollectionNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id()), + String permissionStr = String.format(COLLECTION_PERMISSION_DEFINITION, TestUtils.getCollectionNameLink(createdDatabase.id(), createdCollectionWithPartitionKey.id()), PARTITION_KEY_VALUE_2); Permission permission = new Permission(permissionStr); permission.id("PermissionForColWithPartitionKey2WithName"); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java index 9562960df550f..01f3614e156a3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java @@ -34,6 +34,10 @@ import com.azure.data.cosmos.SqlParameter; import com.azure.data.cosmos.SqlParameterList; import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; +import com.azure.data.cosmos.internal.TestUtils; import io.reactivex.subscribers.TestSubscriber; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -57,7 +61,7 @@ public class SinglePartitionDocumentQueryTest extends TestSuiteBase { private CosmosClient client; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); + return TestUtils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } @Factory(dataProvider = "clientBuildersWithDirect") diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java index 6467119c56a46..afe1a849b8e30 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java @@ -28,6 +28,8 @@ import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java index 377d08c486c0d..6f2662e89ff7e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java @@ -31,6 +31,7 @@ import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; import com.azure.data.cosmos.CosmosStoredProcedureResponse; import com.azure.data.cosmos.CosmosStoredProcedureProperties; +import com.azure.data.cosmos.internal.FailureValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java index 34c2fdde55c31..7ac227a1b8a61 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java @@ -29,6 +29,9 @@ import com.azure.data.cosmos.CosmosStoredProcedureProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index 61611e66a056d..ddeddd6008e2c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -59,10 +59,8 @@ import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.directconnectivity.Protocol; -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.PathParser; -import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.internal.directconnectivity.Protocol; +import com.azure.data.cosmos.internal.*; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java index 07380bdb41fda..3a50d0b52e9d8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java @@ -36,16 +36,10 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.internal.Permission; +import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.PermissionMode; -import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.internal.ResourceResponse; -import com.azure.data.cosmos.internal.StoredProcedure; -import com.azure.data.cosmos.internal.StoredProcedureResponse; import com.azure.data.cosmos.TokenResolver; -import com.azure.data.cosmos.internal.User; -import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.SkipException; import org.testng.annotations.AfterClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java index 81acc28ad5b60..88910aeb5e35c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java @@ -30,7 +30,8 @@ import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.RetryAnalyzer; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.RetryAnalyzer; import com.azure.data.cosmos.internal.Utils.ValueHolder; import com.azure.data.cosmos.internal.query.TakeContinuationToken; import io.reactivex.subscribers.TestSubscriber; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java index 50856df0e9cf2..957853b757d74 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java @@ -33,6 +33,9 @@ import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java index 31b2de8c32c7a..1fcd0f8497509 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java @@ -44,6 +44,8 @@ import com.azure.data.cosmos.UniqueKey; import com.azure.data.cosmos.UniqueKeyPolicy; import com.azure.data.cosmos.internal.HttpConstants; +import com.azure.data.cosmos.internal.TestConfigurations; +import com.azure.data.cosmos.internal.TestUtils; import com.azure.data.cosmos.internal.Utils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java index 112b21a97cf95..a408063fd2f2f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java @@ -31,6 +31,7 @@ import com.azure.data.cosmos.CosmosUser; import com.azure.data.cosmos.CosmosUserResponse; import com.azure.data.cosmos.CosmosUserProperties; +import com.azure.data.cosmos.internal.FailureValidator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java index 85548455060e0..4f1fc6f20e8eb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java @@ -31,6 +31,10 @@ import com.azure.data.cosmos.Database; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; +import com.azure.data.cosmos.internal.TestUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -53,7 +57,7 @@ public class UserDefinedFunctionQueryTest extends TestSuiteBase { private CosmosClient client; public String getCollectionLink() { - return Utils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); + return TestUtils.getCollectionNameLink(createdDatabase.id(), createdCollection.id()); } @Factory(dataProvider = "clientBuildersWithDirect") diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java index 7a12767fb2e1b..875475db35abb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java @@ -29,6 +29,9 @@ import com.azure.data.cosmos.CosmosUserProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.FeedResponseValidator; +import com.azure.data.cosmos.internal.TestUtils; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -92,7 +95,7 @@ public void queryAllUsers() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - String databaseLink = Utils.getDatabaseNameLink(databaseId); + String databaseLink = TestUtils.getDatabaseNameLink(databaseId); Flux> queryObservable = createdDatabase.queryUsers(query, options); List expectedUsers = createdUsers; diff --git a/commons/src/test/resources/sampleConflict.json b/sdk/src/test/resources/sampleConflict.json similarity index 100% rename from commons/src/test/resources/sampleConflict.json rename to sdk/src/test/resources/sampleConflict.json From 9c73dd91db8be81275699d8c1f15e447e1f34fb4 Mon Sep 17 00:00:00 2001 From: Milis Date: Thu, 27 Jun 2019 21:13:55 -0700 Subject: [PATCH 55/85] Refactoring and removing "partition" settings from the CFP options. (#215) --- .../ChangeFeed/SampleChangeFeedProcessor.java | 4 +- .../data/cosmos/ChangeFeedProcessor.java | 27 +++-- .../cosmos/ChangeFeedProcessorOptions.java | 112 +++--------------- .../ChangeFeedProcessorBuilderImpl.java | 23 ++-- .../EqualPartitionsBalancingStrategy.java | 4 +- .../cosmos/rx/ChangeFeedProcessorTest.java | 19 ++- 6 files changed, 62 insertions(+), 127 deletions(-) diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java index b3ee13b0501dc..545c271932924 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java @@ -105,8 +105,8 @@ public static void main (String[]args) { public static ChangeFeedProcessor getChangeFeedProcessor(String hostName, CosmosContainer feedContainer, CosmosContainer leaseContainer) { return ChangeFeedProcessor.Builder() .hostName(hostName) - .feedContainerClient(feedContainer) - .leaseContainerClient(leaseContainer) + .feedContainer(feedContainer) + .leaseContainer(leaseContainer) .handleChanges(docs -> { System.out.println("--->handleChanges() START"); diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java index 61d90296d2767..22f4f6072d5bb 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java @@ -47,8 +47,8 @@ * {@code * ChangeFeedProcessor changeFeedProcessor = ChangeFeedProcessor.Builder() * .hostName(hostName) - * .feedContainerClient(feedContainer) - * .leaseContainerClient(leaseContainer) + * .feedContainer(feedContainer) + * .leaseContainer(leaseContainer) * .handleChanges(docs -> { * // Implementation for handling and processing CosmosItemProperties list goes here * }) @@ -79,8 +79,8 @@ public interface ChangeFeedProcessor { * * ChangeFeedProcessor.Builder() * .hostName("SampleHost") - * .feedContainerClient(feedContainer) - * .leaseContainerClient(leaseContainer) + * .feedContainer(feedContainer) + * .leaseContainer(leaseContainer) * .handleChanges(docs -> { * // Implementation for handling and processing CosmosItemProperties list goes here * }) @@ -93,6 +93,9 @@ static BuilderDefinition Builder() { return new ChangeFeedProcessorBuilderImpl(); } + /** + * The {@link ChangeFeedProcessor} builder definitions for setting the properties. + */ interface BuilderDefinition { /** * Sets the host name. @@ -105,13 +108,21 @@ interface BuilderDefinition { /** * Sets and existing {@link CosmosContainer} to be used to read from the monitored collection. * - * @param feedContainerClient the instance of {@link CosmosContainer} to be used. + * @param feedContainer the instance of {@link CosmosContainer} to be used. * @return current Builder. */ - BuilderDefinition feedContainerClient(CosmosContainer feedContainerClient); + BuilderDefinition feedContainer(CosmosContainer feedContainer); /** * Sets the {@link ChangeFeedProcessorOptions} to be used. + *

+ * Unless specifically set the default values that will be used are: + * - maximum items per page or FeedResponse: 100 + * - lease renew interval: 17 seconds + * - lease acquire interval: 13 seconds + * - lease expiration interval: 60 seconds + * - feed poll delay: 5 seconds + * - maximum scale count: unlimited * * @param changeFeedProcessorOptions the change feed processor options to use. * @return current Builder. @@ -129,10 +140,10 @@ interface BuilderDefinition { /** * Sets an existing {@link CosmosContainer} to be used to read from the leases collection. * - * @param leaseCosmosClient the instance of {@link CosmosContainer} to use. + * @param leaseContainer the instance of {@link CosmosContainer} to use. * @return current Builder. */ - BuilderDefinition leaseContainerClient(CosmosContainer leaseCosmosClient); + BuilderDefinition leaseContainer(CosmosContainer leaseContainer); /** * Builds a new instance of the {@link ChangeFeedProcessor} with the specified configuration asynchronously. diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java index aba333b661700..a712913581b3a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java @@ -25,8 +25,10 @@ import java.time.Duration; import java.time.OffsetDateTime; +/** + * Specifies the options associated with {@link ChangeFeedProcessor}. + */ public class ChangeFeedProcessorOptions { - private static final int DefaultQueryPartitionsMaxBatchSize = 100; private static Duration DefaultRenewInterval = Duration.ofMillis(0).plusSeconds(17); private static Duration DefaultAcquireInterval = Duration.ofMillis(0).plusSeconds(13); private static Duration DefaultExpirationInterval = Duration.ofMillis(0).plusSeconds(60); @@ -42,12 +44,9 @@ public class ChangeFeedProcessorOptions { private String startContinuation; private OffsetDateTime startTime; private boolean startFromBeginning; - private String sessionToken; - private int minPartitionCount; - private int maxPartitionCount; + private int minScaleCount; + private int maxScaleCount; private boolean discardExistingLeases; - private int queryPartitionsMaxBatchSize; - private int degreeOfParallelism; public ChangeFeedProcessorOptions() { this.maxItemCount = 100; @@ -56,9 +55,7 @@ public ChangeFeedProcessorOptions() { this.leaseAcquireInterval = DefaultAcquireInterval; this.leaseExpirationInterval = DefaultExpirationInterval; this.feedPollDelay = DefaultFeedPollDelay; - this.queryPartitionsMaxBatchSize = DefaultQueryPartitionsMaxBatchSize; - this.maxPartitionCount = 0; // unlimited - this.degreeOfParallelism = 25; // default + this.maxScaleCount = 0; // unlimited } /** @@ -278,51 +275,16 @@ public ChangeFeedProcessorOptions startFromBeginning(boolean startFromBeginning) return this; } - /** - * Sets a value indicating whether change feed in the Azure Cosmos DB service should start from beginning. - *

- * This is only used when: - * (1) Lease store is not initialized and is ignored if a lease for partition exists and has continuation token. - * (2) StartContinuation is not specified. - * (3) StartTime is not specified. - * - * @return the current ChangeFeedProcessorOptions instance. - */ - public ChangeFeedProcessorOptions withoutStartFromBeginning() { - this.startFromBeginning = false; - return this; - } - - /** - * Gets the session token for use with session consistency in the Azure Cosmos DB service. - * - * @return the session token for use with session consistency in the Azure Cosmos DB service. - */ - public String sessionToken() { - return this.sessionToken; - } - - /** - * Sets the session token for use with session consistency in the Azure Cosmos DB service. - * - * @param sessionToken the session token for use with session consistency in the Azure Cosmos DB service. - * @return the current ChangeFeedProcessorOptions instance. - */ - public ChangeFeedProcessorOptions sessionToken(String sessionToken) { - this.sessionToken = sessionToken; - return this; - } - /** * Gets the minimum partition count for the host. *

* This can be used to increase the number of partitions for the host and thus override equal distribution (which * is the default) of leases between hosts. * - * @return the minimum partition count for the host. + * @return the minimum scale count for the host. */ - public int minPartitionCount() { - return this.minPartitionCount; + public int minScaleCount() { + return this.minScaleCount; } /** @@ -331,11 +293,11 @@ public int minPartitionCount() { * This can be used to increase the number of partitions for the host and thus override equal distribution (which * is the default) of leases between hosts. * - * @param minPartitionCount the minimum partition count for the host. + * @param minScaleCount the minimum partition count for the host. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions minPartitionCount(int minPartitionCount) { - this.minPartitionCount = minPartitionCount; + public ChangeFeedProcessorOptions minScaleCount(int minScaleCount) { + this.minScaleCount = minScaleCount; return this; } @@ -347,18 +309,18 @@ public ChangeFeedProcessorOptions minPartitionCount(int minPartitionCount) { * * @return the maximum number of partitions the host can serve. */ - public int maxPartitionCount() { - return this.maxPartitionCount; + public int maxScaleCount() { + return this.maxScaleCount; } /** * Sets the maximum number of partitions the host can serve. * - * @param maxPartitionCount the maximum number of partitions the host can serve. + * @param maxScaleCount the maximum number of partitions the host can serve. * @return the current ChangeFeedProcessorOptions instance. */ - public ChangeFeedProcessorOptions maxPartitionCount(int maxPartitionCount) { - this.maxPartitionCount = maxPartitionCount; + public ChangeFeedProcessorOptions maxScaleCount(int maxScaleCount) { + this.maxScaleCount = maxScaleCount; return this; } @@ -383,44 +345,4 @@ public ChangeFeedProcessorOptions discardExistingLeases(boolean discardExistingL this.discardExistingLeases = discardExistingLeases; return this; } - - /** - * Gets the Batch size of query partitions API. - * - * @return the Batch size of query partitions API. - */ - public int queryPartitionsMaxBatchSize() { - return this.queryPartitionsMaxBatchSize; - } - - /** - * Sets the Batch size of query partitions API. - * - * @param queryPartitionsMaxBatchSize the Batch size of query partitions API. - * @return the current ChangeFeedProcessorOptions instance. - */ - public ChangeFeedProcessorOptions queryPartitionsMaxBatchSize(int queryPartitionsMaxBatchSize) { - this.queryPartitionsMaxBatchSize = queryPartitionsMaxBatchSize; - return this; - } - - /** - * Gets maximum number of tasks to use for auxiliary calls. - * - * @return maximum number of tasks to use for auxiliary calls. - */ - public int degreeOfParallelism() { - return this.degreeOfParallelism; - } - - /** - * Sets maximum number of tasks to use for auxiliary calls. - * - * @param defaultQueryPartitionsMaxBatchSize maximum number of tasks to use for auxiliary calls. - * @return the current ChangeFeedProcessorOptions instance. - */ - public ChangeFeedProcessorOptions degreeOfParallelism(int defaultQueryPartitionsMaxBatchSize) { - this.queryPartitionsMaxBatchSize = queryPartitionsMaxBatchSize; - return this; - } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java index 43e8be64aee3a..3d979e59c64bc 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java @@ -59,8 +59,8 @@ * {@code * ChangeFeedProcessor.Builder() * .hostName(hostName) - * .feedContainerClient(feedContainer) - * .leaseContainerClient(leaseContainer) + * .feedContainer(feedContainer) + * .leaseContainer(leaseContainer) * .handleChanges(docs -> { * // Implementation for handling and processing CosmosItemProperties list goes here * }) @@ -73,6 +73,11 @@ public class ChangeFeedProcessorBuilderImpl implements ChangeFeedProcessor.Build private static final long DefaultUnhealthinessDuration = Duration.ofMinutes(15).toMillis(); private final Duration sleepTime = Duration.ofSeconds(15); private final Duration lockTime = Duration.ofSeconds(30); + private static final int DefaultQueryPartitionsMaxBatchSize = 100; + + private int queryPartitionsMaxBatchSize = DefaultQueryPartitionsMaxBatchSize; + private int degreeOfParallelism = 25; // default + private String hostName; private ChangeFeedContextClient feedContextClient; @@ -128,7 +133,7 @@ public ChangeFeedProcessorBuilderImpl hostName(String hostName) { * @return current Builder. */ @Override - public ChangeFeedProcessorBuilderImpl feedContainerClient(CosmosContainer feedDocumentClient) { + public ChangeFeedProcessorBuilderImpl feedContainer(CosmosContainer feedDocumentClient) { if (feedDocumentClient == null) { throw new IllegalArgumentException("feedContextClient"); } @@ -217,7 +222,7 @@ public ChangeFeedProcessorBuilderImpl withCollectionResourceId(String collection * @return current Builder. */ @Override - public ChangeFeedProcessorBuilderImpl leaseContainerClient(CosmosContainer leaseDocumentClient) { + public ChangeFeedProcessorBuilderImpl leaseContainer(CosmosContainer leaseDocumentClient) { if (leaseDocumentClient == null) { throw new IllegalArgumentException("leaseContextClient"); } @@ -319,6 +324,8 @@ public ChangeFeedProcessor build() { } public ChangeFeedProcessorBuilderImpl() { + this.queryPartitionsMaxBatchSize = DefaultQueryPartitionsMaxBatchSize; + this.degreeOfParallelism = 25; // default } public ChangeFeedProcessorBuilderImpl(PartitionManager partitionManager) { @@ -411,8 +418,8 @@ private Mono buildPartitionManager(LeaseStoreManager leaseStor this.feedContextClient.getContainerClient(), leaseStoreManager, leaseStoreManager, - this.changeFeedProcessorOptions.degreeOfParallelism(), - this.changeFeedProcessorOptions.queryPartitionsMaxBatchSize() + this.degreeOfParallelism, + this.queryPartitionsMaxBatchSize ); Bootstrapper bootstrapper = new BootstrapperImpl(synchronizer, leaseStoreManager, this.lockTime, this.sleepTime); @@ -431,8 +438,8 @@ private Mono buildPartitionManager(LeaseStoreManager leaseStor if (this.loadBalancingStrategy == null) { this.loadBalancingStrategy = new EqualPartitionsBalancingStrategy( this.hostName, - this.changeFeedProcessorOptions.minPartitionCount(), - this.changeFeedProcessorOptions.maxPartitionCount(), + this.changeFeedProcessorOptions.minScaleCount(), + this.changeFeedProcessorOptions.maxScaleCount(), this.changeFeedProcessorOptions.leaseExpirationInterval()); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java index bb3942f7a8329..730e161ac1c18 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java @@ -78,8 +78,8 @@ public List selectLeasesToTake(List allLeases) { workerCount, expiredLeases.Count, target, - this.minPartitionCount, - this.maxPartitionCount, + this.minScaleCount, + this.maxScaleCount, myCount, Math.Max(partitionsNeededForMe, 0)); */ diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java index 1971443a7eec5..e4b1e477552dd 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java @@ -89,8 +89,8 @@ public void readFeedDocumentsStartFromBeginning() { } ChangeFeedProcessorTest.log.info("END processing from thread {}", Thread.currentThread().getId()); }) - .feedContainerClient(createdFeedCollection) - .leaseContainerClient(createdLeaseCollection) + .feedContainer(createdFeedCollection) + .leaseContainer(createdLeaseCollection) .options(new ChangeFeedProcessorOptions() .leaseRenewInterval(Duration.ofSeconds(20)) .leaseAcquireInterval(Duration.ofSeconds(10)) @@ -99,11 +99,8 @@ public void readFeedDocumentsStartFromBeginning() { .leasePrefix("TEST") .maxItemCount(10) .startFromBeginning(true) - .minPartitionCount(1) - .maxPartitionCount(3) + .maxScaleCount(0) // unlimited .discardExistingLeases(true) - .queryPartitionsMaxBatchSize(2) - .degreeOfParallelism(1) ) .build(); @@ -148,8 +145,8 @@ public void readFeedDocumentsStartFromCustomDate() { } ChangeFeedProcessorTest.log.info("END processing from thread {}", Thread.currentThread().getId()); }) - .feedContainerClient(createdFeedCollection) - .leaseContainerClient(createdLeaseCollection) + .feedContainer(createdFeedCollection) + .leaseContainer(createdLeaseCollection) .options(new ChangeFeedProcessorOptions() .leaseRenewInterval(Duration.ofSeconds(20)) .leaseAcquireInterval(Duration.ofSeconds(10)) @@ -158,11 +155,9 @@ public void readFeedDocumentsStartFromCustomDate() { .leasePrefix("TEST") .maxItemCount(10) .startTime(OffsetDateTime.now().minusDays(1)) - .minPartitionCount(1) - .maxPartitionCount(3) + .minScaleCount(1) + .maxScaleCount(3) .discardExistingLeases(true) - .queryPartitionsMaxBatchSize(2) - .degreeOfParallelism(2) ) .build(); From 42665d2ef62a75bbefe807b8afdb71dcc8cd389f Mon Sep 17 00:00:00 2001 From: Kushagra Thapar Date: Fri, 28 Jun 2019 01:55:31 -0700 Subject: [PATCH 56/85] Wrapped Client Side Request Statistics (#216) * Wrapped Client Side Request Statistics in Cosmos Response Diagnostic Statistics. Exposed only toString and request latency * Code review comments for Cosmos Response Diagnostics * Wrapped Query Metrics Map in Feed Response Diagnostics. Exposed toString through Feed response diagnostics * Reducing scope of setter to package private --- .../com/azure/data/cosmos/BridgeInternal.java | 42 ++++++++++++- .../cosmos/ClientSideRequestStatistics.java | 24 +++---- .../data/cosmos/CosmosClientException.java | 18 +++--- .../com/azure/data/cosmos/CosmosResponse.java | 4 +- .../cosmos/CosmosResponseDiagnostics.java | 63 +++++++++++++++++++ .../com/azure/data/cosmos/FeedResponse.java | 13 ++-- .../data/cosmos/FeedResponseDiagnostics.java | 38 +++++++++++ .../cosmos/internal/ClientRetryPolicy.java | 13 ++-- .../DocumentServiceRequestContext.java | 6 +- .../cosmos/internal/ResourceResponse.java | 24 +++---- .../internal/RxDocumentServiceResponse.java | 6 +- .../internal/StoredProcedureResponse.java | 10 +-- .../directconnectivity/ConsistencyReader.java | 6 +- .../directconnectivity/ConsistencyWriter.java | 12 ++-- .../GatewayAddressCache.java | 8 +-- .../ReplicatedResourceClient.java | 6 +- .../directconnectivity/StoreClient.java | 4 +- .../directconnectivity/StoreReader.java | 17 +++-- .../directconnectivity/StoreResponse.java | 12 ++-- ...ggregateDocumentQueryExecutionContext.java | 6 +- .../OrderByDocumentQueryExecutionContext.java | 4 +- .../cosmos/internal/query/OrderByUtils.java | 7 ++- ...ParallelDocumentQueryExecutionContext.java | 4 +- .../TopDocumentQueryExecutionContext.java | 4 +- .../internal/FeedResponseListValidator.java | 4 +- .../data/cosmos/rx/CollectionCrudTest.java | 6 +- .../cosmos/rx/ParallelDocumentQueryTest.java | 3 +- 27 files changed, 255 insertions(+), 109 deletions(-) create mode 100644 sdk/src/main/java/com/azure/data/cosmos/CosmosResponseDiagnostics.java create mode 100644 sdk/src/main/java/com/azure/data/cosmos/FeedResponseDiagnostics.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java b/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java index 34b17d27cec67..22a8c74d82902 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java +++ b/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java @@ -28,9 +28,11 @@ import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.internal.ReplicationPolicy; import com.azure.data.cosmos.internal.ResourceResponse; +import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.RxDocumentServiceResponse; import com.azure.data.cosmos.internal.StoredProcedureResponse; import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.internal.directconnectivity.StoreResult; import com.azure.data.cosmos.internal.query.metrics.ClientSideMetrics; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.fasterxml.jackson.databind.JsonNode; @@ -43,6 +45,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentMap; import static com.azure.data.cosmos.internal.Constants.QueryExecutionContext.INCREMENTAL_FEED_HEADER_VALUE; @@ -332,8 +335,8 @@ public static Object getValue(JsonNode value) { return JsonSerializable.getValue(value); } - public static CosmosClientException setClientSideRequestStatistics(CosmosClientException cosmosClientException, ClientSideRequestStatistics clientSideRequestStatistics) { - return cosmosClientException.clientSideRequestStatistics(clientSideRequestStatistics); + public static CosmosClientException setCosmosResponseDiagnostics(CosmosClientException cosmosClientException, CosmosResponseDiagnostics cosmosResponseDiagnostics) { + return cosmosClientException.cosmosResponseDiagnostics(cosmosResponseDiagnostics); } public static CosmosClientException createCosmosClientException(int statusCode) { @@ -367,4 +370,39 @@ public static CosmosClientException createCosmosClientException(String message, cosmosClientException.resourceAddress = resourceAddress; return cosmosClientException; } + + public static CosmosResponseDiagnostics createCosmosResponseDiagnostics() { + return new CosmosResponseDiagnostics(); + } + + public static void recordResponse(CosmosResponseDiagnostics cosmosResponseDiagnostics, + RxDocumentServiceRequest request, StoreResult storeResult) { + cosmosResponseDiagnostics.clientSideRequestStatistics().recordResponse(request, storeResult); + } + + public static String recordAddressResolutionStart(CosmosResponseDiagnostics cosmosResponseDiagnostics, + URI targetEndpoint) { + return cosmosResponseDiagnostics.clientSideRequestStatistics().recordAddressResolutionStart(targetEndpoint); + } + + public static void recordAddressResolutionEnd(CosmosResponseDiagnostics cosmosResponseDiagnostics, + String identifier) { + cosmosResponseDiagnostics.clientSideRequestStatistics().recordAddressResolutionEnd(identifier); + } + + public static List getContactedReplicas(CosmosResponseDiagnostics cosmosResponseDiagnostics) { + return cosmosResponseDiagnostics.clientSideRequestStatistics().getContactedReplicas(); + } + + public static void setContactedReplicas(CosmosResponseDiagnostics cosmosResponseDiagnostics, List contactedReplicas) { + cosmosResponseDiagnostics.clientSideRequestStatistics().setContactedReplicas(contactedReplicas); + } + + public static Set getFailedReplicas(CosmosResponseDiagnostics cosmosResponseDiagnostics) { + return cosmosResponseDiagnostics.clientSideRequestStatistics().getFailedReplicas(); + } + + public static ConcurrentMap queryMetricsFromFeedResponse(FeedResponse feedResponse) { + return feedResponse.queryMetrics(); + } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java b/sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java index 11607a8372519..39d4d16f3159a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java @@ -44,7 +44,7 @@ import java.util.Map; import java.util.Set; -public class ClientSideRequestStatistics { +class ClientSideRequestStatistics { private final static int MAX_SUPPLEMENTAL_REQUESTS_FOR_TO_STRING = 10; @@ -61,7 +61,7 @@ public class ClientSideRequestStatistics { private Set failedReplicas; private Set regionsContacted; - public ClientSideRequestStatistics() { + ClientSideRequestStatistics() { this.requestStartTime = ZonedDateTime.now(ZoneOffset.UTC); this.requestEndTime = ZonedDateTime.now(ZoneOffset.UTC); this.responseStatisticsList = new ArrayList<>(); @@ -72,7 +72,7 @@ public ClientSideRequestStatistics() { this.regionsContacted = new HashSet<>(); } - public Duration getRequestLatency() { + Duration getRequestLatency() { return Duration.between(requestStartTime, requestEndTime); } @@ -81,7 +81,7 @@ private boolean isCPUOverloaded() { return false; } - public void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult) { + void recordResponse(RxDocumentServiceRequest request, StoreResult storeResult) { ZonedDateTime responseTime = ZonedDateTime.now(ZoneOffset.UTC); StoreResponseStatistics storeResponseStatistics = new StoreResponseStatistics(); @@ -117,7 +117,7 @@ public void recordResponse(RxDocumentServiceRequest request, StoreResult storeRe } } - public String recordAddressResolutionStart(URI targetEndpoint) { + String recordAddressResolutionStart(URI targetEndpoint) { String identifier = Utils.randomUUID().toString(); AddressResolutionStatistics resolutionStatistics = new AddressResolutionStatistics(); @@ -133,7 +133,7 @@ public String recordAddressResolutionStart(URI targetEndpoint) { return identifier; } - public void recordAddressResolutionEnd(String identifier) { + void recordAddressResolutionEnd(String identifier) { if (StringUtils.isEmpty(identifier)) { return; } @@ -206,27 +206,27 @@ public String toString() { return StringUtils.EMPTY; } - public List getContactedReplicas() { + List getContactedReplicas() { return contactedReplicas; } - public void setContactedReplicas(List contactedReplicas) { + void setContactedReplicas(List contactedReplicas) { this.contactedReplicas = contactedReplicas; } - public Set getFailedReplicas() { + Set getFailedReplicas() { return failedReplicas; } - public void setFailedReplicas(Set failedReplicas) { + void setFailedReplicas(Set failedReplicas) { this.failedReplicas = failedReplicas; } - public Set getRegionsContacted() { + Set getRegionsContacted() { return regionsContacted; } - public void setRegionsContacted(Set regionsContacted) { + void setRegionsContacted(Set regionsContacted) { this.regionsContacted = regionsContacted; } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClientException.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClientException.java index a33b84290106d..cd3b216dc6c4c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosClientException.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosClientException.java @@ -53,7 +53,7 @@ public class CosmosClientException extends Exception { private final int statusCode; private final Map responseHeaders; - private ClientSideRequestStatistics clientSideRequestStatistics; + private CosmosResponseDiagnostics cosmosResponseDiagnostics; private CosmosError cosmosError; long lsn; @@ -141,10 +141,10 @@ public class CosmosClientException extends Exception { @Override public String getMessage() { - if (clientSideRequestStatistics == null) { + if (cosmosResponseDiagnostics == null) { return innerErrorMessage(); } - return innerErrorMessage() + ", " + clientSideRequestStatistics.toString(); + return innerErrorMessage() + ", " + cosmosResponseDiagnostics.toString(); } /** @@ -250,16 +250,16 @@ String getResourceAddress() { } /** - * Gets the Client side request statistics associated with this exception. + * Gets the Cosmos Response Diagnostic Statistics associated with this exception. * - * @return Client side request statistics associated with this exception. + * @return Cosmos Response Diagnostic Statistics associated with this exception. */ - public ClientSideRequestStatistics clientSideRequestStatistics() { - return clientSideRequestStatistics; + public CosmosResponseDiagnostics cosmosResponseDiagnostics() { + return cosmosResponseDiagnostics; } - CosmosClientException clientSideRequestStatistics(ClientSideRequestStatistics clientSideRequestStatistics) { - this.clientSideRequestStatistics = clientSideRequestStatistics; + CosmosClientException cosmosResponseDiagnostics(CosmosResponseDiagnostics cosmosResponseDiagnostics) { + this.cosmosResponseDiagnostics = cosmosResponseDiagnostics; return this; } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java index b34b756da4f5f..716603437307d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java @@ -122,8 +122,8 @@ public Map responseHeaders() { * * @return diagnostics information for the current request to Azure Cosmos DB service. */ - public String requestDiagnosticsString() { - return resourceResponseWrapper.getRequestDiagnosticsString(); + public CosmosResponseDiagnostics cosmosResponseDiagnosticsString() { + return resourceResponseWrapper.getCosmosResponseDiagnostics(); } /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosResponseDiagnostics.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosResponseDiagnostics.java new file mode 100644 index 0000000000000..3346298fba3a0 --- /dev/null +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosResponseDiagnostics.java @@ -0,0 +1,63 @@ +/* + * The MIT License (MIT) + * Copyright (c) 2018 Microsoft Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.azure.data.cosmos; + +import java.time.Duration; + +/** + * This class represents response diagnostic statistics associated with a request to Azure Cosmos DB + */ +public class CosmosResponseDiagnostics { + + private ClientSideRequestStatistics clientSideRequestStatistics; + + CosmosResponseDiagnostics() { + this.clientSideRequestStatistics = new ClientSideRequestStatistics(); + } + + ClientSideRequestStatistics clientSideRequestStatistics() { + return clientSideRequestStatistics; + } + + CosmosResponseDiagnostics clientSideRequestStatistics(ClientSideRequestStatistics clientSideRequestStatistics) { + this.clientSideRequestStatistics = clientSideRequestStatistics; + return this; + } + + /** + * Retrieves Response Diagnostic String + * @return Response Diagnostic String + */ + @Override + public String toString() { + return this.clientSideRequestStatistics.toString(); + } + + /** + * Retrieves latency related to the completion of the request + * @return request completion latency + */ + public Duration requestLatency() { + return this.clientSideRequestStatistics.getRequestLatency(); + } +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/FeedResponse.java b/sdk/src/main/java/com/azure/data/cosmos/FeedResponse.java index fbb08ab6d238b..ce9d880e2db1c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/FeedResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/FeedResponse.java @@ -45,6 +45,7 @@ public class FeedResponse { boolean nochanges; private final ConcurrentMap queryMetricsMap; private final String DefaultPartition = "0"; + private final FeedResponseDiagnostics feedResponseDiagnostics; FeedResponse(List results, Map headers) { this(results, headers, false, false, new ConcurrentHashMap<>()); @@ -73,6 +74,7 @@ private FeedResponse( this.useEtagAsContinuation = useEtagAsContinuation; this.nochanges = nochanges; this.queryMetricsMap = new ConcurrentHashMap<>(queryMetricsMap); + this.feedResponseDiagnostics = new FeedResponseDiagnostics(queryMetricsMap); } /** @@ -309,11 +311,14 @@ private String queryMetricsString(){ } /** - * Gets the QueryMetrics for each partition. - * - * @return the QueryMetrics for each partition. + * Gets the feed response diagnostics + * @return Feed response diagnostics */ - public ConcurrentMap queryMetrics() { + public FeedResponseDiagnostics feedResponseDiagnostics() { + return this.feedResponseDiagnostics; + } + + ConcurrentMap queryMetrics() { if (queryMetricsMap != null && !queryMetricsMap.isEmpty()) { return queryMetricsMap; } diff --git a/sdk/src/main/java/com/azure/data/cosmos/FeedResponseDiagnostics.java b/sdk/src/main/java/com/azure/data/cosmos/FeedResponseDiagnostics.java new file mode 100644 index 0000000000000..acabc5c5f32d9 --- /dev/null +++ b/sdk/src/main/java/com/azure/data/cosmos/FeedResponseDiagnostics.java @@ -0,0 +1,38 @@ +package com.azure.data.cosmos; + +import com.azure.data.cosmos.internal.QueryMetrics; +import org.apache.commons.lang3.StringUtils; + +import java.util.Map; + +public class FeedResponseDiagnostics { + + private Map queryMetricsMap; + + FeedResponseDiagnostics(Map queryMetricsMap) { + this.queryMetricsMap = queryMetricsMap; + } + + Map queryMetricsMap() { + return queryMetricsMap; + } + + FeedResponseDiagnostics queryMetricsMap(Map queryMetricsMap) { + this.queryMetricsMap = queryMetricsMap; + return this; + } + + /** + * Returns the textual representation of feed response metrics + * @return Textual representation of feed response metrics + */ + @Override + public String toString() { + if (queryMetricsMap == null || queryMetricsMap.isEmpty()) { + return StringUtils.EMPTY; + } + StringBuilder stringBuilder = new StringBuilder(); + queryMetricsMap.forEach((key, value) -> stringBuilder.append(key).append("=").append(value.toString()).append("\n")); + return stringBuilder.toString(); + } +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java index 032f439056100..239899573eb5f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java @@ -22,8 +22,9 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; +import com.azure.data.cosmos.CosmosResponseDiagnostics; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.internal.directconnectivity.WebExceptionUtility; import org.apache.commons.collections4.list.UnmodifiableList; @@ -57,7 +58,7 @@ public class ClientRetryPolicy implements IDocumentClientRetryPolicy { private boolean canUseMultipleWriteLocations; private URL locationEndpoint; private RetryContext retryContext; - private ClientSideRequestStatistics clientSideRequestStatistics; + private CosmosResponseDiagnostics cosmosResponseDiagnostics; public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, boolean enableEndpointDiscovery, @@ -71,7 +72,7 @@ public ClientRetryPolicy(GlobalEndpointManager globalEndpointManager, this.enableEndpointDiscovery = enableEndpointDiscovery; this.sessionTokenRetryCount = 0; this.canUseMultipleWriteLocations = false; - this.clientSideRequestStatistics = new ClientSideRequestStatistics(); + this.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics(); } @Override @@ -86,8 +87,8 @@ public Mono shouldRetry(Exception e) { this.retryContext = null; // Received 403.3 on write region, initiate the endpoint re-discovery CosmosClientException clientException = Utils.as(e, CosmosClientException.class); - if (clientException != null && clientException.clientSideRequestStatistics() != null) { - this.clientSideRequestStatistics = clientException.clientSideRequestStatistics(); + if (clientException != null && clientException.cosmosResponseDiagnostics() != null) { + this.cosmosResponseDiagnostics = clientException.cosmosResponseDiagnostics(); } if (clientException != null && Exceptions.isStatusCode(clientException, HttpConstants.StatusCodes.FORBIDDEN) && @@ -194,7 +195,7 @@ public void onBeforeSendRequest(RxDocumentServiceRequest request) { this.isReadRequest = request.isReadOnlyRequest(); this.canUseMultipleWriteLocations = this.globalEndpointManager.CanUseMultipleWriteLocations(request); if (request.requestContext != null) { - request.requestContext.clientSideRequestStatistics = this.clientSideRequestStatistics; + request.requestContext.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics; } // clear previous location-based routing directive diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java index bc056e69e3a97..9cb502aa9deae 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java @@ -24,8 +24,8 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.CosmosResponseDiagnostics; import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; import com.azure.data.cosmos.internal.directconnectivity.StoreResult; import com.azure.data.cosmos.internal.directconnectivity.TimeoutHelper; @@ -55,7 +55,7 @@ public class DocumentServiceRequestContext implements Cloneable{ public volatile List storeResponses; public volatile StoreResult quorumSelectedStoreResponse; public volatile PartitionKeyInternal effectivePartitionKey; - public volatile ClientSideRequestStatistics clientSideRequestStatistics; + public volatile CosmosResponseDiagnostics cosmosResponseDiagnostics; /** * Sets routing directive for GlobalEndpointManager to resolve the request @@ -112,7 +112,7 @@ public DocumentServiceRequestContext clone() { context.performLocalRefreshOnGoneException = this.performLocalRefreshOnGoneException; context.effectivePartitionKey = this.effectivePartitionKey; context.performedBackgroundAddressRefresh = this.performedBackgroundAddressRefresh; - context.clientSideRequestStatistics = this.clientSideRequestStatistics; + context.cosmosResponseDiagnostics = this.cosmosResponseDiagnostics; return context; } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java index 78dde448d51bc..2c9f2b1684094 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.CosmosResponseDiagnostics; import com.azure.data.cosmos.Resource; import org.apache.commons.lang3.StringUtils; @@ -337,12 +337,12 @@ public long getLazyIndexingProgress() { } /** - * Gets the request statistics for the current request to Azure Cosmos DB service. + * Gets the request diagnostic statistics for the current request to Azure Cosmos DB service. * - * @return request statistics for the current request to Azure Cosmos DB service. + * @return request diagnostic statistics for the current request to Azure Cosmos DB service. */ - public ClientSideRequestStatistics getClientSideRequestStatistics() { - return this.response.getClientSideRequestStatistics(); + public CosmosResponseDiagnostics getCosmosResponseDiagnostics() { + return this.response.getCosmosResponseRequestDiagnosticStatistics(); } /** @@ -351,12 +351,12 @@ public ClientSideRequestStatistics getClientSideRequestStatistics() { * @return end-to-end request latency for the current request to Azure Cosmos DB service. */ public Duration getRequestLatency() { - ClientSideRequestStatistics clientSideRequestStatistics = this.response.getClientSideRequestStatistics(); - if (clientSideRequestStatistics == null) { + CosmosResponseDiagnostics cosmosResponseDiagnostics = this.response.getCosmosResponseRequestDiagnosticStatistics(); + if (cosmosResponseDiagnostics == null) { return Duration.ZERO; } - return clientSideRequestStatistics.getRequestLatency(); + return cosmosResponseDiagnostics.requestLatency(); } /** @@ -364,12 +364,12 @@ public Duration getRequestLatency() { * * @return diagnostics information for the current request to Azure Cosmos DB service. */ - public String getRequestDiagnosticsString() { - ClientSideRequestStatistics clientSideRequestStatistics = this.response.getClientSideRequestStatistics(); - if (clientSideRequestStatistics == null) { + public String getCosmosResponseDiagnosticString() { + CosmosResponseDiagnostics cosmosResponseRequestDiagnosticStatistics = this.response.getCosmosResponseRequestDiagnosticStatistics(); + if (cosmosResponseRequestDiagnosticStatistics == null) { return StringUtils.EMPTY; } - return clientSideRequestStatistics.toString(); + return cosmosResponseRequestDiagnosticStatistics.toString(); } long getCurrentQuotaHeader(String headerName) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java index a8a43a7af15f0..718d187451a91 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java @@ -25,8 +25,8 @@ import com.azure.data.cosmos.Attachment; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.Conflict; +import com.azure.data.cosmos.CosmosResponseDiagnostics; import com.azure.data.cosmos.Database; import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentCollection; @@ -210,10 +210,10 @@ public InputStream getContentStream() { return this.storeResponse.getResponseStream(); } - public ClientSideRequestStatistics getClientSideRequestStatistics() { + CosmosResponseDiagnostics getCosmosResponseRequestDiagnosticStatistics() { if (this.storeResponse == null) { return null; } - return this.storeResponse.getClientSideRequestStatistics(); + return this.storeResponse.getCosmosResponseDiagnostics(); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java index 6bb7c858bd2c8..bf4ae1a06bf36 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.Attachment; -import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.CosmosResponseDiagnostics; import com.azure.data.cosmos.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -155,11 +155,11 @@ public String getScriptLog() { } /** - * Gets the client side request statics for execution of stored procedure. + * Gets the request diagnostic statics for execution of stored procedure. * - * @return client side request statistics for execution of stored procedure. + * @return request diagnostic statistics for execution of stored procedure. */ - public ClientSideRequestStatistics getClientSideRequestStatistics() { - return this.response.getClientSideRequestStatistics(); + public CosmosResponseDiagnostics getCosmosResponseDiagnostics() { + return this.response.getCosmosResponseRequestDiagnosticStatistics(); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java index 17898bbc60764..0617e3254d9e9 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; @@ -209,8 +209,8 @@ public Mono readAsync(RxDocumentServiceRequest entity, entity.requestContext.requestChargeTracker = new RequestChargeTracker(); } - if(entity.requestContext.clientSideRequestStatistics == null) { - entity.requestContext.clientSideRequestStatistics = new ClientSideRequestStatistics(); + if(entity.requestContext.cosmosResponseDiagnostics == null) { + entity.requestContext.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics(); } entity.requestContext.forceRefreshAddressCache = forceRefresh; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java index 40e43cab17e97..77ea1e2481761 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; @@ -141,8 +141,8 @@ Mono writePrivateAsync( request.requestContext.requestChargeTracker = new RequestChargeTracker(); } - if (request.requestContext.clientSideRequestStatistics == null) { - request.requestContext.clientSideRequestStatistics = new ClientSideRequestStatistics(); + if (request.requestContext.cosmosResponseDiagnostics == null) { + request.requestContext.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics(); } request.requestContext.forceRefreshAddressCache = forceRefresh; @@ -156,7 +156,7 @@ Mono writePrivateAsync( try { List contactedReplicas = new ArrayList<>(); replicaAddresses.forEach(replicaAddress -> contactedReplicas.add(HttpUtils.toURI(replicaAddress.getPhysicalUri()))); - request.requestContext.clientSideRequestStatistics.setContactedReplicas(contactedReplicas); + BridgeInternal.setContactedReplicas(request.requestContext.cosmosResponseDiagnostics, contactedReplicas); return Mono.just(AddressSelector.getPrimaryUri(request, replicaAddresses)); } catch (GoneException e) { // RxJava1 doesn't allow throwing checked exception from Observable operators @@ -186,7 +186,7 @@ Mono writePrivateAsync( try { CosmosClientException ex = Utils.as(t, CosmosClientException.class); try { - request.requestContext.clientSideRequestStatistics.recordResponse(request, + BridgeInternal.recordResponse(request.requestContext.cosmosResponseDiagnostics, request, storeReader.createStoreResult(null, ex, false, false, primaryUri)); } catch (CosmosClientException e) { logger.error("Error occurred while recording response", e); @@ -207,7 +207,7 @@ Mono writePrivateAsync( }).flatMap(response -> { try { - request.requestContext.clientSideRequestStatistics.recordResponse(request, + BridgeInternal.recordResponse(request.requestContext.cosmosResponseDiagnostics, request, storeReader.createStoreResult(response, null, false, false, primaryURI.get())); } catch (CosmosClientException e) { logger.error("Error occurred while recording response", e); diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java index 4c858afab2585..ff1d49a1764ea 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java @@ -524,8 +524,8 @@ private boolean notAllReplicasAvailable(AddressInformation[] addressInformations private static String logAddressResolutionStart(RxDocumentServiceRequest request, URL targetEndpointUrl) { try { - if (request.requestContext.clientSideRequestStatistics != null) { - return request.requestContext.clientSideRequestStatistics.recordAddressResolutionStart(targetEndpointUrl.toURI()); + if (request.requestContext.cosmosResponseDiagnostics != null) { + return BridgeInternal.recordAddressResolutionStart(request.requestContext.cosmosResponseDiagnostics, targetEndpointUrl.toURI()); } } catch (URISyntaxException e) { throw new IllegalArgumentException(e); @@ -534,8 +534,8 @@ private static String logAddressResolutionStart(RxDocumentServiceRequest request } private static void logAddressResolutionEnd(RxDocumentServiceRequest request, String identifier) { - if (request.requestContext.clientSideRequestStatistics != null) { - request.requestContext.clientSideRequestStatistics.recordAddressResolutionEnd(identifier); + if (request.requestContext.cosmosResponseDiagnostics != null) { + BridgeInternal.recordAddressResolutionEnd(request.requestContext.cosmosResponseDiagnostics, identifier); } } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java index 629121b8b2c27..138219cd319ba 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.internal.BackoffRetryUtility; @@ -139,8 +139,8 @@ public Mono invokeAsync(RxDocumentServiceRequest request, // 2. enableReadRequestsFallback is set to true. (can only ever be true if // direct mode, on client) if (request.isReadOnlyRequest() && this.enableReadRequestsFallback) { - if (request.requestContext.clientSideRequestStatistics == null) { - request.requestContext.clientSideRequestStatistics = new ClientSideRequestStatistics(); + if (request.requestContext.cosmosResponseDiagnostics == null) { + request.requestContext.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics(); } RxDocumentServiceRequest freshRequest = request.clone(); inBackoffFuncDelegate = (Quadruple forceRefreshAndTimeout) -> { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java index c495a6b00ee0e..f12f4d6f17e8e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java @@ -114,7 +114,7 @@ public Mono processMessageAsync(RxDocumentServiceRequ return; } - exception = BridgeInternal.setClientSideRequestStatistics(exception, request.requestContext.clientSideRequestStatistics); + exception = BridgeInternal.setCosmosResponseDiagnostics(exception, request.requestContext.cosmosResponseDiagnostics); handleUnsuccessfulStoreResponse(request, exception); } catch (Throwable throwable) { @@ -160,7 +160,7 @@ private RxDocumentServiceResponse completeResponse( this.updateResponseHeader(request, headers); this.captureSessionToken(request, headers); - storeResponse.setClientSideRequestStatistics(request.requestContext.clientSideRequestStatistics); + storeResponse.setCosmosResponseDiagnostics(request.requestContext.cosmosResponseDiagnostics); return new RxDocumentServiceResponse(storeResponse); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java index fd6fd838a503c..3858838540965 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java @@ -25,7 +25,6 @@ import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.ClientSideRequestStatistics; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; import com.azure.data.cosmos.ISessionContainer; @@ -116,8 +115,8 @@ public Mono> readMultipleReplicaAsync( String originalSessionToken = entity.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); - if (entity.requestContext.clientSideRequestStatistics == null) { - entity.requestContext.clientSideRequestStatistics = new ClientSideRequestStatistics(); + if (entity.requestContext.cosmosResponseDiagnostics == null) { + entity.requestContext.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics(); } Mono readQuorumResultObs = this.readMultipleReplicasInternalAsync( @@ -172,7 +171,7 @@ private Flux toStoreResult(RxDocumentServiceRequest request, readMode != ReadMode.Strong, storeRespAndURI.getRight()); - request.requestContext.clientSideRequestStatistics.getContactedReplicas().add(storeRespAndURI.getRight()); + BridgeInternal.getContactedReplicas(request.requestContext.cosmosResponseDiagnostics).add(storeRespAndURI.getRight()); return Flux.just(storeResult); } catch (Exception e) { // RxJava1 doesn't allow throwing checked exception from Observable operators @@ -195,7 +194,7 @@ private Flux toStoreResult(RxDocumentServiceRequest request, readMode != ReadMode.Strong, null); if (storeException instanceof TransportException) { - request.requestContext.clientSideRequestStatistics.getFailedReplicas().add(storeRespAndURI.getRight()); + BridgeInternal.getFailedReplicas(request.requestContext.cosmosResponseDiagnostics).add(storeRespAndURI.getRight()); } return Flux.just(storeResult); } catch (Exception e) { @@ -269,7 +268,7 @@ private Flux> readFromReplicas(List resultCollect for (StoreResult srr : newStoreResults) { entity.requestContext.requestChargeTracker.addCharge(srr.requestCharge); - entity.requestContext.clientSideRequestStatistics.recordResponse(entity, srr); + BridgeInternal.recordResponse(entity.requestContext.cosmosResponseDiagnostics, entity, srr); if (srr.isValid) { try { @@ -460,8 +459,8 @@ public Mono readPrimaryAsync( } String originalSessionToken = entity.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); - if (entity.requestContext.clientSideRequestStatistics == null) { - entity.requestContext.clientSideRequestStatistics = new ClientSideRequestStatistics(); + if (entity.requestContext.cosmosResponseDiagnostics == null) { + entity.requestContext.cosmosResponseDiagnostics = BridgeInternal.createCosmosResponseDiagnostics(); } return this.readPrimaryInternalAsync( @@ -577,7 +576,7 @@ private Mono readPrimaryInternalAsync( }); return storeResultObs.map(storeResult -> { - entity.requestContext.clientSideRequestStatistics.recordResponse(entity, storeResult); + BridgeInternal.recordResponse(entity.requestContext.cosmosResponseDiagnostics, entity, storeResult); entity.requestContext.requestChargeTracker.addCharge(storeResult.requestCharge); if (storeResult.isGoneException && !storeResult.isInvalidPartitionException) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java index dad95e7bd76ce..0639c6bb109c3 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.ClientSideRequestStatistics; +import com.azure.data.cosmos.CosmosResponseDiagnostics; import com.azure.data.cosmos.internal.HttpConstants; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -44,7 +44,7 @@ public class StoreResponse { final private InputStream httpEntityStream; final private String content; - private ClientSideRequestStatistics clientSideRequestStatistics; + private CosmosResponseDiagnostics cosmosResponseDiagnostics; public StoreResponse(int status, List> headerEntries, InputStream inputStream) { this(status, headerEntries, null, inputStream); @@ -128,12 +128,12 @@ public String getHeaderValue(String attribute) { return null; } - public ClientSideRequestStatistics getClientSideRequestStatistics() { - return clientSideRequestStatistics; + public CosmosResponseDiagnostics getCosmosResponseDiagnostics() { + return cosmosResponseDiagnostics; } - public void setClientSideRequestStatistics(ClientSideRequestStatistics clientSideRequestStatistics) { - this.clientSideRequestStatistics = clientSideRequestStatistics; + void setCosmosResponseDiagnostics(CosmosResponseDiagnostics cosmosResponseDiagnostics) { + this.cosmosResponseDiagnostics = cosmosResponseDiagnostics; } int getSubStatusCode() { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java index 6f52e5c998975..88ed48ccdd0be 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java @@ -106,12 +106,12 @@ public Flux> drainAsync(int maxPageSize) { requestCharge += page.requestCharge(); QueryItem values = new QueryItem(doc.toJson()); this.aggregator.aggregate(values.getItem()); - for(String key : page.queryMetrics().keySet()) { + for(String key : BridgeInternal.queryMetricsFromFeedResponse(page).keySet()) { if (queryMetricsMap.containsKey(key)) { - QueryMetrics qm = page.queryMetrics().get(key); + QueryMetrics qm = BridgeInternal.queryMetricsFromFeedResponse(page).get(key); queryMetricsMap.get(key).add(qm); } else { - queryMetricsMap.put(key, page.queryMetrics().get(key)); + queryMetricsMap.put(key, BridgeInternal.queryMetricsFromFeedResponse(page).get(key)); } } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java index 32514f32a46a7..30afa3602176a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java @@ -437,7 +437,7 @@ private FeedResponse> addOrderByContinuationToken( orderByContinuationToken); return BridgeInternal.createFeedResponseWithQueryMetrics(page.results(), headers, - page.queryMetrics()); + BridgeInternal.queryMetricsFromFeedResponse(page)); } @Override @@ -516,7 +516,7 @@ public Flux> apply(Flux> source) { return BridgeInternal.createFeedResponseWithQueryMetrics(unwrappedResults, feedOfOrderByRowResults.responseHeaders(), - feedOfOrderByRowResults.queryMetrics()); + BridgeInternal.queryMetricsFromFeedResponse(feedOfOrderByRowResults)); }).switchIfEmpty(Flux.defer(() -> { // create an empty page if there is no result return Flux.just(BridgeInternal.createFeedResponse(Utils.immutableListOf(), diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java index 2cd35c048a347..2837ac580b817 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos.internal.query; import com.azure.data.cosmos.BadRequestException; +import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.internal.RequestChargeTracker; @@ -87,12 +88,12 @@ public PageToItemTransformer(Class klass, RequestChargeTracker tracker, Map> apply(Flux.DocumentProducerFeedResponse> source) { return source.flatMap(documentProducerFeedResponse -> { - for (String key : documentProducerFeedResponse.pageResult.queryMetrics().keySet()) { + for (String key : BridgeInternal.queryMetricsFromFeedResponse(documentProducerFeedResponse.pageResult).keySet()) { if (queryMetricsMap.containsKey(key)) { - QueryMetrics qm = documentProducerFeedResponse.pageResult.queryMetrics().get(key); + QueryMetrics qm = BridgeInternal.queryMetricsFromFeedResponse(documentProducerFeedResponse.pageResult).get(key); queryMetricsMap.get(key).add(qm); } else { - queryMetricsMap.put(key, documentProducerFeedResponse.pageResult.queryMetrics().get(key)); + queryMetricsMap.put(key, BridgeInternal.queryMetricsFromFeedResponse(documentProducerFeedResponse.pageResult).get(key)); } } List results = documentProducerFeedResponse.pageResult.results(); diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java index 074f84dfd0171..61b9354ea8fb3 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java @@ -212,7 +212,7 @@ private DocumentProducer.DocumentProducerFeedResponse plusCharge( String.valueOf(pageCharge)); FeedResponse newPage = BridgeInternal.createFeedResponseWithQueryMetrics(page.results(), headers, - page.queryMetrics()); + BridgeInternal.queryMetricsFromFeedResponse(page)); documentProducerFeedResponse.pageResult = newPage; return documentProducerFeedResponse; } @@ -226,7 +226,7 @@ private DocumentProducer.DocumentProducerFeedResponse addCompositeContinuatio compositeContinuationToken); FeedResponse newPage = BridgeInternal.createFeedResponseWithQueryMetrics(page.results(), headers, - page.queryMetrics()); + BridgeInternal.queryMetricsFromFeedResponse(page)); documentProducerFeedResponse.pageResult = newPage; return documentProducerFeedResponse; } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java index f169b94ff5bdf..661b132cf5a90 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java @@ -128,7 +128,7 @@ public FeedResponse apply(FeedResponse t) { } return BridgeInternal.createFeedResponseWithQueryMetrics(t.results(), headers, - t.queryMetrics()); + BridgeInternal.queryMetricsFromFeedResponse(t)); } else { assert lastPage == false; lastPage = true; @@ -140,7 +140,7 @@ public FeedResponse apply(FeedResponse t) { headers.put(HttpConstants.HttpHeaders.CONTINUATION, null); return BridgeInternal.createFeedResponseWithQueryMetrics(t.results().subList(0, lastPageSize), - headers, t.queryMetrics()); + headers, BridgeInternal.queryMetricsFromFeedResponse(t)); } } }); diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java index 31380c1e2f7b8..aedb8d046173f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java @@ -295,7 +295,7 @@ public Builder hasValidQueryMetrics(boolean shouldHaveMetrics) { public void validate(List> feedList) { for(FeedResponse feedPage: feedList) { if (shouldHaveMetrics) { - QueryMetrics queryMetrics = BridgeInternal.createQueryMetricsFromCollection(feedPage.queryMetrics().values()); + QueryMetrics queryMetrics = BridgeInternal.createQueryMetricsFromCollection(BridgeInternal.queryMetricsFromFeedResponse(feedPage).values()); assertThat(queryMetrics.getIndexHitDocumentCount()).isGreaterThanOrEqualTo(0); assertThat(queryMetrics.getRetrievedDocumentSize()).isGreaterThan(0); assertThat(queryMetrics.getTotalQueryExecutionTime().compareTo(Duration.ZERO)).isGreaterThan(0); @@ -310,7 +310,7 @@ public void validate(List> feedList) { assertThat(queryMetrics.getRuntimeExecutionTimes().getQueryEngineExecutionTime().compareTo(Duration.ZERO)).isGreaterThanOrEqualTo(0); assertThat(BridgeInternal.getClientSideMetrics(queryMetrics).getRequestCharge()).isGreaterThan(0); } else { - assertThat(feedPage.queryMetrics().isEmpty()); + assertThat(BridgeInternal.queryMetricsFromFeedResponse(feedPage).isEmpty()); } } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java index 9fba4bc3c1a71..24e525a20d7cf 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java @@ -286,12 +286,12 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { CosmosItemRequestOptions options = new CosmosItemRequestOptions(); options.partitionKey(new PartitionKey("mypkValue")); CosmosItemResponse readDocumentResponse = item.read(options).block(); - logger.info("Client 1 READ Document Client Side Request Statistics {}", readDocumentResponse.requestDiagnosticsString()); + logger.info("Client 1 READ Document Client Side Request Statistics {}", readDocumentResponse.cosmosResponseDiagnosticsString()); logger.info("Client 1 READ Document Latency {}", readDocumentResponse.requestLatency()); BridgeInternal.setProperty(document, "name", "New Updated Document"); CosmosItemResponse upsertDocumentResponse = collection.upsertItem(document).block(); - logger.info("Client 1 Upsert Document Client Side Request Statistics {}", upsertDocumentResponse.requestDiagnosticsString()); + logger.info("Client 1 Upsert Document Client Side Request Statistics {}", upsertDocumentResponse.cosmosResponseDiagnosticsString()); logger.info("Client 1 Upsert Document Latency {}", upsertDocumentResponse.requestLatency()); // DELETE the existing collection @@ -306,7 +306,7 @@ public void sessionTokenConsistencyCollectionDeleteCreateSameName() { createDocument(collection2, newDocument); readDocumentResponse = client1.getDatabase(dbId).getContainer(collectionId).getItem(newDocument.id(), newDocument.get("mypk")).read().block(); - logger.info("Client 2 READ Document Client Side Request Statistics {}", readDocumentResponse.requestDiagnosticsString()); + logger.info("Client 2 READ Document Client Side Request Statistics {}", readDocumentResponse.cosmosResponseDiagnosticsString()); logger.info("Client 2 READ Document Latency {}", readDocumentResponse.requestLatency()); CosmosItemProperties readDocument = readDocumentResponse.properties(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java index 7cb82188c3b99..e7b8a697d8a96 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java @@ -121,7 +121,8 @@ public void queryMetricEquality() throws Exception { assertThat(resultList1.size()).isEqualTo(resultList2.size()); for(int i = 0; i < resultList1.size(); i++){ - compareQueryMetrics(resultList1.get(i).queryMetrics(), resultList2.get(i).queryMetrics()); + compareQueryMetrics(BridgeInternal.queryMetricsFromFeedResponse(resultList1.get(i)), + BridgeInternal.queryMetricsFromFeedResponse(resultList2.get(i))); } } From 415ab5eebd09daf2f1f6a3742d00876cb9806274 Mon Sep 17 00:00:00 2001 From: Christopher Anderson Date: Fri, 28 Jun 2019 03:42:57 -0700 Subject: [PATCH 57/85] Final cleanup for V3 (#217) * Hide AsyncDocumentClient * Remove Attachment * Cleanup ChangeFeedOptions * Hide Conflict * Cleanup ConsistencyPolicy * Cleanup CosmosClient * Cleanup CosmosClientBuilder * Cleanup CosmosConflict * Cleanup CosmosConflictProperties * CosmosConflictResponse cleanup * Cleanup CosmosContainer * Cleanup CosmosContainerRequestOptions * Cleanup CosmosContainerResponse * Cleanup CosmosContainerProperties * Cleanup CosmosDatabase * Cleanup CosmosDatabaseRequestOptions * Remove CosmosFeedResponse * Cleanup CosmosItemRequestOptions * Cleanup CosmosPermissionsRequestOptions * Remove CosmosRequestOptions * Cleanup CosmosStoredProcedure * Cleanup CosmosStoredProcedureRequestOptions * Cleanup CosmosTrigger * Cleanup CosmosUser * Cleanup CosmosUDF * Cleanup CosmosUDFResposne * Clean up CosmosUserResponse * Cleanup CosmosUserProperties * Hide old v2 types * Hide Json constructors * Remove MediaReadMode * Hide Undefined * list to readAll * Fix json serialization --- .../data/cosmos/benchmark/AsyncBenchmark.java | 8 +- .../cosmos/benchmark/AsyncMixedBenchmark.java | 2 +- .../cosmos/benchmark/AsyncQueryBenchmark.java | 2 +- .../AsyncQuerySinglePartitionMultiple.java | 2 +- .../cosmos/benchmark/AsyncReadBenchmark.java | 2 +- .../cosmos/benchmark/AsyncWriteBenchmark.java | 2 +- .../data/cosmos/benchmark/DocDBUtils.java | 6 +- .../cosmos/benchmark/ReadMyWriteWorkflow.java | 2 +- .../ReadMyWritesConsistencyTest.java | 6 +- .../azure/data/cosmos/benchmark/Utils.java | 6 +- .../data/cosmos/benchmark/WorkflowTest.java | 6 +- .../azure/data/cosmos/examples/BasicDemo.java | 6 +- .../ChangeFeed/SampleChangeFeedProcessor.java | 6 +- .../rx/examples/multimaster/Helpers.java | 6 +- .../multimaster/samples/ConflictWorker.java | 8 +- .../samples/MultiMasterScenario.java | 2 +- .../examples/multimaster/samples/Worker.java | 4 +- .../azure/data/cosmos/DocumentClientTest.java | 1 + .../examples/CollectionCRUDAsyncAPITest.java | 6 +- .../cosmos/rx/examples/ConflictAPITest.java | 10 +- .../rx/examples/DatabaseCRUDAsyncAPITest.java | 4 +- .../rx/examples/DocumentCRUDAsyncAPITest.java | 8 +- .../examples/DocumentQueryAsyncAPITest.java | 8 +- .../rx/examples/InMemoryGroupbyTest.java | 8 +- .../rx/examples/OfferCRUDAsyncAPITest.java | 6 +- .../examples/StoredProcedureAsyncAPITest.java | 6 +- .../cosmos/rx/examples/TokenResolverTest.java | 8 +- .../rx/examples/UniqueIndexAsyncAPITest.java | 8 +- .../azure/data/cosmos/rx/examples/Utils.java | 6 +- .../com/azure/data/cosmos/Attachment.java | 87 ------ .../com/azure/data/cosmos/BridgeInternal.java | 30 ++ .../azure/data/cosmos/ChangeFeedOptions.java | 18 -- .../data/cosmos/ConflictResolutionMode.java | 1 + .../data/cosmos/ConflictResolutionPolicy.java | 1 + .../azure/data/cosmos/ConnectionPolicy.java | 5 - .../azure/data/cosmos/ConsistencyPolicy.java | 6 +- .../data/cosmos/CosmosBridgeInternal.java | 3 + .../com/azure/data/cosmos/CosmosClient.java | 101 +++++-- .../data/cosmos/CosmosClientBuilder.java | 141 ++++++---- .../com/azure/data/cosmos/CosmosConflict.java | 2 +- .../data/cosmos/CosmosConflictProperties.java | 5 +- .../cosmos/CosmosConflictRequestOptions.java | 30 +- .../data/cosmos/CosmosConflictResponse.java | 6 +- .../azure/data/cosmos/CosmosContainer.java | 148 +++++----- .../cosmos/CosmosContainerProperties.java | 3 +- .../cosmos/CosmosContainerRequestOptions.java | 43 ++- .../data/cosmos/CosmosContainerResponse.java | 3 +- .../com/azure/data/cosmos/CosmosDatabase.java | 257 ++++++++++++++---- .../data/cosmos/CosmosDatabaseProperties.java | 1 + .../cosmos/CosmosDatabaseRequestOptions.java | 37 ++- .../data/cosmos/CosmosDatabaseResponse.java | 1 + .../azure/data/cosmos/CosmosFeedResponse.java | 49 ---- .../com/azure/data/cosmos/CosmosItem.java | 1 + .../data/cosmos/CosmosItemProperties.java | 1 + .../data/cosmos/CosmosItemRequestOptions.java | 31 ++- .../azure/data/cosmos/CosmosItemResponse.java | 1 + .../azure/data/cosmos/CosmosPermission.java | 6 +- .../cosmos/CosmosPermissionProperties.java | 5 +- ...va => CosmosPermissionRequestOptions.java} | 14 +- .../CosmosPermissionsRequestOptions.java | 40 --- .../com/azure/data/cosmos/CosmosResponse.java | 6 +- .../com/azure/data/cosmos/CosmosScripts.java | 34 +-- .../data/cosmos/CosmosStoredProcedure.java | 72 ++++- .../CosmosStoredProcedureRequestOptions.java | 28 +- .../com/azure/data/cosmos/CosmosTrigger.java | 18 +- .../data/cosmos/CosmosTriggerProperties.java | 4 +- .../com/azure/data/cosmos/CosmosUser.java | 56 ++-- .../cosmos/CosmosUserDefinedFunction.java | 21 +- .../CosmosUserDefinedFunctionResponse.java | 6 +- .../data/cosmos/CosmosUserProperties.java | 10 +- .../azure/data/cosmos/CosmosUserResponse.java | 4 +- .../com/azure/data/cosmos/ExcludedPath.java | 2 +- .../java/com/azure/data/cosmos/HashIndex.java | 2 +- .../java/com/azure/data/cosmos/Index.java | 4 +- .../azure/data/cosmos/JsonSerializable.java | 4 + .../{ => internal}/AsyncDocumentClient.java | 27 +- ...eDatabaseAccountConfigurationProvider.java | 3 +- ...ringSessionContainerClientRetryPolicy.java | 1 - .../data/cosmos/{ => internal}/Conflict.java | 5 +- .../data/cosmos/{ => internal}/Database.java | 4 +- .../{ => internal}/DatabaseAccount.java | 70 ++--- .../DatabaseAccountLocation.java | 12 +- .../DatabaseAccountManagerInternal.java | 3 +- .../data/cosmos/internal/DatabaseForTest.java | 1 - .../data/cosmos/{ => internal}/Document.java | 17 +- .../{ => internal}/DocumentCollection.java | 39 ++- .../internal/GlobalEndpointManager.java | 2 - .../data/cosmos/internal/HttpConstants.java | 2 +- .../{ => internal}/ISessionContainer.java | 2 +- .../data/cosmos/internal/MediaReadMode.java | 44 --- .../PartitionKeyRangeGoneRetryPolicy.java | 1 - .../data/cosmos/internal/PathsHelper.java | 8 - ...enameCollectionAwareClientRetryPolicy.java | 2 - .../ResetSessionTokenRetryPolicyFactory.java | 1 - .../cosmos/internal/RxDocumentClientImpl.java | 8 - .../internal/RxDocumentServiceResponse.java | 9 +- .../cosmos/internal/RxGatewayStoreModel.java | 1 - .../cosmos/internal/SessionContainer.java | 1 - .../cosmos/internal/SessionTokenHelper.java | 1 - .../internal/StoredProcedureResponse.java | 11 - .../data/cosmos/{ => internal}/Undefined.java | 4 +- .../com/azure/data/cosmos/internal/Utils.java | 1 - .../caches/RxClientCollectionCache.java | 4 +- .../internal/caches/RxCollectionCache.java | 2 +- .../caches/RxPartitionKeyRangeCache.java | 4 +- .../changefeed/ChangeFeedContextClient.java | 4 +- .../changefeed/LeaseStoreManagerSettings.java | 2 +- .../changefeed/ProcessorSettings.java | 2 +- .../internal/changefeed/ServiceItemLease.java | 2 +- .../ChangeFeedContextClientImpl.java | 2 +- .../implementation/LeaseStoreManagerImpl.java | 8 +- .../PartitionProcessorImpl.java | 8 +- .../PartitionSynchronizerImpl.java | 4 +- .../directconnectivity/AddressResolver.java | 2 +- .../directconnectivity/ConsistencyReader.java | 2 +- .../directconnectivity/ConsistencyWriter.java | 2 +- .../GatewayAddressCache.java | 2 +- .../GatewayServiceConfigurationReader.java | 11 +- .../GlobalAddressResolver.java | 2 +- .../ReplicatedResourceClient.java | 2 +- .../directconnectivity/StoreReader.java | 2 +- ...ggregateDocumentQueryExecutionContext.java | 4 +- .../DocumentQueryExecutionContextFactory.java | 2 +- .../cosmos/internal/query/ItemTypeHelper.java | 2 +- .../ProxyDocumentQueryExecutionContext.java | 2 +- .../data/cosmos/internal/query/QueryItem.java | 2 +- .../query/aggregation/AverageAggregator.java | 2 +- .../query/aggregation/MaxAggregator.java | 2 +- .../query/aggregation/MinAggregator.java | 2 +- .../query/aggregation/SumAggregator.java | 2 +- .../query/orderbyquery/OrderByRowResult.java | 2 +- .../internal/routing/LocationCache.java | 4 +- .../routing/PartitionKeyInternal.java | 2 +- .../com/azure/data/cosmos/BridgeUtils.java | 3 + .../data/cosmos/ClientUnderTestBuilder.java | 20 +- .../com/azure/data/cosmos/ConflictTests.java | 2 + .../azure/data/cosmos/CosmosClientTest.java | 8 +- .../data/cosmos/CosmosPartitionKeyTests.java | 8 +- .../data/cosmos/CosmosResponseValidator.java | 8 +- .../azure/data/cosmos/DocumentClientTest.java | 1 + .../data/cosmos/DocumentCollectionTests.java | 1 + .../com/azure/data/cosmos/DocumentTests.java | 4 +- .../data/cosmos/JsonSerializableTests.java | 18 +- .../data/cosmos/PartitionKeyHashingTests.java | 1 + .../cosmos/internal/ConsistencyTests1.java | 6 - .../cosmos/internal/ConsistencyTests2.java | 3 - .../cosmos/internal/ConsistencyTestsBase.java | 4 - .../DocumentQuerySpyWireContentTest.java | 7 +- .../internal/FeedResponseListValidator.java | 1 - .../cosmos/internal/NetworkFailureTest.java | 4 - ...eCollectionAwareClientRetryPolicyTest.java | 2 - .../internal/ResourceResponseValidator.java | 13 - .../internal/RetryCreateDocumentTest.java | 7 - .../cosmos/internal/RetryThrottleTest.java | 7 - .../internal/RxDocumentClientUnderTest.java | 1 - .../RxDocumentServiceRequestTest.java | 1 - .../internal/RxGatewayStoreModelTest.java | 2 - .../data/cosmos/internal/SessionTest.java | 4 - .../{ => internal}/SpyClientBuilder.java | 4 +- .../internal/SpyClientUnderTestFactory.java | 3 - .../cosmos/internal/StoreHeaderTests.java | 4 - .../data/cosmos/internal/TestSuiteBase.java | 11 +- .../azure/data/cosmos/internal/TestUtils.java | 2 - .../AddressResolverTest.java | 6 +- .../BarrierRequestHelperTest.java | 7 +- .../ConsistencyReaderTest.java | 3 +- .../ConsistencyReaderUnderTest.java | 3 +- .../ConsistencyWriterTest.java | 5 +- .../DCDocumentCrudTest.java | 9 +- .../GatewayAddressCacheTest.java | 11 +- ...GatewayServiceConfigurationReaderTest.java | 7 +- .../GatewayServiceConfiguratorReaderMock.java | 3 +- .../GlobalAddressResolverTest.java | 2 +- .../PartitionKeyInternalTest.java | 2 +- .../directconnectivity/PartitionKeyTest.java | 2 +- .../directconnectivity/QuorumReaderTest.java | 2 +- .../directconnectivity/ReflectionUtils.java | 2 +- .../StoreReaderDotNetTest.java | 3 +- .../directconnectivity/StoreReaderTest.java | 3 +- .../StoreReaderUnderTest.java | 6 +- .../internal/query/DocumentProducerTest.java | 2 +- .../cosmos/internal/query/FetcherTest.java | 2 +- .../internal/routing/LocationCacheTest.java | 6 +- .../data/cosmos/rx/AggregateQueryTests.java | 2 +- .../rx/BackPressureCrossPartitionTest.java | 3 +- .../data/cosmos/rx/BackPressureTest.java | 5 +- .../cosmos/rx/ChangeFeedProcessorTest.java | 8 +- .../azure/data/cosmos/rx/ChangeFeedTest.java | 8 +- .../data/cosmos/rx/CollectionCrudTest.java | 2 +- .../data/cosmos/rx/CosmosConflictTest.java | 2 +- .../azure/data/cosmos/rx/OfferQueryTest.java | 8 +- .../data/cosmos/rx/OfferReadReplaceTest.java | 6 +- .../cosmos/rx/OrderbyDocumentQueryTest.java | 2 +- .../cosmos/rx/ParallelDocumentQueryTest.java | 2 +- .../data/cosmos/rx/PermissionQueryTest.java | 6 +- .../cosmos/rx/ReadFeedCollectionsTest.java | 2 +- .../data/cosmos/rx/ReadFeedDatabasesTest.java | 4 +- .../data/cosmos/rx/ReadFeedDocumentsTest.java | 4 +- .../rx/ReadFeedExceptionHandlingTest.java | 5 +- .../data/cosmos/rx/ReadFeedOffersTest.java | 6 +- .../cosmos/rx/ReadFeedPermissionsTest.java | 4 +- .../data/cosmos/rx/ReadFeedPkrTests.java | 2 +- .../rx/ReadFeedStoredProceduresTest.java | 2 +- .../data/cosmos/rx/ReadFeedTriggersTest.java | 5 +- .../data/cosmos/rx/ReadFeedUdfsTest.java | 9 +- .../data/cosmos/rx/ReadFeedUsersTest.java | 5 +- .../data/cosmos/rx/ResourceTokenTest.java | 8 +- .../rx/SinglePartitionDocumentQueryTest.java | 2 +- .../SinglePartitionReadFeedDocumentsTest.java | 2 +- .../rx/StoredProcedureUpsertReplaceTest.java | 9 +- .../azure/data/cosmos/rx/TestSuiteBase.java | 57 ++-- .../data/cosmos/rx/TokenResolverTest.java | 8 +- .../azure/data/cosmos/rx/TriggerCrudTest.java | 12 +- .../data/cosmos/rx/TriggerQueryTest.java | 3 +- .../cosmos/rx/TriggerUpsertReplaceTest.java | 8 +- .../azure/data/cosmos/rx/UserCrudTest.java | 18 +- .../rx/UserDefinedFunctionCrudTest.java | 11 +- .../rx/UserDefinedFunctionQueryTest.java | 5 +- .../UserDefinedFunctionUpsertReplaceTest.java | 8 +- .../azure/data/cosmos/rx/UserQueryTest.java | 2 +- 220 files changed, 1236 insertions(+), 1143 deletions(-) delete mode 100644 sdk/src/main/java/com/azure/data/cosmos/Attachment.java delete mode 100644 sdk/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java rename sdk/src/main/java/com/azure/data/cosmos/{CosmosRequestOptions.java => CosmosPermissionRequestOptions.java} (81%) delete mode 100644 sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionsRequestOptions.java rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/AsyncDocumentClient.java (98%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/Conflict.java (96%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/Database.java (97%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/DatabaseAccount.java (78%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/DatabaseAccountLocation.java (88%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/DatabaseAccountManagerInternal.java (95%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/Document.java (89%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/DocumentCollection.java (88%) rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/ISessionContainer.java (99%) delete mode 100644 sdk/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java rename sdk/src/main/java/com/azure/data/cosmos/{ => internal}/Undefined.java (95%) rename sdk/src/test/java/com/azure/data/cosmos/{ => internal}/SpyClientBuilder.java (96%) diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java index a28bba1464b8a..f93c9a0b53a27 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos.benchmark; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.benchmark.Configuration.Operation; import com.azure.data.cosmos.internal.ResourceResponse; import com.codahale.metrics.ConsoleReporter; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java index d9e6132dc9300..618d80556beee 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.benchmark; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.internal.RequestOptions; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java index 50132efdabc7c..ee592ad291eeb 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.benchmark; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java index 665e55877a572..a41280c5afe28 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.benchmark; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java index 97edb051a503b..0e8172ec35287 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.benchmark; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.ResourceResponse; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java index c3e69cf140a80..54af2e988b8e2 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.benchmark; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.internal.ResourceResponse; import com.codahale.metrics.Timer; import org.apache.commons.lang3.RandomStringUtils; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java index e9b52b9467fb3..534603bd67031 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java @@ -23,9 +23,9 @@ package com.azure.data.cosmos.benchmark; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.AsyncDocumentClient; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.SqlParameter; import com.azure.data.cosmos.SqlParameterList; diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java index 78590124f2d0c..233f177e3bb66 100644 --- a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java +++ b/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.benchmark; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.PartitionKey; diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java index 80e223094d114..fc7086a6e82da 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos.benchmark; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.DataType; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java index 88bd336a70395..641f85e3753a2 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java @@ -47,11 +47,11 @@ */ -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.internal.DatabaseForTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.RetryOptions; diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java index 7376259cd324a..57e611fec82cd 100644 --- a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java +++ b/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java @@ -23,11 +23,11 @@ package com.azure.data.cosmos.benchmark; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.DataType; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java b/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java index a7089befe8846..5af0ed8f6febd 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java @@ -68,9 +68,9 @@ private void start(){ TestObject testObject2 = new TestObject("item_new_id_2", "test2", "test description2", "CA"); //CREATE an Item async - Mono itemResponseMono = container.createItem(testObject, testObject.country); + Mono itemResponseMono = container.createItem(testObject); //CREATE another Item async - Mono itemResponseMono1 = container.createItem(testObject2, testObject2.country); + Mono itemResponseMono1 = container.createItem(testObject2); //Wait for completion try { @@ -100,7 +100,7 @@ private void createAndReplaceItem() { CosmosItem cosmosItem = null; //CREATE item sync try { - cosmosItem = container.createItem(replaceObject, replaceObject.country) + cosmosItem = container.createItem(replaceObject) .doOnError(throwable -> log("CREATE 3", throwable)) .publishOn(Schedulers.elastic()) .block() diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java index 545c271932924..9267879f9e0f2 100644 --- a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java +++ b/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java @@ -163,9 +163,8 @@ public static CosmosContainer createNewCollection(CosmosClient client, String da CosmosContainerProperties containerSettings = new CosmosContainerProperties(collectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); - requestOptions.offerThroughput(10000); - containerResponse = databaseLink.createContainer(containerSettings, requestOptions).block(); + containerResponse = databaseLink.createContainer(containerSettings, 10000, requestOptions).block(); if (containerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", collectionName, databaseName)); @@ -205,9 +204,8 @@ public static CosmosContainer createNewLeaseCollection(CosmosClient client, Stri CosmosContainerProperties containerSettings = new CosmosContainerProperties(leaseCollectionName, "/id"); CosmosContainerRequestOptions requestOptions = new CosmosContainerRequestOptions(); - requestOptions.offerThroughput(400); - leaseContainerResponse = databaseLink.createContainer(containerSettings, requestOptions).block(); + leaseContainerResponse = databaseLink.createContainer(containerSettings, 400,requestOptions).block(); if (leaseContainerResponse == null) { throw new RuntimeException(String.format("Failed to create collection %s in database %s.", leaseCollectionName, databaseName)); diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java index ab1afe53d34c0..b6a02833768b2 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java @@ -23,10 +23,10 @@ package com.azure.data.cosmos.rx.examples.multimaster; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.internal.ResourceResponse; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java index 116acabea9ef1..720bc936b0ecf 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java @@ -25,13 +25,13 @@ import com.azure.data.cosmos.AccessCondition; import com.azure.data.cosmos.AccessConditionType; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.Conflict; +import com.azure.data.cosmos.internal.Conflict; import com.azure.data.cosmos.ConflictResolutionPolicy; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.Document; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.RequestOptions; diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java index 8604aeabb12b2..42d31123a67bd 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.rx.examples.multimaster.samples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.rx.examples.multimaster.ConfigurationManager; diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java index 482dfccf3dada..f5d7657f89762 100644 --- a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java +++ b/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java @@ -24,9 +24,9 @@ package com.azure.data.cosmos.rx.examples.multimaster.samples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import org.slf4j.Logger; diff --git a/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java b/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java index 054bbcf8595a6..2a537e8ed9b39 100644 --- a/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.google.common.base.Strings; import org.testng.ITest; import org.testng.annotations.AfterMethod; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java index 2b9b08cd2fef8..7a882bc6540db 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java @@ -22,16 +22,16 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DataType; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.DocumentClientTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java index b9b90026eb0f3..b6523b40f163f 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java @@ -22,15 +22,15 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.Conflict; +import com.azure.data.cosmos.internal.AsyncDocumentClient; +import com.azure.data.cosmos.internal.Conflict; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.DocumentClientTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java index a1d9b104c9275..02805f1ab1e76 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java @@ -22,12 +22,12 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.DocumentClientTest; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.ResourceResponse; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java index 3323a42999909..6232cb561f2fc 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java @@ -22,16 +22,16 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.DocumentClientTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java index ebdf0f6d85906..733097ab8cd7e 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java @@ -22,14 +22,14 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.DocumentClientTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java index ddf6feee69bfc..333edfe75b0c2 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java @@ -22,14 +22,14 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.DocumentClientTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.SqlParameter; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java index d3a5733140c23..bfbd72ab5232c 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java @@ -23,15 +23,15 @@ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.DataType; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.DocumentClientTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java index 5351d24b18cb4..e0159e7510340 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java @@ -23,15 +23,15 @@ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.DataType; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.DocumentClientTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.IncludedPath; import com.azure.data.cosmos.Index; import com.azure.data.cosmos.IndexingPolicy; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java index bb7c7cb5a8a77..810d8409a0105 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java @@ -23,15 +23,15 @@ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosResourceType; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.DocumentClientTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.Permission; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java index 6b16f43f26881..f1d48c7f0197f 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java @@ -22,15 +22,15 @@ */ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.DocumentClientTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.UniqueKey; import com.azure.data.cosmos.UniqueKeyPolicy; diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java index 5fd7eab71d6e1..87d3ab1a170ec 100644 --- a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java +++ b/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java @@ -23,12 +23,12 @@ package com.azure.data.cosmos.rx.examples; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.internal.DatabaseForTest; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.ResourceResponse; import com.azure.data.cosmos.RetryOptions; diff --git a/sdk/src/main/java/com/azure/data/cosmos/Attachment.java b/sdk/src/main/java/com/azure/data/cosmos/Attachment.java deleted file mode 100644 index c3a370050ba8a..0000000000000 --- a/sdk/src/main/java/com/azure/data/cosmos/Attachment.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.azure.data.cosmos; - -import com.azure.data.cosmos.internal.Constants; - -/** - * Represents a document attachment in the Azure Cosmos DB database service. - *

- * Each document may contain zero or more attachments. Attachments can be of any MIME type - text, image, binary data. - * These are stored externally in Azure Blob storage. Attachments are automatically deleted when the parent document - * is deleted. - */ -public class Attachment extends Resource { - /** - * Initialize an attachment object. - */ - public Attachment() { - super(); - } - - /** - * Initialize an attachment object from json string. - * - * @param source the json string representation of the Attachment. - */ - public Attachment(String source) { - super(source); - } - - /** - * Gets the MIME content type of the attachment. - * - * @return the content type. - */ - public String getContentType() { - return super.getString(Constants.Properties.CONTENT_TYPE); - } - - /** - * Sets the MIME content type of the attachment. - * - * @param contentType the content type to use. - */ - public void setContentType(String contentType) { - super.set(Constants.Properties.CONTENT_TYPE, contentType); - } - - /** - * Gets the media link associated with the attachment content. - * - * @return the media link. - */ - public String getMediaLink() { - return super.getString(Constants.Properties.MEDIA_LINK); - } - - /** - * Sets the media link associated with the attachment content. - * - * @param mediaLink the media link to use. - */ - public void setMediaLink(String mediaLink) { - super.set(Constants.Properties.MEDIA_LINK, mediaLink); - } -} diff --git a/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java b/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java index 22a8c74d82902..f0e29b03accd6 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java +++ b/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java @@ -23,7 +23,10 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.DatabaseAccount; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.QueryMetrics; import com.azure.data.cosmos.internal.ReplicationPolicy; @@ -40,6 +43,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import java.net.URI; +import java.time.OffsetDateTime; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -371,6 +375,32 @@ public static CosmosClientException createCosmosClientException(String message, return cosmosClientException; } + public static Configs extractConfigs(CosmosClientBuilder cosmosClientBuilder) { + return cosmosClientBuilder.configs(); + } + + public static CosmosClientBuilder injectConfigs(CosmosClientBuilder cosmosClientBuilder, Configs configs) { + return cosmosClientBuilder.configs(configs); + } + + public static String extractContainerSelfLink(CosmosContainer container) { + return container.getLink(); + } + + public static String extractResourceSelfLink(Resource resource) { return resource.selfLink(); } + + public static void setResourceSelfLink(Resource resource, String selfLink) { resource.selfLink(selfLink); } + + public static void populatePropertyBagJsonSerializable(JsonSerializable jsonSerializable) { jsonSerializable.populatePropertyBag(); } + + public static void setMapper(JsonSerializable jsonSerializable, ObjectMapper om) { + jsonSerializable.setMapper(om); + } + + public static void setTimestamp(Resource resource, OffsetDateTime date) { + resource.timestamp(date); + } + public static CosmosResponseDiagnostics createCosmosResponseDiagnostics() { return new CosmosResponseDiagnostics(); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java index daedc612113c1..5635320ebc8ae 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java @@ -199,24 +199,6 @@ public ChangeFeedOptions partitionKey(PartitionKey partitionkey) { return this; } - /** - * Gets the option to enable populate query metrics - * @return whether to enable populate query metrics - */ - public boolean populateQueryMetrics() { - return populateQueryMetrics; - } - - /** - * Sets the option to enable/disable getting metrics relating to query execution on document query requests - * @param populateQueryMetrics whether to enable or disable query metrics - * @return the FeedOptionsBase. - */ - public ChangeFeedOptions populateQueryMetrics(boolean populateQueryMetrics) { - this.populateQueryMetrics = populateQueryMetrics; - return this; - } - /** * Gets the properties * diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java b/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java index d3e058d70e671..5854e31f17e98 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Conflict; import com.azure.data.cosmos.internal.StoredProcedure; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java index 4737e0b6520c3..9f862e8ed9a16 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java @@ -2,6 +2,7 @@ import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.internal.StoredProcedure; import com.azure.data.cosmos.internal.Strings; diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java index d5279ed904f76..524d304acfdfa 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java @@ -23,8 +23,6 @@ package com.azure.data.cosmos; -import com.azure.data.cosmos.internal.MediaReadMode; - import java.net.InetSocketAddress; import java.util.Collections; import java.util.List; @@ -46,7 +44,6 @@ public final class ConnectionPolicy { private int requestTimeoutInMillis; private int mediaRequestTimeoutInMillis; private ConnectionMode connectionMode; - private MediaReadMode mediaReadMode; private int maxPoolSize; private int idleConnectionTimeoutInMillis; private String userAgentSuffix; @@ -65,7 +62,6 @@ public ConnectionPolicy() { this.enableReadRequestsFallback = null; this.idleConnectionTimeoutInMillis = DEFAULT_IDLE_CONNECTION_TIMEOUT_IN_MILLIS; this.maxPoolSize = DEFAULT_MAX_POOL_SIZE; - this.mediaReadMode = MediaReadMode.Buffered; this.mediaRequestTimeoutInMillis = ConnectionPolicy.DEFAULT_MEDIA_REQUEST_TIMEOUT_IN_MILLIS; this.requestTimeoutInMillis = ConnectionPolicy.DEFAULT_REQUEST_TIMEOUT_IN_MILLIS; this.retryOptions = new RetryOptions(); @@ -371,7 +367,6 @@ public String toString() { "requestTimeoutInMillis=" + requestTimeoutInMillis + ", mediaRequestTimeoutInMillis=" + mediaRequestTimeoutInMillis + ", connectionMode=" + connectionMode + - ", mediaReadMode=" + mediaReadMode + ", maxPoolSize=" + maxPoolSize + ", idleConnectionTimeoutInMillis=" + idleConnectionTimeoutInMillis + ", userAgentSuffix='" + userAgentSuffix + '\'' + diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java index 5cd9be8db75c9..2af95869c1db4 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java @@ -28,7 +28,7 @@ import org.apache.commons.lang3.StringUtils; /** - * Encapsulates the settings for consistency policy in the Azure Cosmos DB database service. + * Encapsulates the properties for consistency policy in the Azure Cosmos DB database service. */ public final class ConsistencyPolicy extends JsonSerializable { private static final ConsistencyLevel DEFAULT_DEFAULT_CONSISTENCY_LEVEL = @@ -49,7 +49,7 @@ public ConsistencyPolicy() { * * @param jsonString the json string that represents the consistency policy. */ - public ConsistencyPolicy(String jsonString) { + ConsistencyPolicy(String jsonString) { super(jsonString); } @@ -58,7 +58,7 @@ public ConsistencyPolicy(String jsonString) { * * @return the default consistency level. */ - public ConsistencyLevel getDefaultConsistencyLevel() { + public ConsistencyLevel defaultConsistencyLevel() { ConsistencyLevel result = ConsistencyPolicy.DEFAULT_DEFAULT_CONSISTENCY_LEVEL; try { diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java index dc1f84bbdd4fb..fab004759731b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java @@ -1,5 +1,8 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.AsyncDocumentClient; +import com.azure.data.cosmos.internal.DatabaseAccount; +import com.azure.data.cosmos.internal.DocumentCollection; import reactor.core.publisher.Mono; /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java index 0c7ff61fc8ff0..049d4fc01dfed 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java @@ -22,7 +22,10 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.DatabaseAccount; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Permission; import reactor.core.publisher.Flux; @@ -49,13 +52,13 @@ public class CosmosClient implements AutoCloseable { CosmosClient(CosmosClientBuilder builder) { - this.configs = builder.getConfigs(); - this.serviceEndpoint = builder.getServiceEndpoint(); - this.keyOrResourceToken = builder.getKeyOrResourceToken(); - this.connectionPolicy = builder.getConnectionPolicy(); - this.desiredConsistencyLevel = builder.getDesiredConsistencyLevel(); - this.permissions = builder.getPermissions(); - this.tokenResolver = builder.getTokenResolver(); + this.configs = builder.configs(); + this.serviceEndpoint = builder.endpoint(); + this.keyOrResourceToken = builder.key(); + this.connectionPolicy = builder.connectionPolicy(); + this.desiredConsistencyLevel = builder.consistencyLevel(); + this.permissions = builder.permissions(); + this.tokenResolver = builder.tokenResolver(); this.asyncDocumentClient = new AsyncDocumentClient.Builder() .withServiceEndpoint(this.serviceEndpoint) .withMasterKeyOrResourceToken(this.keyOrResourceToken) @@ -70,10 +73,6 @@ AsyncDocumentClient getContextClient() { return this.asyncDocumentClient; } - public static AsyncDocumentClient getContextClient(CosmosClient cosmosClient) { - return cosmosClient.asyncDocumentClient; - } - /** * Instantiate the cosmos client builder to build cosmos client * @return {@link CosmosClientBuilder} @@ -86,7 +85,7 @@ public static CosmosClientBuilder builder(){ * Get the service endpoint * @return the service endpoint */ - public String getServiceEndpoint() { + String getServiceEndpoint() { return serviceEndpoint; } @@ -102,7 +101,7 @@ String getKeyOrResourceToken() { * Get the connection policy * @return {@link ConnectionPolicy} */ - public ConnectionPolicy getConnectionPolicy() { + ConnectionPolicy getConnectionPolicy() { return connectionPolicy; } @@ -110,7 +109,7 @@ public ConnectionPolicy getConnectionPolicy() { * Gets the consistency level * @return the (@link ConsistencyLevel) */ - public ConsistencyLevel getDesiredConsistencyLevel() { + ConsistencyLevel getDesiredConsistencyLevel() { return desiredConsistencyLevel; } @@ -118,7 +117,7 @@ public ConsistencyLevel getDesiredConsistencyLevel() { * Gets the permission list * @return the permission list */ - public List getPermissions() { + List getPermissions() { return permissions; } @@ -130,7 +129,7 @@ AsyncDocumentClient getDocClientWrapper(){ * Gets the configs * @return the configs */ - public Configs getConfigs() { + Configs getConfigs() { return configs; } @@ -138,7 +137,7 @@ public Configs getConfigs() { * Gets the token resolver * @return the token resolver */ - public TokenResolver getTokenResolver() { + TokenResolver getTokenResolver() { return tokenResolver; } @@ -232,6 +231,68 @@ public Mono createDatabase(String id) { return createDatabase(new CosmosDatabaseProperties(id), new CosmosDatabaseRequestOptions()); } + /** + * Creates a database. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the + * created database. + * In case of failure the {@link Mono} will error. + * + * @param databaseSettings {@link CosmosDatabaseProperties} + * @param throughput the throughput for the database + * @param options {@link CosmosDatabaseRequestOptions} + * @return an {@link Mono} containing the single cosmos database response with the created database or an error. + */ + public Mono createDatabase(CosmosDatabaseProperties databaseSettings, + int throughput, + CosmosDatabaseRequestOptions options) { + if (options == null) { + options = new CosmosDatabaseRequestOptions(); + } + options.offerThroughput(throughput); + Database wrappedDatabase = new Database(); + wrappedDatabase.id(databaseSettings.id()); + return asyncDocumentClient.createDatabase(wrappedDatabase, options.toRequestOptions()).map(databaseResourceResponse -> + new CosmosDatabaseResponse(databaseResourceResponse, this)).single(); + } + + /** + * Creates a database. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the + * created database. + * In case of failure the {@link Mono} will error. + * + * @param databaseSettings {@link CosmosDatabaseProperties} + * @param throughput the throughput for the database + * @return an {@link Mono} containing the single cosmos database response with the created database or an error. + */ + public Mono createDatabase(CosmosDatabaseProperties databaseSettings, int throughput) { + CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions(); + options.offerThroughput(throughput); + return createDatabase(databaseSettings, options); + } + + /** + * Creates a database. + * + * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the + * created database. + * In case of failure the {@link Mono} will error. + * + * @param id id of the database + * @param throughput the throughput for the database + * @return a {@link Mono} containing the single cosmos database response with the created database or an error. + */ + public Mono createDatabase(String id, int throughput) { + CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions(); + options.offerThroughput(throughput); + return createDatabase(new CosmosDatabaseProperties(id), options); + } + /** * Reads all databases. * @@ -242,7 +303,7 @@ public Mono createDatabase(String id) { * @param options {@link FeedOptions} * @return a {@link Flux} containing one or several feed response pages of read databases or an error. */ - public Flux> listDatabases(FeedOptions options) { + public Flux> readAllDatabases(FeedOptions options) { return getDocClientWrapper().readDatabases(options) .map(response-> BridgeInternal.createFeedResponse(CosmosDatabaseProperties.getFromV2Results(response.results()), response.responseHeaders())); @@ -257,8 +318,8 @@ public Flux> listDatabases(FeedOptions op * * @return a {@link Flux} containing one or several feed response pages of read databases or an error. */ - public Flux> listDatabases() { - return listDatabases(new FeedOptions()); + public Flux> readAllDatabases() { + return readAllDatabases(new FeedOptions()); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java index 5e0dd66e4ed25..f077c6570096f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java @@ -58,17 +58,15 @@ public class CosmosClientBuilder { } /** - * Configs - * @param configs - * @return current builder + * Gets the token resolver + * @return the token resolver */ - public CosmosClientBuilder configs(Configs configs) { - this.configs = configs; - return this; + public TokenResolver tokenResolver() { + return tokenResolver; } /** - * Token Resolver + * Sets the token resolver * @param tokenResolver * @return current builder */ @@ -78,29 +76,76 @@ public CosmosClientBuilder tokenResolver(TokenResolver tokenResolver) { } /** - * The service endpoint url - * @param serviceEndpoint the service endpoint + * Gets the Azure Cosmos DB endpoint the SDK will connect to + * @return the endpoint + */ + public String endpoint() { + return serviceEndpoint; + } + + /** + * Sets the Azure Cosmos DB endpoint the SDK will connect to + * @param endpoint the service endpoint * @return current Builder */ - public CosmosClientBuilder endpoint(String serviceEndpoint) { - this.serviceEndpoint = serviceEndpoint; + public CosmosClientBuilder endpoint(String endpoint) { + this.serviceEndpoint = endpoint; return this; } /** - * This method will take either key or resource token and perform authentication + * Gets either a master or readonly key used to perform authentication + * for accessing resource. + * @return the key + */ + public String key() { + return keyOrResourceToken; + } + + /** + * Sets either a master or readonly key used to perform authentication * for accessing resource. * - * @param keyOrResourceToken key or resourceToken for authentication . + * @param key master or readonly key * @return current Builder. */ - public CosmosClientBuilder key(String keyOrResourceToken) { - this.keyOrResourceToken = keyOrResourceToken; + public CosmosClientBuilder key(String key) { + this.keyOrResourceToken = key; return this; } /** - * This method will accept the permission list , which contains the + * Sets a resource token used to perform authentication + * for accessing resource. + * @return the resourceToken + */ + public String resourceToken() { + return keyOrResourceToken; + } + + /** + * Sets a resource token used to perform authentication + * for accessing resource. + * + * @param resourceToken resourceToken for authentication + * @return current Builder. + */ + public CosmosClientBuilder resourceToken(String resourceToken) { + this.keyOrResourceToken = resourceToken; + return this; + } + + /** + * Gets the permission list, which contains the + * resource tokens needed to access resources. + * @return the permission list + */ + public List permissions() { + return permissions; + } + + /** + * Sets the permission list, which contains the * resource tokens needed to access resources. * * @param permissions Permission list for authentication. @@ -112,7 +157,15 @@ public CosmosClientBuilder permissions(List permissions) { } /** - * This method accepts the (@link ConsistencyLevel) to be used + * Gets the (@link ConsistencyLevel) to be used + * @return the consistency level + */ + public ConsistencyLevel consistencyLevel() { + return this.desiredConsistencyLevel; + } + + /** + * Sets the (@link ConsistencyLevel) to be used * @param desiredConsistencyLevel {@link ConsistencyLevel} * @return current Builder */ @@ -122,7 +175,15 @@ public CosmosClientBuilder consistencyLevel(ConsistencyLevel desiredConsistencyL } /** - * The (@link ConnectionPolicy) to be used + * Gets the (@link ConnectionPolicy) to be used + * @return the connection policy + */ + public ConnectionPolicy connectionPolicy() { + return connectionPolicy; + } + + /** + * Sets the (@link ConnectionPolicy) to be used * @param connectionPolicy {@link ConnectionPolicy} * @return current Builder */ @@ -131,14 +192,8 @@ public CosmosClientBuilder connectionPolicy(ConnectionPolicy connectionPolicy) { return this; } - private void ifThrowIllegalArgException(boolean value, String error) { - if (value) { - throw new IllegalArgumentException(error); - } - } - /** - * Builds a cosmos configuration object with the provided settings + * Builds a cosmos configuration object with the provided properties * @return CosmosClient */ public CosmosClient build() { @@ -151,31 +206,23 @@ public CosmosClient build() { return new CosmosClient(this); } - String getServiceEndpoint() { - return serviceEndpoint; - } - - String getKeyOrResourceToken() { - return keyOrResourceToken; - } - - public ConnectionPolicy getConnectionPolicy() { - return connectionPolicy; - } - - public ConsistencyLevel getDesiredConsistencyLevel() { - return desiredConsistencyLevel; - } - - List getPermissions() { - return permissions; + Configs configs() { + return configs; } - public Configs getConfigs() { - return configs; + /** + * Configs + * @param configs + * @return current builder + */ + CosmosClientBuilder configs(Configs configs) { + this.configs = configs; + return this; } - public TokenResolver getTokenResolver() { - return tokenResolver; + private void ifThrowIllegalArgException(boolean value, String error) { + if (value) { + throw new IllegalArgumentException(error); + } } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java index 7983bc5b460a8..4b4b6adbf9755 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java @@ -95,7 +95,7 @@ public Mono read(CosmosConflictRequestOptions options) { * failure the {@link Mono} will error. * * @param options the feed options. - * @return an {@link Mono} containing one or several feed response pages of the + * @return a {@link Mono} containing one or several feed response pages of the * read conflicts or an error. */ public Mono delete(CosmosConflictRequestOptions options) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java index c5c6c82d4f4d0..8c33bd1ab47f8 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Conflict; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.Strings; @@ -61,7 +62,7 @@ public String operationKind() { * * @return the resource type. */ - public String resouceType() { + public String resourceType() { return super.getString(Constants.Properties.RESOURCE_TYPE); } @@ -69,7 +70,7 @@ public String resouceType() { * Gets the resource ID for the conflict in the Azure Cosmos DB service. * @return resource Id for the conflict. */ - public String sourceResourceId() { + String sourceResourceId() { return super.getString(Constants.Properties.SOURCE_RESOURCE_ID); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java index 2019544904b20..3271fccd84e7e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java @@ -24,10 +24,32 @@ import com.azure.data.cosmos.internal.RequestOptions; -public class CosmosConflictRequestOptions extends CosmosRequestOptions{ +public class CosmosConflictRequestOptions { + private AccessCondition accessCondition; - @Override - protected RequestOptions toRequestOptions() { - return super.toRequestOptions(); + /** + * Gets the conditions associated with the request. + * + * @return the access condition. + */ + public AccessCondition accessCondition() { + return accessCondition; + } + + /** + * Sets the conditions associated with the request. + * + * @param accessCondition the access condition. + * @return the current request options + */ + public CosmosConflictRequestOptions accessCondition(AccessCondition accessCondition) { + this.accessCondition = accessCondition; + return this; + } + + RequestOptions toRequestOptions() { + RequestOptions requestOptions = new RequestOptions(); + requestOptions.setAccessCondition(accessCondition); + return requestOptions; } } \ No newline at end of file diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java index 0cd4c14257954..6ece0c92f4a85 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Conflict; import com.azure.data.cosmos.internal.ResourceResponse; public class CosmosConflictResponse extends CosmosResponse { @@ -30,6 +31,7 @@ public class CosmosConflictResponse extends CosmosResponse response, CosmosContainer container) { super(response); + this.container = container; if(response.getResource() == null){ super.resourceSettings(null); }else{ @@ -46,7 +48,7 @@ CosmosContainer getContainer() { * Get conflict client * @return the cosmos conflict client */ - public CosmosConflict getConflict() { + public CosmosConflict conflict() { return conflictClient; } @@ -54,7 +56,7 @@ public CosmosConflict getConflict() { * Get conflict properties object representing the resource on the server * @return the conflict properties */ - public CosmosConflictProperties getConflictProperties() { + public CosmosConflictProperties properties() { return resourceSettings(); } } \ No newline at end of file diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java index 13a61147e7407..c2a55589f499e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java @@ -31,6 +31,10 @@ import static com.azure.data.cosmos.Resource.validateResource; +/** + * Provides methods for reading, deleting, and replacing existing Containers. + * Provides methods for interacting with child resources (Items, Scripts, Conflicts) + */ public class CosmosContainer { private CosmosDatabase database; @@ -62,42 +66,6 @@ CosmosContainer id(String id) { return this; } - AsyncDocumentClient getContextClient() { - if (this.database == null || this.database.getClient() == null) { - return null; - } - - return this.database.getClient().getContextClient(); - } - - /** - * Gets the context client. - * - * @param cosmosContainer the container client. - * @return the context client. - */ - static AsyncDocumentClient getContextClient(CosmosContainer cosmosContainer) { - if (cosmosContainer == null) { - return null; - } - - return cosmosContainer.getContextClient(); - } - - /** - * Gets the self link to the container. - * - * @param cosmosContainer the container client. - * @return the self link. - */ - public static String getSelfLink(CosmosContainer cosmosContainer) { - if (cosmosContainer == null) { - return null; - } - - return cosmosContainer.getLink(); - } - /** * Reads the document container * @@ -172,7 +140,23 @@ public Mono delete() { * the replaced document container. In case of failure the {@link Mono} will * error. * - * @param containerSettings the item container settings + * @param containerSettings the item container properties + * @return an {@link Mono} containing the single cosmos container response with + * the replaced document container or an error. + */ + public Mono replace(CosmosContainerProperties containerSettings) { + return replace(containerSettings, null); + } + + /** + * Replaces a document container. + * + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a single cosmos container response with + * the replaced document container. In case of failure the {@link Mono} will + * error. + * + * @param containerSettings the item container properties * @param options the cosmos container request options. * @return an {@link Mono} containing the single cosmos container response with * the replaced document container or an error. @@ -205,23 +189,6 @@ public Mono createItem(Object item) { return createItem(item, new CosmosItemRequestOptions()); } - /** - * Creates a cosmos item. - * - * After subscription the operation will be performed. The {@link Mono} upon - * successful completion will contain a single resource response with the - * created cosmos item. In case of failure the {@link Mono} will error. - * - * @param item the cosmos item represented as a POJO or cosmos item - * object. - * @param partitionKey the partition key - * @return an {@link Mono} containing the single resource response with the - * created cosmos item or an error. - */ - public Mono createItem(Object item, Object partitionKey) { - return createItem(item, new CosmosItemRequestOptions(partitionKey)); - } - /** * Creates a cosmos item. * @@ -256,23 +223,7 @@ public Mono createItem(Object item, CosmosItemRequestOptions * upserted document or an error. */ public Mono upsertItem(Object item) { - return upsertItem(item, new CosmosItemRequestOptions()); - } - - /** - * Upserts an item. - * - * After subscription the operation will be performed. The {@link Mono} upon - * successful completion will contain a single resource response with the - * upserted item. In case of failure the {@link Mono} will error. - * - * @param item the item represented as a POJO or Item object to upsert. - * @param partitionKey the partitionKey to be used. - * @return an {@link Mono} containing the single resource response with the - * upserted document or an error. - */ - public Mono upsertItem(Object item, Object partitionKey) { - return upsertItem(item, new CosmosItemRequestOptions(partitionKey)); + return upsertItem(item, null); } /** @@ -308,8 +259,8 @@ public Mono upsertItem(Object item, CosmosItemRequestOptions * @return an {@link Flux} containing one or several feed response pages of the * read cosmos items or an error. */ - public Flux> listItems() { - return listItems(new FeedOptions()); + public Flux> readAllItems() { + return readAllItems(new FeedOptions()); } /** @@ -323,12 +274,27 @@ public Flux> listItems() { * @return an {@link Flux} containing one or several feed response pages of the * read cosmos items or an error. */ - public Flux> listItems(FeedOptions options) { + public Flux> readAllItems(FeedOptions options) { return getDatabase().getDocClientWrapper().readDocuments(getLink(), options).map( response -> BridgeInternal.createFeedResponse(CosmosItemProperties.getFromV2Results(response.results()), response.responseHeaders())); } + /** + * Query for documents in a items in a container + * + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained items. In case of + * failure the {@link Flux} will error. + * + * @param query the query. + * @return an {@link Flux} containing one or several feed response pages of the + * obtained items or an error. + */ + public Flux> queryItems(String query) { + return queryItems(new SqlQuerySpec(query), null); + } + /** * Query for documents in a items in a container * @@ -345,6 +311,21 @@ public Flux> queryItems(String query, FeedOpt return queryItems(new SqlQuerySpec(query), options); } + /** + * Query for documents in a items in a container + * + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained items. In case of + * failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @return an {@link Flux} containing one or several feed response pages of the + * obtained items or an error. + */ + public Flux> queryItems(SqlQuerySpec querySpec) { + return queryItems(querySpec, null); + } + /** * Query for documents in a items in a container * @@ -406,12 +387,23 @@ public CosmosScripts getScripts() { * @return a {@link Flux} containing one or several feed response pages of the * obtained conflicts or an error. */ - public Flux> listConflicts(FeedOptions options) { + public Flux> readAllConflicts(FeedOptions options) { return database.getDocClientWrapper().readConflicts(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( CosmosConflictProperties.getFromV2Results(response.results()), response.responseHeaders())); } + /** + * Queries all the conflicts in the container + * + * @param query the query + * @return a {@link Flux} containing one or several feed response pages of the + * obtained conflicts or an error. + */ + public Flux> queryConflicts(String query) { + return queryConflicts(query, null); + } + /** * Queries all the conflicts in the container * @@ -432,8 +424,8 @@ public Flux> queryConflicts(String query, * @param id id of the cosmos conflict * @return a cosmos conflict */ - public CosmosTrigger getConflict(String id) { - return new CosmosTrigger(id, this); + public CosmosConflict getConflict(String id) { + return new CosmosConflict(id, this); } /** @@ -481,7 +473,7 @@ public Mono replaceProvisionedThroughput(int requestUnitsPerSecond) { /** * Gets the parent Database * - * @return the (@link CosmosDatabase) + * @return the {@link CosmosDatabase} */ public CosmosDatabase getDatabase() { return database; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java index 885885680571e..244bf3422db76 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.internal.ResourceResponse; import java.util.ArrayList; @@ -60,7 +61,7 @@ public CosmosContainerProperties(String id, String partitionKeyPath) { /** * Constructor * @param id id of the container - * @param partitionKeyDefinition the (@link PartitionKeyDefinition) + * @param partitionKeyDefinition the {@link PartitionKeyDefinition} */ public CosmosContainerProperties(String id, PartitionKeyDefinition partitionKeyDefinition) { super.id(id); diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java index df5592b1a459a..c2222cca36b5b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java @@ -27,18 +27,19 @@ /** * Encapsulates options that can be specified for a request issued to cosmos container. */ -public class CosmosContainerRequestOptions extends CosmosRequestOptions { +public class CosmosContainerRequestOptions { private Integer offerThroughput; private boolean populateQuotaInfo; private ConsistencyLevel consistencyLevel; private String sessionToken; + private AccessCondition accessCondition; /** * Gets the throughput in the form of Request Units per second when creating a cosmos container. * * @return the throughput value. */ - public Integer offerThroughput() { + Integer offerThroughput() { return offerThroughput; } @@ -48,7 +49,7 @@ public Integer offerThroughput() { * @param offerThroughput the throughput value. * @return the current request options */ - public CosmosContainerRequestOptions offerThroughput(Integer offerThroughput) { + CosmosContainerRequestOptions offerThroughput(Integer offerThroughput) { this.offerThroughput = offerThroughput; return this; } @@ -117,13 +118,33 @@ public CosmosContainerRequestOptions sessionToken(String sessionToken) { return this; } - @Override - protected RequestOptions toRequestOptions() { - super.toRequestOptions(); - requestOptions.setOfferThroughput(offerThroughput); - requestOptions.setPopulateQuotaInfo(populateQuotaInfo); - requestOptions.setSessionToken(sessionToken); - requestOptions.setConsistencyLevel(consistencyLevel); - return requestOptions; + /** + * Gets the conditions associated with the request. + * + * @return the access condition. + */ + public AccessCondition accessCondition() { + return accessCondition; + } + + /** + * Sets the conditions associated with the request. + * + * @param accessCondition the access condition. + * @return the current request options + */ + public CosmosContainerRequestOptions accessCondition(AccessCondition accessCondition) { + this.accessCondition = accessCondition; + return this; + } + + RequestOptions toRequestOptions() { + RequestOptions options = new RequestOptions(); + options.setAccessCondition(accessCondition); + options.setOfferThroughput(offerThroughput); + options.setPopulateQuotaInfo(populateQuotaInfo); + options.setSessionToken(sessionToken); + options.setConsistencyLevel(consistencyLevel); + return options; } } \ No newline at end of file diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java index 8fc7813121d93..50c82ee30f3f2 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.internal.ResourceResponse; public class CosmosContainerResponse extends CosmosResponse { @@ -52,7 +53,7 @@ public long indexTransformationProgress() { * * @return the progress of lazy indexing. */ - public long lazyIndexingProgress() { + long lazyIndexingProgress() { return resourceResponseWrapper.getLazyIndexingProgress(); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java index b51bf62ec4adf..b37885710fefd 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java @@ -22,10 +22,10 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.Offer; import com.azure.data.cosmos.internal.Paths; -import com.azure.data.cosmos.internal.RequestOptions; import org.apache.commons.lang3.StringUtils; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -104,7 +104,7 @@ public Mono read(CosmosDatabaseRequestOptions options) { * @return an {@link Mono} containing the single cosmos database response */ public Mono delete() { - return delete(new CosmosRequestOptions()); + return delete(new CosmosDatabaseRequestOptions()); } /** @@ -117,7 +117,7 @@ public Mono delete() { * @param options the request options * @return an {@link Mono} containing the single cosmos database response */ - public Mono delete(CosmosRequestOptions options) { + public Mono delete(CosmosDatabaseRequestOptions options) { return getDocClientWrapper().deleteDatabase(getLink(), options.toRequestOptions()) .map(response -> new CosmosDatabaseResponse(response, getClient())).single(); } @@ -131,15 +131,33 @@ public Mono delete(CosmosRequestOptions options) { * successful completion will contain a cosmos container response with the * created collection. In case of failure the {@link Mono} will error. * - * @param containerSettings the container settings. + * @param containerSettings the container properties. * @return an {@link Flux} containing the single cosmos container response with * the created container or an error. */ public Mono createContainer(CosmosContainerProperties containerSettings) { - validateResource(containerSettings); return createContainer(containerSettings, new CosmosContainerRequestOptions()); } + /** + * Creates a document container. + * + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos container response with the + * created collection. In case of failure the {@link Mono} will error. + * + * @param containerSettings the container properties. + * @param throughput the throughput for the container + * @return an {@link Flux} containing the single cosmos container response with + * the created container or an error. + */ + public Mono createContainer(CosmosContainerProperties containerSettings, int throughput) { + validateResource(containerSettings); + CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); + options.offerThroughput(throughput); + return createContainer(containerSettings, options); + } + /** * Creates a document container. * @@ -154,11 +172,32 @@ public Mono createContainer(CosmosContainerProperties c */ public Mono createContainer(CosmosContainerProperties containerSettings, CosmosContainerRequestOptions options) { + validateResource(containerSettings); return getDocClientWrapper() .createCollection(this.getLink(), containerSettings.getV2Collection(), options.toRequestOptions()) .map(response -> new CosmosContainerResponse(response, this)).single(); } + /** + * Creates a document container. + * + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos container response with the + * created collection. In case of failure the {@link Mono} will error. + * + * @param containerSettings the containerSettings. + * @param throughput the throughput for the container + * @param options the cosmos container request options + * @return an {@link Flux} containing the cosmos container response with the + * created container or an error. + */ + public Mono createContainer(CosmosContainerProperties containerSettings, + int throughput, + CosmosContainerRequestOptions options) { + options.offerThroughput(throughput); + return createContainer(containerSettings, options); + } + /** * Creates a document container. * @@ -175,6 +214,25 @@ public Mono createContainer(String id, String partition return createContainer(new CosmosContainerProperties(id, partitionKeyPath)); } + /** + * Creates a document container. + * + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos container response with the + * created collection. In case of failure the {@link Mono} will error. + * + * @param id the cosmos container id + * @param partitionKeyPath the partition key path + * @param throughput the throughput for the container + * @return an {@link Flux} containing the cosmos container response with the + * created container or an error. + */ + public Mono createContainer(String id, String partitionKeyPath, int throughput) { + CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); + options.offerThroughput(throughput); + return createContainer(new CosmosContainerProperties(id, partitionKeyPath), options); + } + /** * Creates a document container if it does not exist on the service. *

@@ -183,13 +241,33 @@ public Mono createContainer(String id, String partition * created or existing collection. In case of failure the {@link Mono} will * error. * - * @param containerSettings the container settings + * @param containerSettings the container properties * @return a {@link Mono} containing the cosmos container response with the * created or existing container or an error. */ public Mono createContainerIfNotExists(CosmosContainerProperties containerSettings) { CosmosContainer container = getContainer(containerSettings.id()); - return createContainerIfNotExistsInternal(containerSettings, container); + return createContainerIfNotExistsInternal(containerSettings, container, null); + } + + /** + * Creates a document container if it does not exist on the service. + *

+ * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos container response with the + * created or existing collection. In case of failure the {@link Mono} will + * error. + * + * @param containerSettings the container properties + * @param throughput the throughput for the container + * @return a {@link Mono} containing the cosmos container response with the + * created or existing container or an error. + */ + public Mono createContainerIfNotExists(CosmosContainerProperties containerSettings, int throughput) { + CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); + options.offerThroughput(throughput); + CosmosContainer container = getContainer(containerSettings.id()); + return createContainerIfNotExistsInternal(containerSettings, container, options); } /** @@ -206,16 +284,36 @@ public Mono createContainerIfNotExists(CosmosContainerP */ public Mono createContainerIfNotExists(String id, String partitionKeyPath) { CosmosContainer container = getContainer(id); - return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container); + return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, null); + } + + /** + * Creates a document container if it does not exist on the service. + * + * After subscription the operation will be performed. The {@link Mono} upon + * successful completion will contain a cosmos container response with the + * created collection. In case of failure the {@link Mono} will error. + * + * @param id the cosmos container id + * @param partitionKeyPath the partition key path + * @param throughput the throughput for the container + * @return an {@link Flux} containing the cosmos container response with the + * created container or an error. + */ + public Mono createContainerIfNotExists(String id, String partitionKeyPath, int throughput) { + CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); + options.offerThroughput(throughput); + CosmosContainer container = getContainer(id); + return createContainerIfNotExistsInternal(new CosmosContainerProperties(id, partitionKeyPath), container, options); } private Mono createContainerIfNotExistsInternal( - CosmosContainerProperties containerSettings, CosmosContainer container) { - return container.read().onErrorResume(exception -> { + CosmosContainerProperties containerSettings, CosmosContainer container, CosmosContainerRequestOptions options) { + return container.read(options).onErrorResume(exception -> { if (exception instanceof CosmosClientException) { CosmosClientException cosmosClientException = (CosmosClientException) exception; if (cosmosClientException.statusCode() == HttpConstants.StatusCodes.NOTFOUND) { - return createContainer(containerSettings); + return createContainer(containerSettings, options); } } return Mono.error(exception); @@ -233,7 +331,7 @@ private Mono createContainerIfNotExistsInternal( * @return a {@link Flux} containing one or several feed response pages of read * containers or an error. */ - public Flux> listContainers(FeedOptions options) { + public Flux> readAllContainers(FeedOptions options) { return getDocClientWrapper().readCollections(getLink(), options) .map(response -> BridgeInternal.createFeedResponse( CosmosContainerProperties.getFromV2Results(response.results()), response.responseHeaders())); @@ -249,8 +347,23 @@ public Flux> listContainers(FeedOptions * @return a {@link Flux} containing one or several feed response pages of read * containers or an error. */ - public Flux> listContainers() { - return listContainers(new FeedOptions()); + public Flux> readAllContainers() { + return readAllContainers(new FeedOptions()); + } + + /** + * Query for cosmos containers in a cosmos database. + * + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained containers. In case of + * failure the {@link Flux} will error. + * + * @param query the query + * @return a {@link Flux} containing one or several feed response pages of the + * obtained containers or an error. + */ + public Flux> queryContainers(String query) { + return queryContainers(new SqlQuerySpec(query)); } /** @@ -262,13 +375,28 @@ public Flux> listContainers() { * * @param query the query. * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the + * @return a {@link Flux} containing one or several feed response pages of the * obtained containers or an error. */ public Flux> queryContainers(String query, FeedOptions options) { return queryContainers(new SqlQuerySpec(query), options); } + /** + * Query for cosmos containers in a cosmos database. + * + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained containers. In case of + * failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @return a {@link Flux} containing one or several feed response pages of the + * obtained containers or an error. + */ + public Flux> queryContainers(SqlQuerySpec querySpec) { + return queryContainers(querySpec, null); + } + /** * Query for cosmos containers in a cosmos database. * @@ -278,7 +406,7 @@ public Flux> queryContainers(String quer * * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the + * @return a {@link Flux} containing one or several feed response pages of the * obtained containers or an error. */ public Flux> queryContainers(SqlQuerySpec querySpec, FeedOptions options) { @@ -299,35 +427,22 @@ public CosmosContainer getContainer(String id) { /** User operations **/ - /** - * Creates a user - * After subscription the operation will be performed. - * The {@link Mono} upon successful completion will contain a single resource response with the created user. - * In case of failure the {@link Mono} will error. - * - * @param settings the cosmos user settings - * @return an {@link Mono} containing the single resource response with the created cosmos user or an error. - */ - public Mono createUser(CosmosUserProperties settings) { - return this.createUser(settings, null); - } - /** * Creates a user After subscription the operation will be performed. The * {@link Mono} upon successful completion will contain a single resource * response with the created user. In case of failure the {@link Mono} will * error. * - * @param settings the cosmos user settings - * @param options the request options + * @param settings the cosmos user properties * @return an {@link Mono} containing the single resource response with the * created cosmos user or an error. */ - public Mono createUser(CosmosUserProperties settings, RequestOptions options) { - return getDocClientWrapper().createUser(this.getLink(), settings.getV2User(), options) + public Mono createUser(CosmosUserProperties settings) { + return getDocClientWrapper().createUser(this.getLink(), settings.getV2User(), null) .map(response -> new CosmosUserResponse(response, this)).single(); } + /** * Upsert a user. Upsert will create a new user if it doesn't exist, or replace * the existing one if it does. After subscription the operation will be @@ -335,33 +450,27 @@ public Mono createUser(CosmosUserProperties settings, Reques * resource response with the created user. In case of failure the {@link Mono} * will error. * - * @param settings the cosmos user settings + * @param settings the cosmos user properties * @return an {@link Mono} containing the single resource response with the * upserted user or an error. */ public Mono upsertUser(CosmosUserProperties settings) { - return this.upsertUser(settings, null); + return getDocClientWrapper().upsertUser(this.getLink(), settings.getV2User(), null) + .map(response -> new CosmosUserResponse(response, this)).single(); } /** - * Upsert a user. Upsert will create a new user if it doesn't exist, or replace - * the existing one if it does. After subscription the operation will be - * performed. The {@link Mono} upon successful completion will contain a single - * resource response with the created user. In case of failure the {@link Mono} - * will error. + * Reads all cosmos users in a database. * - * @param settings the cosmos user settings - * @param options the request options - * @return an {@link Mono} containing the single resource response with the - * upserted user or an error. + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the read cosmos users. In case of + * failure the {@link Flux} will error. + * + * @return an {@link Flux} containing one or several feed response pages of the + * read cosmos users or an error. */ - public Mono upsertUser(CosmosUserProperties settings, RequestOptions options) { - return getDocClientWrapper().upsertUser(this.getLink(), settings.getV2User(), options) - .map(response -> new CosmosUserResponse(response, this)).single(); - } - - public Flux> listUsers() { - return listUsers(new FeedOptions()); + public Flux> readAllUsers() { + return readAllUsers(new FeedOptions()); } /** @@ -375,15 +484,57 @@ public Flux> listUsers() { * @return an {@link Flux} containing one or several feed response pages of the * read cosmos users or an error. */ - public Flux> listUsers(FeedOptions options) { + public Flux> readAllUsers(FeedOptions options) { return getDocClientWrapper().readUsers(getLink(), options).map(response -> BridgeInternal.createFeedResponse( CosmosUserProperties.getFromV2Results(response.results()), response.responseHeaders())); } + /** + * Query for cosmos users in a database. + * + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained users. In case of + * failure the {@link Flux} will error. + * + * @param query query as string + * @return a {@link Flux} containing one or several feed response pages of the + * obtained users or an error. + */ + public Flux> queryUsers(String query) { + return queryUsers(query, null); + } + + /** + * Query for cosmos users in a database. + * + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained users. In case of + * failure the {@link Flux} will error. + * + * @param query query as string + * @param options the feed options + * @return a {@link Flux} containing one or several feed response pages of the + * obtained users or an error. + */ public Flux> queryUsers(String query, FeedOptions options) { return queryUsers(new SqlQuerySpec(query), options); } + /** + * Query for cosmos users in a database. + * + * After subscription the operation will be performed. The {@link Flux} will + * contain one or several feed response of the obtained users. In case of + * failure the {@link Flux} will error. + * + * @param querySpec the SQL query specification. + * @return a {@link Flux} containing one or several feed response pages of the + * obtained users or an error. + */ + public Flux> queryUsers(SqlQuerySpec querySpec) { + return queryUsers(querySpec, null); + } + /** * Query for cosmos users in a database. * @@ -393,7 +544,7 @@ public Flux> queryUsers(String query, FeedOpt * * @param querySpec the SQL query specification. * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the + * @return a {@link Flux} containing one or several feed response pages of the * obtained users or an error. */ public Flux> queryUsers(SqlQuerySpec querySpec, FeedOptions options) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java index e6043e96d604a..8153fb579bb7d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.internal.ResourceResponse; import java.util.List; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java index e87fb7e685809..ca1b8cc0ecd77 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java @@ -27,15 +27,36 @@ /** * Encapsulates options that can be specified for a request issued to cosmos database. */ -public class CosmosDatabaseRequestOptions extends CosmosRequestOptions{ +public class CosmosDatabaseRequestOptions{ private Integer offerThroughput; + private AccessCondition accessCondition; + + /** + * Gets the conditions associated with the request. + * + * @return the access condition. + */ + public AccessCondition accessCondition() { + return accessCondition; + } + + /** + * Sets the conditions associated with the request. + * + * @param accessCondition the access condition. + * @return the current request options + */ + public CosmosDatabaseRequestOptions accessCondition(AccessCondition accessCondition) { + this.accessCondition = accessCondition; + return this; + } /** * Gets the throughput in the form of Request Units per second when creating a cosmos database. * * @return the throughput value. */ - public Integer offerThroughput() { + Integer offerThroughput() { return offerThroughput; } @@ -45,15 +66,15 @@ public Integer offerThroughput() { * @param offerThroughput the throughput value. * @return the current request options */ - public CosmosDatabaseRequestOptions offerThroughput(Integer offerThroughput) { + CosmosDatabaseRequestOptions offerThroughput(Integer offerThroughput) { this.offerThroughput = offerThroughput; return this; } - @Override - protected RequestOptions toRequestOptions() { - super.toRequestOptions(); - requestOptions.setOfferThroughput(offerThroughput); - return requestOptions; + RequestOptions toRequestOptions() { + RequestOptions options = new RequestOptions(); + options.setAccessCondition(accessCondition); + options.setOfferThroughput(offerThroughput); + return options; } } \ No newline at end of file diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java index 4b75ef23d180b..b1b2240c289fe 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.internal.ResourceResponse; public class CosmosDatabaseResponse extends CosmosResponse{ diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java deleted file mode 100644 index 23c164d4e9fff..0000000000000 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosFeedResponse.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.azure.data.cosmos; - -import java.lang.reflect.InvocationTargetException; -import java.util.List; -import java.util.stream.Collectors; - -public class CosmosFeedResponse { - private List results; - - //Temporary code. Used for testing conversion(one old resource type to new in feed) - CosmosFeedResponse(FeedResponse feedResponse, Class klass) { - results = feedResponse.results().stream().map(resource -> { - T item = null; - try { - item = klass.getConstructor(Resource.class).newInstance(resource); - } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { - throw new IllegalStateException(e); - } - return item; - }).collect(Collectors.toList()); - } - - - List getResults() { - return results; - } -} diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java index 296bcada6e4c9..74eeaa27a576c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.internal.Paths; import com.azure.data.cosmos.internal.RequestOptions; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java index a4741d3c9e54b..c610554cf3b58 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.internal.Utils; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java index 0c20bddcf5adb..9d2363e0aae16 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java @@ -29,13 +29,14 @@ /** * Encapsulates options that can be specified for a request issued to cosmos Item. */ -public class CosmosItemRequestOptions extends CosmosRequestOptions { +public class CosmosItemRequestOptions { private ConsistencyLevel consistencyLevel; private IndexingDirective indexingDirective; private List preTriggerInclude; private List postTriggerInclude; private String sessionToken; private PartitionKey partitionKey; + private AccessCondition accessCondition; /** * Constructor @@ -56,7 +57,27 @@ public CosmosItemRequestOptions(Object partitionKey){ partitionKey(new PartitionKey(partitionKey)); } } - + + /** + * Gets the conditions associated with the request. + * + * @return the access condition. + */ + public AccessCondition accessCondition() { + return accessCondition; + } + + /** + * Sets the conditions associated with the request. + * + * @param accessCondition the access condition. + * @return the current request options + */ + public CosmosItemRequestOptions accessCondition(AccessCondition accessCondition) { + this.accessCondition = accessCondition; + return this; + } + /** * Gets the consistency level required for the request. * @@ -175,10 +196,10 @@ public PartitionKey partitionKey() { return partitionKey; } - @Override - protected RequestOptions toRequestOptions() { + RequestOptions toRequestOptions() { //TODO: Should we set any default values instead of nulls? - super.toRequestOptions(); + RequestOptions requestOptions = new RequestOptions(); + requestOptions.setAccessCondition(accessCondition); requestOptions.setAccessCondition(accessCondition()); requestOptions.setConsistencyLevel(consistencyLevel()); requestOptions.setIndexingDirective(indexingDirective); diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java index d98cca0b42bd9..f25d0d2361789 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java @@ -22,6 +22,7 @@ */ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.internal.ResourceResponse; public class CosmosItemResponse extends CosmosResponse{ diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java index f30ef3596389d..590c95cc23b5d 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java @@ -80,7 +80,7 @@ public Mono read(RequestOptions options) { * The {@link Mono} upon successful completion will contain a single resource response with the replaced permission. * In case of failure the {@link Mono} will error. * - * @param permissionSettings the permission settings to use. + * @param permissionSettings the permission properties to use. * @param options the request options. * @return an {@link Mono} containing the single resource response with the replaced permission or an error. */ @@ -103,9 +103,9 @@ public Mono replace(CosmosPermissionProperties permiss * @param options the request options. * @return an {@link Mono} containing the single resource response for the deleted permission or an error. */ - public Mono delete(CosmosPermissionsRequestOptions options) { + public Mono delete(CosmosPermissionRequestOptions options) { if(options == null){ - options = new CosmosPermissionsRequestOptions(); + options = new CosmosPermissionRequestOptions(); } return cosmosUser.getDatabase() .getDocClientWrapper() diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java index 88aa2534af423..dce8f70a96799 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java @@ -46,7 +46,7 @@ public CosmosPermissionProperties() { * Sets the id * * @param id the name of the resource. - * @return the cosmos permission properties with id set + * @return the current {@link CosmosPermissionProperties} object */ public CosmosPermissionProperties id(String id) { super.id(id); @@ -75,6 +75,7 @@ public String resourceLink() { * Sets the self-link of resource to which the permission applies. * * @param resourceLink the resource link. + * @return the current {@link CosmosPermissionProperties} object */ public CosmosPermissionProperties resourceLink(String resourceLink) { super.set(Constants.Properties.RESOURCE_LINK, resourceLink); @@ -95,6 +96,7 @@ public PermissionMode permissionMode() { * Sets the permission mode. * * @param permissionMode the permission mode. + * @return the current {@link CosmosPermissionProperties} object */ public CosmosPermissionProperties permissionMode(PermissionMode permissionMode) { this.set(Constants.Properties.PERMISSION_MODE, @@ -123,6 +125,7 @@ public CosmosPermissionProperties permissionMode(PermissionMode permissionMode) * Sets the resource partition key associated with this permission object. * * @param partitionKey the partition key. + * @return the current {@link CosmosPermissionProperties} object */ public CosmosPermissionProperties resourcePartitionKey(PartitionKey partitionKey) { super.set(Constants.Properties.RESOURCE_PARTITION_KEY, partitionKey.getInternalPartitionKey().toJson()); diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionRequestOptions.java similarity index 81% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java rename to sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionRequestOptions.java index 7a12fa4374f2e..d3cb39f886523 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosRequestOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionRequestOptions.java @@ -25,10 +25,10 @@ import com.azure.data.cosmos.internal.RequestOptions; /** - * Encapsulates options that can be specified for a request + * Contains the request options of CosmosPermission */ -public class CosmosRequestOptions { - protected RequestOptions requestOptions = new RequestOptions(); +public class CosmosPermissionRequestOptions { + //TODO: Need to add respective options private AccessCondition accessCondition; /** @@ -46,13 +46,15 @@ public AccessCondition accessCondition() { * @param accessCondition the access condition. * @return the current request options */ - public CosmosRequestOptions accessCondition(AccessCondition accessCondition) { + public CosmosPermissionRequestOptions accessCondition(AccessCondition accessCondition) { this.accessCondition = accessCondition; return this; } - protected RequestOptions toRequestOptions(){ + RequestOptions toRequestOptions() { + //TODO: Should we set any default values instead of nulls? + RequestOptions requestOptions = new RequestOptions(); requestOptions.setAccessCondition(accessCondition); return requestOptions; } -} \ No newline at end of file +} diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionsRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionsRequestOptions.java deleted file mode 100644 index 96cd59f47e32c..0000000000000 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionsRequestOptions.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ -package com.azure.data.cosmos; - -import com.azure.data.cosmos.internal.RequestOptions; - -/** - * Contains the request options of CosmosPermission - */ -public class CosmosPermissionsRequestOptions extends CosmosRequestOptions { - //TODO: Need to add respective options - - - @Override - protected RequestOptions toRequestOptions() { - //TODO: Should we set any default values instead of nulls? - super.toRequestOptions(); - return requestOptions; - } -} diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java index 716603437307d..fe227d5bd771b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java @@ -30,7 +30,7 @@ public class CosmosResponse { private T resourceSettings; - protected ResourceResponse resourceResponseWrapper; + ResourceResponse resourceResponseWrapper; CosmosResponse(ResourceResponse resourceResponse){ this.resourceResponseWrapper = resourceResponse; @@ -44,11 +44,11 @@ public class CosmosResponse { CosmosResponse(StoredProcedureResponse response) { } - protected T resourceSettings() { + T resourceSettings() { return resourceSettings; } - protected CosmosResponse resourceSettings(T resourceSettings){ + CosmosResponse resourceSettings(T resourceSettings){ this.resourceSettings = resourceSettings; return this; } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java index 54ad53a361874..3891d36e843da 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java @@ -83,14 +83,14 @@ public Mono createStoredProcedure(CosmosStoredPro * Reads all cosmos stored procedures in a container. * * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the read cosmos stored procedure settings. + * The {@link Flux} will contain one or several feed response pages of the read cosmos stored procedure properties. * In case of failure the {@link Flux} will error. * * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the read cosmos stored procedures - * settings or an error. + * properties or an error. */ - public Flux> listStoredProcedures(FeedOptions options){ + public Flux> readAllStoredProcedures(FeedOptions options){ return database.getDocClientWrapper() .readStoredProcedures(container.getLink(), options) .map(response -> BridgeInternal.createFeedResponse(CosmosStoredProcedureProperties.getFromV2Results(response.results()), @@ -154,19 +154,15 @@ public CosmosStoredProcedure getStoredProcedure(String id){ * In case of failure the {@link Mono} will error. * * @param properties the cosmos user defined function properties - * @param options the cosmos request options. * @return an {@link Mono} containing the single resource response with the created user defined function or an error. */ - public Mono createUserDefinedFunction(CosmosUserDefinedFunctionProperties properties, - CosmosRequestOptions options){ + public Mono createUserDefinedFunction(CosmosUserDefinedFunctionProperties properties){ UserDefinedFunction udf = new UserDefinedFunction(); udf.id(properties.id()); udf.setBody(properties.body()); - if(options == null){ - options = new CosmosRequestOptions(); - } + return database.getDocClientWrapper() - .createUserDefinedFunction(container.getLink(), udf, options.toRequestOptions()) + .createUserDefinedFunction(container.getLink(), udf, null) .map(response -> new CosmosUserDefinedFunctionResponse(response, this.container)).single(); } @@ -180,7 +176,7 @@ public Mono createUserDefinedFunction(CosmosU * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the read user defined functions or an error. */ - public Flux> listUserDefinedFunctions(FeedOptions options){ + public Flux> readAllUserDefinedFunctions(FeedOptions options){ return database.getDocClientWrapper() .readUserDefinedFunctions(container.getLink(), options) .map(response -> BridgeInternal.createFeedResponse(CosmosUserDefinedFunctionProperties.getFromV2Results(response.results()), @@ -240,17 +236,13 @@ public CosmosUserDefinedFunction getUserDefinedFunction(String id){ * In case of failure the {@link Mono} will error. * * @param properties the cosmos trigger properties - * @param options the request options. * @return an {@link Mono} containing the single resource response with the created trigger or an error. */ - public Mono createTrigger(CosmosTriggerProperties properties, - CosmosRequestOptions options){ + public Mono createTrigger(CosmosTriggerProperties properties){ Trigger trigger = new Trigger(properties.toJson()); - if(options == null){ - options = new CosmosRequestOptions(); - } + return database.getDocClientWrapper() - .createTrigger(container.getLink(), trigger,options.toRequestOptions()) + .createTrigger(container.getLink(), trigger, null) .map(response -> new CosmosTriggerResponse(response, this.container)) .single(); } @@ -259,13 +251,13 @@ public Mono createTrigger(CosmosTriggerProperties propert * Reads all triggers in a container * * After subscription the operation will be performed. - * The {@link Flux} will contain one or several feed response pages of the read cosmos trigger settings. + * The {@link Flux} will contain one or several feed response pages of the read cosmos trigger properties. * In case of failure the {@link Flux} will error. * * @param options the feed options. - * @return an {@link Flux} containing one or several feed response pages of the read cosmos rigger settings or an error. + * @return an {@link Flux} containing one or several feed response pages of the read cosmos rigger properties or an error. */ - public Flux> listTriggers(FeedOptions options){ + public Flux> readAllTriggers(FeedOptions options){ return database.getDocClientWrapper() .readTriggers(container.getLink(), options) .map(response -> BridgeInternal.createFeedResponse(CosmosTriggerProperties.getFromV2Results(response.results()), diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java index 7e22c9504598a..14a11f121eb32 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; -import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.StoredProcedure; import reactor.core.publisher.Mono; @@ -56,7 +55,21 @@ CosmosStoredProcedure id(String id) { } /** - * READ a stored procedure by the stored procedure link. + * Read a stored procedure by the stored procedure link. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the read stored + * procedure. + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the single resource response with the read stored procedure or an error. + */ + public Mono read() { + return read(null); + } + + /** + * Read a stored procedure by the stored procedure link. *

* After subscription the operation will be performed. * The {@link Mono} upon successful completion will contain a single resource response with the read stored @@ -66,11 +79,27 @@ CosmosStoredProcedure id(String id) { * @param options the request options. * @return an {@link Mono} containing the single resource response with the read stored procedure or an error. */ - public Mono read(RequestOptions options) { - return cosmosContainer.getDatabase().getDocClientWrapper().readStoredProcedure(getLink(), options) + public Mono read(CosmosStoredProcedureRequestOptions options) { + if(options == null) { + options = new CosmosStoredProcedureRequestOptions(); + } + return cosmosContainer.getDatabase().getDocClientWrapper().readStoredProcedure(getLink(), options.toRequestOptions()) .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)).single(); } + /** + * Deletes a stored procedure by the stored procedure link. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response for the deleted stored procedure. + * In case of failure the {@link Mono} will error. + * + * @return an {@link Mono} containing the single resource response for the deleted stored procedure or an error. + */ + public Mono delete() { + return delete(null); + } + /** * Deletes a stored procedure by the stored procedure link. *

@@ -81,7 +110,10 @@ public Mono read(RequestOptions options) { * @param options the request options. * @return an {@link Mono} containing the single resource response for the deleted stored procedure or an error. */ - public Mono delete(CosmosRequestOptions options) { + public Mono delete(CosmosStoredProcedureRequestOptions options) { + if(options == null) { + options = new CosmosStoredProcedureRequestOptions(); + } return cosmosContainer.getDatabase() .getDocClientWrapper() .deleteStoredProcedure(getLink(), options.toRequestOptions()) @@ -100,10 +132,13 @@ public Mono delete(CosmosRequestOptions options) { * @param options the request options. * @return an {@link Mono} containing the single resource response with the stored procedure response or an error. */ - public Mono execute(Object[] procedureParams, RequestOptions options) { + public Mono execute(Object[] procedureParams, CosmosStoredProcedureRequestOptions options) { + if(options == null) { + options = new CosmosStoredProcedureRequestOptions(); + } return cosmosContainer.getDatabase() .getDocClientWrapper() - .executeStoredProcedure(getLink(), options, procedureParams) + .executeStoredProcedure(getLink(), options.toRequestOptions(), procedureParams) .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)) .single(); } @@ -115,15 +150,32 @@ public Mono execute(Object[] procedureParams, Req * The {@link Mono} upon successful completion will contain a single resource response with the replaced stored procedure. * In case of failure the {@link Mono} will error. * - * @param storedProcedureSettings the stored procedure settings. + * @param storedProcedureSettings the stored procedure properties + * @return an {@link Mono} containing the single resource response with the replaced stored procedure or an error. + */ + public Mono replace(CosmosStoredProcedureProperties storedProcedureSettings) { + return replace(storedProcedureSettings, null); + } + + /** + * Replaces a stored procedure. + *

+ * After subscription the operation will be performed. + * The {@link Mono} upon successful completion will contain a single resource response with the replaced stored procedure. + * In case of failure the {@link Mono} will error. + * + * @param storedProcedureSettings the stored procedure properties. * @param options the request options. * @return an {@link Mono} containing the single resource response with the replaced stored procedure or an error. */ public Mono replace(CosmosStoredProcedureProperties storedProcedureSettings, - RequestOptions options) { + CosmosStoredProcedureRequestOptions options) { + if(options == null) { + options = new CosmosStoredProcedureRequestOptions(); + } return cosmosContainer.getDatabase() .getDocClientWrapper() - .replaceStoredProcedure(new StoredProcedure(storedProcedureSettings.toJson()), options) + .replaceStoredProcedure(new StoredProcedure(storedProcedureSettings.toJson()), options.toRequestOptions()) .map(response -> new CosmosStoredProcedureResponse(response, cosmosContainer)) .single(); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java index fac71c1937f44..8cd9d08689788 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java @@ -27,11 +27,31 @@ /** * Encapsulates options that can be specified for a request issued to cosmos stored procedure. */ -public class CosmosStoredProcedureRequestOptions extends CosmosRequestOptions { +public class CosmosStoredProcedureRequestOptions { private ConsistencyLevel consistencyLevel; private PartitionKey partitionKey; private String sessionToken; + private AccessCondition accessCondition; + /** + * Gets the conditions associated with the request. + * + * @return the access condition. + */ + public AccessCondition accessCondition() { + return accessCondition; + } + + /** + * Sets the conditions associated with the request. + * + * @param accessCondition the access condition. + * @return the current request options + */ + public CosmosStoredProcedureRequestOptions accessCondition(AccessCondition accessCondition) { + this.accessCondition = accessCondition; + return this; + } /** * Gets the consistency level required for the request. * @@ -92,9 +112,9 @@ public CosmosStoredProcedureRequestOptions sessionToken(String sessionToken) { return this; } - @Override - protected RequestOptions toRequestOptions() { - super.toRequestOptions(); + RequestOptions toRequestOptions() { + RequestOptions requestOptions = new RequestOptions(); + requestOptions.setAccessCondition(accessCondition); requestOptions.setConsistencyLevel(consistencyLevel()); requestOptions.setPartitionKey(partitionKey); requestOptions.setSessionToken(sessionToken); diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java index 93aebc0f0bf56..e0ff10e1b286f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; -import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.Trigger; import reactor.core.publisher.Mono; @@ -62,13 +61,12 @@ CosmosTrigger id(String id) { * The {@link Mono} upon successful completion will contain a single resource response for the read trigger. * In case of failure the {@link Mono} will error. * - * @param options the request options. * @return an {@link Mono} containing the single resource response for the read cosmos trigger or an error. */ - public Mono read(RequestOptions options) { + public Mono read() { return container.getDatabase() .getDocClientWrapper() - .readTrigger(getLink(), options) + .readTrigger(getLink(), null) .map(response -> new CosmosTriggerResponse(response, container)) .single(); } @@ -81,14 +79,13 @@ public Mono read(RequestOptions options) { * The {@link Mono} upon successful completion will contain a single resource response with the replaced trigger. * In case of failure the {@link Mono} will error. * - * @param triggerSettings the cosmos trigger settings. - * @param options the request options. + * @param triggerSettings the cosmos trigger properties. * @return an {@link Mono} containing the single resource response with the replaced cosmos trigger or an error. */ - public Mono replace(CosmosTriggerProperties triggerSettings, RequestOptions options) { + public Mono replace(CosmosTriggerProperties triggerSettings) { return container.getDatabase() .getDocClientWrapper() - .replaceTrigger(new Trigger(triggerSettings.toJson()), options) + .replaceTrigger(new Trigger(triggerSettings.toJson()), null) .map(response -> new CosmosTriggerResponse(response, container)) .single(); } @@ -100,13 +97,12 @@ public Mono replace(CosmosTriggerProperties triggerSettin * The {@link Mono} upon successful completion will contain a single resource response for the deleted trigger. * In case of failure the {@link Mono} will error. * - * @param options the request options. * @return an {@link Mono} containing the single resource response for the deleted cosmos trigger or an error. */ - public Mono delete(CosmosRequestOptions options) { + public Mono delete() { return container.getDatabase() .getDocClientWrapper() - .deleteTrigger(getLink(), options.toRequestOptions()) + .deleteTrigger(getLink(), null) .map(response -> new CosmosResponse(response.getResource())) .single(); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java index a0d8fa4cbd540..e221e9faa7fe8 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java @@ -42,7 +42,7 @@ public CosmosTriggerProperties(){ /** * Constructor. * - * @param jsonString the json string that represents the trigger settings. + * @param jsonString the json string that represents the trigger properties. */ CosmosTriggerProperties(String jsonString){ super(jsonString); @@ -56,7 +56,7 @@ public CosmosTriggerProperties(){ * Sets the id * * @param id the name of the resource. - * @return the current cosmos trigger settings instance + * @return the current cosmos trigger properties instance */ public CosmosTriggerProperties id(String id) { super.id(id); diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java index 507cb41195952..08c61dae6150a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java @@ -2,7 +2,6 @@ import com.azure.data.cosmos.internal.Paths; import com.azure.data.cosmos.internal.Permission; -import com.azure.data.cosmos.internal.RequestOptions; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -35,45 +34,34 @@ CosmosUser id(String id) { /** * Reads a cosmos user - * @return an {@link Mono} containing the single cosmos user response with the read user or an error. - */ - public Mono read() { - return this.read(null); - } - - /** - * Reads a cosmos user - * @param options the request options * @return a {@link Mono} containing the single resource response with the read user or an error. */ - public Mono read(RequestOptions options) { + public Mono read() { return this.database.getDocClientWrapper() - .readUser(getLink(), options) + .readUser(getLink(), null) .map(response -> new CosmosUserResponse(response, database)).single(); } /** * REPLACE a cosmos user * - * @param userSettings the user settings to use - * @param options the request options + * @param userSettings the user properties to use * @return a {@link Mono} containing the single resource response with the replaced user or an error. */ - public Mono replace(CosmosUserProperties userSettings, RequestOptions options) { + public Mono replace(CosmosUserProperties userSettings) { return this.database.getDocClientWrapper() - .replaceUser(userSettings.getV2User(), options) + .replaceUser(userSettings.getV2User(), null) .map(response -> new CosmosUserResponse(response, database)).single(); } /** - * DELETE a cosmos user + * Delete a cosmos user * - * @param options the request options * @return a {@link Mono} containing the single resource response with the deleted user or an error. */ - public Mono delete(RequestOptions options) { + public Mono delete() { return this.database.getDocClientWrapper() - .deleteUser(getLink(), options) + .deleteUser(getLink(), null) .map(response -> new CosmosUserResponse(response, database)).single(); } @@ -84,13 +72,13 @@ public Mono delete(RequestOptions options) { * The {@link Mono} upon successful completion will contain a single resource response with the created permission. * In case of failure the {@link Mono} will error. * - * @param permissionSettings the permission settings to create. + * @param permissionSettings the permission properties to create. * @param options the request options. * @return an {@link Mono} containing the single resource response with the created permission or an error. */ - public Mono createPermission(CosmosPermissionProperties permissionSettings, CosmosPermissionsRequestOptions options) { + public Mono createPermission(CosmosPermissionProperties permissionSettings, CosmosPermissionRequestOptions options) { if(options == null){ - options = new CosmosPermissionsRequestOptions(); + options = new CosmosPermissionRequestOptions(); } Permission permission = permissionSettings.getV2Permissions(); return database.getDocClientWrapper() @@ -106,14 +94,14 @@ public Mono createPermission(CosmosPermissionPropertie * The {@link Mono} upon successful completion will contain a single resource response with the upserted permission. * In case of failure the {@link Mono} will error. * - * @param permissionSettings the permission settings to upsert. + * @param permissionSettings the permission properties to upsert. * @param options the request options. * @return an {@link Mono} containing the single resource response with the upserted permission or an error. */ - public Mono upsertPermission(CosmosPermissionProperties permissionSettings, CosmosPermissionsRequestOptions options) { + public Mono upsertPermission(CosmosPermissionProperties permissionSettings, CosmosPermissionRequestOptions options) { Permission permission = permissionSettings.getV2Permissions(); if(options == null){ - options = new CosmosPermissionsRequestOptions(); + options = new CosmosPermissionRequestOptions(); } return database.getDocClientWrapper() .upsertPermission(getLink(), permission, options.toRequestOptions()) @@ -132,13 +120,27 @@ public Mono upsertPermission(CosmosPermissionPropertie * @param options the feed options. * @return an {@link Flux} containing one or several feed response pages of the read permissions or an error. */ - public Flux> listPermissions(FeedOptions options) { + public Flux> readAllPermissions(FeedOptions options) { return getDatabase().getDocClientWrapper() .readPermissions(getLink(), options) .map(response-> BridgeInternal.createFeedResponse(CosmosPermissionProperties.getFromV2Results(response.results()), response.responseHeaders())); } + /** + * Query for permissions. + *

+ * After subscription the operation will be performed. + * The {@link Flux} will contain one or several feed response pages of the obtained permissions. + * In case of failure the {@link Flux} will error. + * + * @param query the query. + * @return an {@link Flux} containing one or several feed response pages of the obtained permissions or an error. + */ + public Flux> queryPermissions(String query) { + return queryPermissions(query); + } + /** * Query for permissions. *

diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java index ee0524c77eb19..3229de163ca60 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos; import com.azure.data.cosmos.internal.Paths; -import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.internal.UserDefinedFunction; import reactor.core.publisher.Mono; @@ -56,18 +55,17 @@ CosmosUserDefinedFunction id(String id) { } /** - * READ a user defined function. + * Read a user defined function. *

* After subscription the operation will be performed. * The {@link Mono} upon successful completion will contain a single resource response for the read user defined * function. * In case of failure the {@link Mono} will error. * - * @param options the request options. * @return an {@link Mono} containing the single resource response for the read user defined function or an error. */ - public Mono read(RequestOptions options) { - return container.getDatabase().getDocClientWrapper().readUserDefinedFunction(getLink(), options) + public Mono read() { + return container.getDatabase().getDocClientWrapper().readUserDefinedFunction(getLink(), null) .map(response -> new CosmosUserDefinedFunctionResponse(response, container)).single(); } @@ -79,17 +77,15 @@ public Mono read(RequestOptions options) { * defined function. * In case of failure the {@link Mono} will error. * - * @param udfSettings the cosmos user defined function settings. - * @param options the request options. + * @param udfSettings the cosmos user defined function properties. * @return an {@link Mono} containing the single resource response with the replaced cosmos user defined function * or an error. */ - public Mono replace(CosmosUserDefinedFunctionProperties udfSettings, - RequestOptions options) { + public Mono replace(CosmosUserDefinedFunctionProperties udfSettings) { return container.getDatabase() .getDocClientWrapper() .replaceUserDefinedFunction(new UserDefinedFunction(udfSettings.toJson()) - , options) + , null) .map(response -> new CosmosUserDefinedFunctionResponse(response, container)) .single(); } @@ -101,14 +97,13 @@ public Mono replace(CosmosUserDefinedFunction * The {@link Mono} upon successful completion will contain a single resource response for the deleted user defined function. * In case of failure the {@link Mono} will error. * - * @param options the request options. * @return an {@link Mono} containing the single resource response for the deleted cosmos user defined function or * an error. */ - public Mono delete(CosmosRequestOptions options) { + public Mono delete() { return container.getDatabase() .getDocClientWrapper() - .deleteUserDefinedFunction(this.getLink(), options.toRequestOptions()) + .deleteUserDefinedFunction(this.getLink(), null) .map(response -> new CosmosResponse(response.getResource())) .single(); } diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java index 99b1429ce7dc1..0f3fb1d545c9e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java @@ -40,10 +40,10 @@ public class CosmosUserDefinedFunctionResponse extends CosmosResponse c) { if (c.isAnonymousClass() || c.isLocalClass()) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/AsyncDocumentClient.java similarity index 98% rename from sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/AsyncDocumentClient.java index 98a0956d8bbbd..0c0f0d5808a53 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/AsyncDocumentClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/AsyncDocumentClient.java @@ -20,20 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; - -import com.azure.data.cosmos.internal.Configs; -import com.azure.data.cosmos.internal.Offer; -import com.azure.data.cosmos.internal.PartitionKeyRange; -import com.azure.data.cosmos.internal.Permission; -import com.azure.data.cosmos.internal.RequestOptions; -import com.azure.data.cosmos.internal.ResourceResponse; -import com.azure.data.cosmos.internal.RxDocumentClientImpl; -import com.azure.data.cosmos.internal.StoredProcedure; -import com.azure.data.cosmos.internal.StoredProcedureResponse; -import com.azure.data.cosmos.internal.Trigger; -import com.azure.data.cosmos.internal.User; -import com.azure.data.cosmos.internal.UserDefinedFunction; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.ChangeFeedOptions; +import com.azure.data.cosmos.ConnectionPolicy; +import com.azure.data.cosmos.ConsistencyLevel; +import com.azure.data.cosmos.FeedOptions; +import com.azure.data.cosmos.FeedResponse; +import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.TokenResolver; import reactor.core.publisher.Flux; import java.net.URI; @@ -387,7 +382,7 @@ public void setTokenResolver(TokenResolver tokenResolver) { * @return an {@link Flux} containing the single resource response with the created collection or an error. */ Flux> createCollection(String databaseLink, DocumentCollection collection, - RequestOptions options); + RequestOptions options); /** * Replaces a document collection. @@ -483,7 +478,7 @@ Flux> createCollection(String databaseLink, * @return an {@link Flux} containing the single resource response with the created document or an error. */ Flux> createDocument(String collectionLink, Object document, RequestOptions options, - boolean disableAutomaticIdGeneration); + boolean disableAutomaticIdGeneration); /** * Upserts a document. diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java b/sdk/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java index cea418c333536..8fc51eadbe534 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java @@ -24,7 +24,6 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.DatabaseAccount; /** * Used internally to provides functionality to work with database account configuration in the Azure Cosmos DB database service. @@ -39,7 +38,7 @@ public BaseDatabaseAccountConfigurationProvider(DatabaseAccount databaseAccount, } public ConsistencyLevel getStoreConsistencyPolicy() { - ConsistencyLevel databaseAccountConsistency = this.databaseAccount.getConsistencyPolicy().getDefaultConsistencyLevel(); + ConsistencyLevel databaseAccountConsistency = this.databaseAccount.getConsistencyPolicy().defaultConsistencyLevel(); if (this.desiredConsistencyLevel == null) { return databaseAccountConsistency; } else if (!Utils.isValidConsistency(databaseAccountConsistency, this.desiredConsistencyLevel)) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java index 75a992fe1baf6..09b510367b480 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.ISessionContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; diff --git a/sdk/src/main/java/com/azure/data/cosmos/Conflict.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Conflict.java similarity index 96% rename from sdk/src/main/java/com/azure/data/cosmos/Conflict.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Conflict.java index 26de0dc92e861..12133673af9c3 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/Conflict.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/Conflict.java @@ -21,10 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; -import com.azure.data.cosmos.internal.Strings; +import com.azure.data.cosmos.Resource; import java.lang.reflect.InvocationTargetException; diff --git a/sdk/src/main/java/com/azure/data/cosmos/Database.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Database.java similarity index 97% rename from sdk/src/main/java/com/azure/data/cosmos/Database.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Database.java index b5ca302a0b1ba..af8e1df73cb0e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/Database.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/Database.java @@ -21,9 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.Resource; import org.apache.commons.lang3.StringUtils; /** diff --git a/sdk/src/main/java/com/azure/data/cosmos/DatabaseAccount.java b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccount.java similarity index 78% rename from sdk/src/main/java/com/azure/data/cosmos/DatabaseAccount.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccount.java index 74fc5d89f8b45..8f2fd00f6e016 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/DatabaseAccount.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccount.java @@ -21,11 +21,10 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; -import com.azure.data.cosmos.internal.ReplicationPolicy; -import com.azure.data.cosmos.internal.Utils; +import com.azure.data.cosmos.ConsistencyPolicy; +import com.azure.data.cosmos.Resource; import com.fasterxml.jackson.core.type.TypeReference; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; @@ -34,6 +33,10 @@ import java.util.HashMap; import java.util.Map; +import static com.azure.data.cosmos.BridgeInternal.setProperty; +import static com.azure.data.cosmos.BridgeInternal.setResourceSelfLink; +import static com.azure.data.cosmos.BridgeInternal.populatePropertyBagJsonSerializable; + /** * Represents a database account in the Azure Cosmos DB database service. */ @@ -49,8 +52,8 @@ public class DatabaseAccount extends Resource { /** * Constructor. */ - DatabaseAccount() { - this.selfLink(""); + public DatabaseAccount() { + setResourceSelfLink(this, ""); } /** @@ -76,8 +79,8 @@ public String getDatabasesLink() { * * @param databasesLink the databases link. */ - void setDatabasesLink(String databasesLink) { - super.set(Constants.Properties.DATABASES_LINK, databasesLink); + public void setDatabasesLink(String databasesLink) { + setProperty(this, Constants.Properties.DATABASES_LINK, databasesLink); } /** @@ -94,8 +97,8 @@ public String getMediaLink() { * * @param medialink the media link. */ - void setMediaLink(String medialink) { - super.set(Constants.Properties.MEDIA_LINK, medialink); + public void setMediaLink(String medialink) { + setProperty(this, Constants.Properties.MEDIA_LINK, medialink); } /** @@ -112,8 +115,8 @@ public String getAddressesLink() { * * @param addresseslink the addresses link. */ - void setAddressesLink(String addresseslink) { - super.set(Constants.Properties.ADDRESS_LINK, addresseslink); + public void setAddressesLink(String addresseslink) { + setProperty(this, Constants.Properties.ADDRESS_LINK, addresseslink); } /** @@ -125,7 +128,7 @@ public long getMaxMediaStorageUsageInMB() { return this.maxMediaStorageUsageInMB; } - void setMaxMediaStorageUsageInMB(long value) { + public void setMaxMediaStorageUsageInMB(long value) { this.maxMediaStorageUsageInMB = value; } @@ -141,12 +144,12 @@ public long getMediaStorageUsageInMB() { return this.mediaStorageUsageInMB; } - void setMediaStorageUsageInMB(long value) { + public void setMediaStorageUsageInMB(long value) { this.mediaStorageUsageInMB = value; } /** - * Gets the ConsistencyPolicy settings. + * Gets the ConsistencyPolicy properties. * * @return the consistency policy. */ @@ -163,7 +166,7 @@ public ConsistencyPolicy getConsistencyPolicy() { } /** - * Gets the ReplicationPolicy settings. + * Gets the ReplicationPolicy properties. * * @return the replication policy. */ @@ -181,11 +184,11 @@ public ReplicationPolicy getReplicationPolicy() { } /** - * Gets the SystemReplicationPolicy settings. + * Gets the SystemReplicationPolicy properties. * * @return the system replication policy. */ - ReplicationPolicy getSystemReplicationPolicy() { + public ReplicationPolicy getSystemReplicationPolicy() { if (this.systemReplicationPolicy == null) { this.systemReplicationPolicy = super.getObject(Constants.Properties.SYSTEM_REPLICATION_POLICY, ReplicationPolicy.class); @@ -199,11 +202,11 @@ ReplicationPolicy getSystemReplicationPolicy() { } /** - * Gets the QueryEngineConfiuration settings. + * Gets the QueryEngineConfiuration properties. * * @return the query engine configuration. */ - Map getQueryEngineConfiuration() { + public Map getQueryEngineConfiuration() { if (this.queryEngineConfiguration == null) { String queryEngineConfigurationJsonString = super.getObject(Constants.Properties.QUERY_ENGINE_CONFIGURATION, String.class); @@ -241,8 +244,8 @@ public Iterable getWritableLocations() { * * @param locations the list of writable locations. */ - void setWritableLocations(Iterable locations) { - super.set(Constants.Properties.WRITABLE_LOCATIONS, locations); + public void setWritableLocations(Iterable locations) { + setProperty(this, Constants.Properties.WRITABLE_LOCATIONS, locations); } /** @@ -261,23 +264,28 @@ public Iterable getReadableLocations() { * * @param locations the list of readable locations. */ - void setReadableLocations(Iterable locations) { - super.set(Constants.Properties.READABLE_LOCATIONS, locations); + public void setReadableLocations(Iterable locations) { + setProperty(this, Constants.Properties.READABLE_LOCATIONS, locations); } - boolean isEnableMultipleWriteLocations() { + public boolean isEnableMultipleWriteLocations() { return ObjectUtils.defaultIfNull(super.getBoolean(Constants.Properties.ENABLE_MULTIPLE_WRITE_LOCATIONS), false); } - void setEnableMultipleWriteLocations(boolean value) { - super.set(Constants.Properties.ENABLE_MULTIPLE_WRITE_LOCATIONS, value); + public void setEnableMultipleWriteLocations(boolean value) { + setProperty(this, Constants.Properties.ENABLE_MULTIPLE_WRITE_LOCATIONS, value); } - @Override - void populatePropertyBag() { + public void populatePropertyBag() { if (this.consistencyPolicy != null) { - this.consistencyPolicy.populatePropertyBag(); - super.set(Constants.Properties.USER_CONSISTENCY_POLICY, this.consistencyPolicy); + populatePropertyBagJsonSerializable(this.consistencyPolicy); + setProperty(this, Constants.Properties.USER_CONSISTENCY_POLICY, this.consistencyPolicy); } } + + @Override + public String toJson() { + this.populatePropertyBag(); + return super.toJson(); + } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountLocation.java similarity index 88% rename from sdk/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountLocation.java index bf743f7f8d69b..160dd825ee868 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/DatabaseAccountLocation.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountLocation.java @@ -21,9 +21,11 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.JsonSerializable; + +import static com.azure.data.cosmos.BridgeInternal.setProperty; /** * Represents the location of a database account in the Azure Cosmos DB database service. @@ -34,7 +36,7 @@ public class DatabaseAccountLocation extends JsonSerializable { * DEFAULT Constructor. Creates a new instance of the * DatabaseAccountLocation object. */ - DatabaseAccountLocation() { + public DatabaseAccountLocation() { super(); } @@ -63,7 +65,7 @@ public String getName() { * @param name the name of the database account location. */ public void setName(String name) { - super.set(Constants.Properties.Name, name); + setProperty(this, Constants.Properties.Name, name); } /** @@ -81,6 +83,6 @@ public String getEndpoint() { * @param endpoint the endpoint of the database account location. */ public void setEndpoint(String endpoint) { - super.set(Constants.Properties.DATABASE_ACCOUNT_ENDPOINT, endpoint); + setProperty(this, Constants.Properties.DATABASE_ACCOUNT_ENDPOINT, endpoint); } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountManagerInternal.java similarity index 95% rename from sdk/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountManagerInternal.java index 3606f07eff051..e423da21f639a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/DatabaseAccountManagerInternal.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountManagerInternal.java @@ -20,8 +20,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; +import com.azure.data.cosmos.ConnectionPolicy; import reactor.core.publisher.Flux; import java.net.URI; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java index 4b37c8e9f1555..3d2ca095c6f3b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.Database; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.SqlParameter; import com.azure.data.cosmos.SqlParameterList; diff --git a/sdk/src/main/java/com/azure/data/cosmos/Document.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Document.java similarity index 89% rename from sdk/src/main/java/com/azure/data/cosmos/Document.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Document.java index 87a07417451c0..9e4f5e2dfb9ca 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/Document.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/Document.java @@ -21,13 +21,17 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.Resource; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; +import static com.azure.data.cosmos.BridgeInternal.remove; +import static com.azure.data.cosmos.BridgeInternal.setProperty; +import static com.azure.data.cosmos.BridgeInternal.setMapper; + /** * Represents a document in the Azure Cosmos DB database service. *

@@ -62,7 +66,8 @@ public Document id(String id){ */ Document(String jsonString, ObjectMapper objectMapper) { // TODO: Made package private due to #153. #171 adding custom serialization options back. - super(jsonString, objectMapper); + super(jsonString); + setMapper(this, objectMapper); } /** @@ -74,7 +79,7 @@ public Document(String jsonString) { super(jsonString); } - static Document FromObject(Object document, ObjectMapper objectMapper) { + public static Document FromObject(Object document, ObjectMapper objectMapper) { Document typedDocument; if (document instanceof Document) { typedDocument = (Document) document; @@ -121,9 +126,9 @@ public void setTimeToLive(Integer timeToLive) { // a "null" value is represented as a missing element on the wire. // setting timeToLive to null should remove the property from the property bag. if (timeToLive != null) { - super.set(Constants.Properties.TTL, timeToLive); + setProperty(this, Constants.Properties.TTL, timeToLive); } else if (super.has(Constants.Properties.TTL)) { - super.remove(Constants.Properties.TTL); + remove(this, Constants.Properties.TTL); } } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/DocumentCollection.java b/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentCollection.java similarity index 88% rename from sdk/src/main/java/com/azure/data/cosmos/DocumentCollection.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/DocumentCollection.java index a4d195d90d051..13e552434f094 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/DocumentCollection.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentCollection.java @@ -21,11 +21,19 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.ConflictResolutionPolicy; +import com.azure.data.cosmos.IndexingPolicy; +import com.azure.data.cosmos.PartitionKeyDefinition; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.UniqueKeyPolicy; import org.apache.commons.lang3.StringUtils; +import static com.azure.data.cosmos.BridgeInternal.populatePropertyBagJsonSerializable; +import static com.azure.data.cosmos.BridgeInternal.setProperty; +import static com.azure.data.cosmos.BridgeInternal.remove; + /** * Represents a document collection in the Azure Cosmos DB database service. A collection is a named logical container * for documents. @@ -160,9 +168,9 @@ public void setDefaultTimeToLive(Integer timeToLive) { // a "null" value is represented as a missing element on the wire. // setting timeToLive to null should remove the property from the property bag. if (timeToLive != null) { - super.set(Constants.Properties.DEFAULT_TTL, timeToLive); + setProperty(this, Constants.Properties.DEFAULT_TTL, timeToLive); } else if (super.has(Constants.Properties.DEFAULT_TTL)) { - super.remove(Constants.Properties.DEFAULT_TTL); + remove(this, Constants.Properties.DEFAULT_TTL); } } @@ -190,7 +198,7 @@ public void setUniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) { } this.uniqueKeyPolicy = uniqueKeyPolicy; - super.set(Constants.Properties.UNIQUE_KEY_POLICY, uniqueKeyPolicy); + setProperty(this, Constants.Properties.UNIQUE_KEY_POLICY, uniqueKeyPolicy); } /** @@ -214,7 +222,7 @@ public void setConflictResolutionPolicy(ConflictResolutionPolicy value) { throw new IllegalArgumentException("CONFLICT_RESOLUTION_POLICY cannot be null."); } - super.set(Constants.Properties.CONFLICT_RESOLUTION_POLICY, value); + setProperty(this, Constants.Properties.CONFLICT_RESOLUTION_POLICY, value); } @@ -270,7 +278,6 @@ public String getConflictsLink() { "/" + super.getString(Constants.Properties.CONFLICTS_LINK); } - @Override void populatePropertyBag() { if (this.indexingPolicy == null) { this.getIndexingPolicy(); @@ -280,14 +287,14 @@ void populatePropertyBag() { } if (this.partitionKeyDefinition != null) { - this.partitionKeyDefinition.populatePropertyBag(); - super.set(Constants.Properties.PARTITION_KEY, this.partitionKeyDefinition); + populatePropertyBagJsonSerializable(this.partitionKeyDefinition); + setProperty(this, Constants.Properties.PARTITION_KEY, this.partitionKeyDefinition); } + populatePropertyBagJsonSerializable(this.indexingPolicy); + populatePropertyBagJsonSerializable(this.uniqueKeyPolicy); - this.indexingPolicy.populatePropertyBag(); - this.uniqueKeyPolicy.populatePropertyBag(); - super.set(Constants.Properties.INDEXING_POLICY, this.indexingPolicy); - super.set(Constants.Properties.UNIQUE_KEY_POLICY, this.uniqueKeyPolicy); + setProperty(this, Constants.Properties.INDEXING_POLICY, this.indexingPolicy); + setProperty(this, Constants.Properties.UNIQUE_KEY_POLICY, this.uniqueKeyPolicy); } @Override @@ -304,4 +311,10 @@ public boolean equals(Object obj) { public int hashCode() { return this.resourceId().hashCode(); } + + @Override + public String toJson() { + this.populatePropertyBag(); + return super.toJson(); + } } \ No newline at end of file diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java b/sdk/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java index 24a56c6bd3d9f..90d5957302a0c 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java @@ -25,8 +25,6 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.DatabaseAccount; -import com.azure.data.cosmos.DatabaseAccountManagerInternal; import com.azure.data.cosmos.internal.routing.LocationCache; import com.azure.data.cosmos.internal.routing.LocationHelper; import org.apache.commons.collections4.list.UnmodifiableList; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java b/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java index 9d4b63288f369..f1af93352ca66 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java @@ -219,7 +219,7 @@ public static class HttpHeaders { public static final String A_IM = "A-IM"; public static final String ALLOW_TENTATIVE_WRITES = "x-ms-cosmos-allow-tentative-writes"; - // These settings were added to support RNTBD and they've been added here to + // These properties were added to support RNTBD and they've been added here to // reduce merge conflicts public static final String CAN_CHARGE = "x-ms-cancharge"; diff --git a/sdk/src/main/java/com/azure/data/cosmos/ISessionContainer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ISessionContainer.java similarity index 99% rename from sdk/src/main/java/com/azure/data/cosmos/ISessionContainer.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/ISessionContainer.java index d292dc869a93a..ed47596aff626 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/ISessionContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ISessionContainer.java @@ -21,7 +21,7 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; import com.azure.data.cosmos.internal.ISessionToken; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java b/sdk/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java deleted file mode 100644 index 0c1c960553bd5..0000000000000 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/MediaReadMode.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * The MIT License (MIT) - * Copyright (c) 2018 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.azure.data.cosmos.internal; - -/** - * Represents the mode for use with downloading attachment content (aka media) from the Azure Cosmos DB database service. - */ -public enum MediaReadMode { - - /** - * Content is buffered at the client and not directly streamed from the - * content store. Use Buffered to reduce the time taken to read and write - * media files. - */ - Buffered, - - /** - * Content is directly streamed from the content store without any buffering - * at the client. Use Streamed to reduce the client memory overhead of - * reading and writing media files. - */ - Streamed -} diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java index 622fbf3797d61..a72c6fef177f8 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.internal.caches.IPartitionKeyRangeCache; import com.azure.data.cosmos.internal.caches.RxCollectionCache; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java index c890b843f2e7b..8294feedf2add 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java @@ -23,12 +23,7 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.Attachment; import com.azure.data.cosmos.BadRequestException; -import com.azure.data.cosmos.Conflict; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.Resource; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; @@ -71,8 +66,6 @@ public static String generatePathForNameBased(Resource resourceType, String reso return resourceOwnerFullName + "/" + Paths.TRIGGERS_PATH_SEGMENT + "/" + resourceName; } else if (resourceType instanceof Conflict) { return resourceOwnerFullName + "/" + Paths.CONFLICTS_PATH_SEGMENT + "/" + resourceName; - } else if (resourceType instanceof Attachment) { - return resourceOwnerFullName + "/" + Paths.ATTACHMENTS_PATH_SEGMENT + "/" + resourceName; } else if (resourceType instanceof User) { return resourceOwnerFullName + "/" + Paths.USERS_PATH_SEGMENT + "/" + resourceName; } else if (resourceType instanceof Permission) { @@ -859,7 +852,6 @@ public static boolean isPublicResource(Resource resourceType) { resourceType instanceof UserDefinedFunction || resourceType instanceof Trigger || resourceType instanceof Conflict || - resourceType instanceof Attachment || resourceType instanceof User || resourceType instanceof Permission || resourceType instanceof Document || diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java index 558a6cf332e84..86570eb1c4b72 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java @@ -23,8 +23,6 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java index dd6c46770e2f3..8a76dde7f420b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java @@ -22,7 +22,6 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; public class ResetSessionTokenRetryPolicyFactory implements IRetryPolicyFactory { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java index cd7d6cb429d93..a8445b91fd5bb 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java @@ -23,22 +23,14 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.AccessConditionType; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ChangeFeedOptions; -import com.azure.data.cosmos.Conflict; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosResourceType; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DatabaseAccount; -import com.azure.data.cosmos.DatabaseAccountManagerInternal; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; -import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.JsonSerializable; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java index 718d187451a91..2485ce563e388 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java @@ -23,13 +23,8 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.Attachment; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.Conflict; import com.azure.data.cosmos.CosmosResponseDiagnostics; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.internal.directconnectivity.Address; import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; @@ -72,9 +67,7 @@ public RxDocumentServiceResponse(StoreResponse response) { } public static String getResourceKey(Class c) { - if (c.equals(Attachment.class)) { - return InternalConstants.ResourceKeys.ATTACHMENTS; - } else if (c.equals(Conflict.class)) { + if (c.equals(Conflict.class)) { return InternalConstants.ResourceKeys.CONFLICTS; } else if (c.equals(Database.class)) { return InternalConstants.ResourceKeys.DATABASES; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java b/sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java index 9eebe2bea3653..a46f076a6a4cd 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java @@ -27,7 +27,6 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosError; -import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.internal.directconnectivity.HttpUtils; import com.azure.data.cosmos.internal.directconnectivity.StoreResponse; import com.azure.data.cosmos.internal.http.HttpClient; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java b/sdk/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java index 04ced6a7c9138..dc1f91bf57f22 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java @@ -24,7 +24,6 @@ package com.azure.data.cosmos.internal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.ISessionContainer; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java index b2eb877332bf2..5926de23533e4 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java @@ -25,7 +25,6 @@ import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.InternalServerErrorException; import org.apache.commons.lang3.StringUtils; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java b/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java index bf4ae1a06bf36..7ccac84529036 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java @@ -23,9 +23,7 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.Attachment; import com.azure.data.cosmos.CosmosResponseDiagnostics; -import com.azure.data.cosmos.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -127,15 +125,6 @@ public Document getResponseAsDocument() { return this.response.getResource(Document.class); } - /** - * Gets the response of a stored procedure, serialized into an attachment. - * - * @return the response as an attachment. - */ - public Attachment getResponseAsAttachment() { - return this.response.getResource(Attachment.class); - } - /** * Gets the response of a stored procedure as a string. * diff --git a/sdk/src/main/java/com/azure/data/cosmos/Undefined.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Undefined.java similarity index 95% rename from sdk/src/main/java/com/azure/data/cosmos/Undefined.java rename to sdk/src/main/java/com/azure/data/cosmos/internal/Undefined.java index e0951a340278a..82bdf0cb88b42 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/Undefined.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/Undefined.java @@ -21,7 +21,9 @@ * SOFTWARE. */ -package com.azure.data.cosmos; +package com.azure.data.cosmos.internal; + +import com.azure.data.cosmos.JsonSerializable; /** * Represents the 'Undefined' partition key in the Azure Cosmos DB database service. diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Utils.java b/sdk/src/main/java/com/azure/data/cosmos/internal/Utils.java index bfa3a73274f8e..843ea904d1a4f 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/Utils.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/Utils.java @@ -24,7 +24,6 @@ import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.DocumentCollection; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java index 84116a4a01a29..565d218954242 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java @@ -23,8 +23,8 @@ package com.azure.data.cosmos.internal.caches; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.DocumentCollection; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.ClearingSessionContainerClientRetryPolicy; import com.azure.data.cosmos.internal.HttpConstants; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java index c07f582d2e09c..1a3d510a81915 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos.internal.caches; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.InvalidPartitionException; import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.PathsHelper; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java index 6085c00b72e06..c52fdd85ce0f5 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java @@ -22,9 +22,9 @@ */ package com.azure.data.cosmos.internal.caches; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.Exceptions; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java index eacfd90aea4b0..f715a440fcb61 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java @@ -139,11 +139,11 @@ Mono createItem(CosmosContainer containerLink, Object docume URI getServiceEndpoint(); /** - * Reads and returns the container settings. + * Reads and returns the container properties. * * @param containerLink a reference to the container. * @param options the {@link CosmosContainerRequestOptions} for this request; it can be set as null. - * @return an {@link Mono} containing the read container settings. + * @return an {@link Mono} containing the read container properties. */ Mono readContainerSettings(CosmosContainer containerLink, CosmosContainerRequestOptions options); diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java index b08edecce5a0f..8c892d4d4d440 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.CosmosContainer; /** - * Captures LeaseStoreManager settings. + * Captures LeaseStoreManager properties. */ public class LeaseStoreManagerSettings { String containerNamePrefix; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java index ae61fade13ecd..9a9463f5c72cf 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java @@ -28,7 +28,7 @@ import java.time.OffsetDateTime; /** - * Implementation for the partition processor settings. + * Implementation for the partition processor properties. */ public class ProcessorSettings { private CosmosContainer collectionSelfLink; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java index 2ba022de1737c..3cd2f125039b1 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.changefeed; import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.internal.Constants; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java index b08b27dd9b5db..9d98c6da6fadb 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos.internal.changefeed.implementation; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosContainerProperties; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java index dafb72dd3f601..224c69f7f7311 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java @@ -121,10 +121,10 @@ public LeaseStoreManagerBuilderDefinition hostName(String hostName) { @Override public Mono build() { - if (this.settings == null) throw new IllegalArgumentException("settings"); - if (this.settings.getContainerNamePrefix() == null) throw new IllegalArgumentException("settings.containerNamePrefix"); - if (this.settings.getLeaseCollectionLink() == null) throw new IllegalArgumentException("settings.leaseCollectionLink"); - if (this.settings.getHostName() == null || this.settings.getHostName().isEmpty()) throw new IllegalArgumentException("settings.hostName"); + if (this.settings == null) throw new IllegalArgumentException("properties"); + if (this.settings.getContainerNamePrefix() == null) throw new IllegalArgumentException("properties.containerNamePrefix"); + if (this.settings.getLeaseCollectionLink() == null) throw new IllegalArgumentException("properties.leaseCollectionLink"); + if (this.settings.getHostName() == null || this.settings.getHostName().isEmpty()) throw new IllegalArgumentException("properties.hostName"); if (this.leaseDocumentClient == null) throw new IllegalArgumentException("leaseDocumentClient"); if (this.requestOptionsFactory == null) throw new IllegalArgumentException("requestOptionsFactory"); if (this.leaseUpdater == null) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java index 1b978f9907f3b..8f7c563d8fe78 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java @@ -67,12 +67,12 @@ public PartitionProcessorImpl(ChangeFeedObserver observer, ChangeFeedContextClie this.options = new ChangeFeedOptions(); this.options.maxItemCount(settings.getMaxItemCount()); partitionKeyRangeIdInternal(this.options, settings.getPartitionKeyRangeId()); - // this.options.sessionToken(settings.sessionToken()); + // this.options.sessionToken(properties.sessionToken()); this.options.startFromBeginning(settings.isStartFromBeginning()); this.options.requestContinuation(settings.getStartContinuation()); this.options.startDateTime(settings.getStartTime()); - //this.query = documentClient.createDocumentChangeFeedQuery(self.settings.getCollectionSelfLink(), this.options); + //this.query = documentClient.createDocumentChangeFeedQuery(self.properties.getCollectionSelfLink(), this.options); } @Override @@ -111,7 +111,7 @@ public Mono run(CancellationToken cancellationToken) { if (ex.getCause() instanceof CosmosClientException) { CosmosClientException clientException = (CosmosClientException) ex.getCause(); - // this.logger.WarnException("exception: partition '{0}'", clientException, this.settings.PartitionKeyRangeId); + // this.logger.WarnException("exception: partition '{0}'", clientException, this.properties.PartitionKeyRangeId); StatusCodeErrorType docDbError = ExceptionClassifier.classifyClientException(clientException); switch (docDbError) { @@ -143,7 +143,7 @@ public Mono run(CancellationToken cancellationToken) { } } } else if (ex instanceof TaskCancelledException) { - // this.logger.WarnException("exception: partition '{0}'", canceledException, this.settings.PartitionKeyRangeId); + // this.logger.WarnException("exception: partition '{0}'", canceledException, this.properties.PartitionKeyRangeId); self.resultException = ex; } } diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java index 27bfa38fb24b1..68c71488da960 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java @@ -38,6 +38,8 @@ import java.util.HashSet; import java.util.Set; +import static com.azure.data.cosmos.BridgeInternal.extractContainerSelfLink; + /** * Implementation for the partition synchronizer. */ @@ -120,7 +122,7 @@ public Flux splitPartition(Lease lease) { private Flux enumPartitionKeyRanges() { // STRING partitionKeyRangesPath = STRING.format("%spkranges", this.collectionSelfLink); - String partitionKeyRangesPath = CosmosContainer.getSelfLink(this.collectionSelfLink); + String partitionKeyRangesPath = extractContainerSelfLink(this.collectionSelfLink); FeedOptions feedOptions = new FeedOptions(); feedOptions.maxItemCount(this.maxBatchSize); feedOptions.requestContinuation(null); diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java index a5bb8e5ad241f..d02517152cded 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java @@ -26,7 +26,7 @@ import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.InvalidPartitionException; import com.azure.data.cosmos.NotFoundException; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java index 0617e3254d9e9..3ddf572d09643 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; -import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.RequestTimeoutException; import com.azure.data.cosmos.internal.Configs; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java index 77ea1e2481761..2202c5c5ccfff 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; -import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.RequestTimeoutException; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java index ff1d49a1764ea..e07c3d8c7253a 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.PartitionKeyRangeGoneException; import com.azure.data.cosmos.internal.AuthorizationTokenType; import com.azure.data.cosmos.internal.Constants; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java index 7e480a92438f8..e02e7ef88b20b 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java @@ -23,12 +23,11 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.DatabaseAccount; import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; import com.azure.data.cosmos.internal.Constants; +import com.azure.data.cosmos.internal.DatabaseAccount; import com.azure.data.cosmos.internal.GlobalEndpointManager; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.ReplicationPolicy; @@ -158,10 +157,10 @@ public Mono initializeReaderAsync() { throw new IllegalArgumentException("URI " + url); } }).doOnSuccess(databaseAccount -> { - userReplicationPolicy = BridgeInternal.getReplicationPolicy(databaseAccount); - systemReplicationPolicy = BridgeInternal.getSystemReplicationPolicy(databaseAccount); - queryEngineConfiguration = BridgeInternal.getQueryEngineConfiuration(databaseAccount); - consistencyLevel = BridgeInternal.getConsistencyPolicy(databaseAccount).getDefaultConsistencyLevel(); + userReplicationPolicy = databaseAccount.getReplicationPolicy(); + systemReplicationPolicy = databaseAccount.getSystemReplicationPolicy(); + queryEngineConfiguration = databaseAccount.getQueryEngineConfiuration(); + consistencyLevel = databaseAccount.getConsistencyPolicy().defaultConsistencyLevel(); initialized = true; }); } catch (MalformedURLException e) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java index 791bbbe0a140d..0e5b8f918317e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.internal.GlobalEndpointManager; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.PartitionKeyRange; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java index 138219cd319ba..ff9df5aa91b55 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.internal.BackoffRetryUtility; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.HttpConstants; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java index 3858838540965..ec2415fc96ea2 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; -import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.InternalServerErrorException; import com.azure.data.cosmos.PartitionIsMigratingException; import com.azure.data.cosmos.PartitionKeyRangeGoneException; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java index 88ed48ccdd0be..543d03b16cf5e 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java @@ -24,10 +24,10 @@ package com.azure.data.cosmos.internal.query; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; -import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Undefined; import com.azure.data.cosmos.internal.Constants; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.QueryMetrics; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java index 7c52b54ae4044..bef8a6b7fdc31 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java @@ -24,7 +24,7 @@ import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.Resource; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java index 9daed7e1b118c..b43d8cf0fdfab 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.query; -import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Undefined; public final class ItemTypeHelper { public static ItemType getOrderByItemType(Object obj) { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java index 6601b759d38eb..a3980bea91665 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.query; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java index c23c468078131..ff447462358be 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java @@ -25,7 +25,7 @@ package com.azure.data.cosmos.internal.query; import com.azure.data.cosmos.JsonSerializable; -import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Undefined; /** * Used internally for query in the Azure Cosmos DB database service. diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java index 1ecbbb4afaf06..d64ba353914c5 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.query.aggregation; -import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Undefined; import com.azure.data.cosmos.internal.Utils; import java.io.IOException; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java index 523b9f776fb51..ea59e3b4538e6 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.query.aggregation; -import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Undefined; import com.azure.data.cosmos.internal.query.ItemComparator; public class MaxAggregator implements Aggregator { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java index ebad5582c5a7a..981e55a957b89 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.query.aggregation; -import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Undefined; import com.azure.data.cosmos.internal.query.ItemComparator; public class MinAggregator implements Aggregator { diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java index 100c56119c4ec..0d238dc9a0c00 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.query.aggregation; -import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Undefined; public class SumAggregator implements Aggregator { private Double sum; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java b/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java index bc49218e8b53d..2427b16d25355 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.query.orderbyquery; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.query.QueryItem; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java index 7e7f276919f32..78c2cf6d7ea72 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java @@ -24,8 +24,8 @@ package com.azure.data.cosmos.internal.routing; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.DatabaseAccount; -import com.azure.data.cosmos.DatabaseAccountLocation; +import com.azure.data.cosmos.internal.DatabaseAccount; +import com.azure.data.cosmos.internal.DatabaseAccountLocation; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java index b5cddde833e2d..fc9c6e63c4e35 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.routing; -import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Undefined; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.Strings; import com.azure.data.cosmos.internal.Utils; diff --git a/sdk/src/test/java/com/azure/data/cosmos/BridgeUtils.java b/sdk/src/test/java/com/azure/data/cosmos/BridgeUtils.java index 43afebcdaa69c..864c5cf448874 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/BridgeUtils.java +++ b/sdk/src/test/java/com/azure/data/cosmos/BridgeUtils.java @@ -23,6 +23,9 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.DatabaseAccount; +import com.azure.data.cosmos.internal.DatabaseAccountLocation; + import java.util.List; /** diff --git a/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java index afe66309bdb19..e597e9d2676d7 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java @@ -31,11 +31,11 @@ public class ClientUnderTestBuilder extends CosmosClientBuilder { public ClientUnderTestBuilder(CosmosClientBuilder builder) { - this.configs(builder.getConfigs()); - this.connectionPolicy(builder.getConnectionPolicy()); - this.consistencyLevel(builder.getDesiredConsistencyLevel()); - this.key(builder.getKeyOrResourceToken()); - this.endpoint(builder.getServiceEndpoint()); + this.configs(builder.configs()); + this.connectionPolicy(builder.connectionPolicy()); + this.consistencyLevel(builder.consistencyLevel()); + this.key(builder.key()); + this.endpoint(builder.endpoint()); } @Override @@ -43,11 +43,11 @@ public CosmosClient build() { RxDocumentClientUnderTest rxClient; try { rxClient = new RxDocumentClientUnderTest( - new URI(this.getServiceEndpoint()), - this.getKeyOrResourceToken(), - this.getConnectionPolicy(), - this.getDesiredConsistencyLevel(), - this.getConfigs()); + new URI(this.endpoint()), + this.key(), + this.connectionPolicy(), + this.consistencyLevel(), + this.configs()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e.getMessage()); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/ConflictTests.java b/sdk/src/test/java/com/azure/data/cosmos/ConflictTests.java index 8ec191b8c82d9..2ecafa25a9b90 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/ConflictTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/ConflictTests.java @@ -23,6 +23,8 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Conflict; +import com.azure.data.cosmos.internal.Document; import org.apache.commons.io.IOUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java index 0dce9b08dc15d..dce8d389f77aa 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java @@ -58,15 +58,15 @@ public final void setTestName(Method method) { method.getDeclaringClass().getSimpleName(), method.getName()); - if (this.clientBuilder.getConnectionPolicy() != null && this.clientBuilder.getConfigs() != null) { - String connectionMode = this.clientBuilder.getConnectionPolicy().connectionMode() == ConnectionMode.DIRECT - ? "Direct " + this.clientBuilder.getConfigs().getProtocol() + if (this.clientBuilder.connectionPolicy() != null && this.clientBuilder.configs() != null) { + String connectionMode = this.clientBuilder.connectionPolicy().connectionMode() == ConnectionMode.DIRECT + ? "Direct " + this.clientBuilder.configs().getProtocol() : "Gateway"; this.testName = Strings.lenientFormat("%s[%s with %s consistency]", testClassAndMethodName, connectionMode, - clientBuilder.getDesiredConsistencyLevel()); + clientBuilder.consistencyLevel()); } else { this.testName = testClassAndMethodName; } diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java index 959f2810ab803..2e862ea61c2b1 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java @@ -182,7 +182,7 @@ public void testNonPartitionedCollectionOperations() throws Exception { .build(); validateQuerySuccess(queryFlux, queryValidator); - queryFlux = createdContainer.listItems(feedOptions); + queryFlux = createdContainer.readAllItems(feedOptions); queryValidator = new FeedResponseListValidator.Builder() .totalSize(3) .numberOfPages(1) @@ -210,12 +210,12 @@ public void testNonPartitionedCollectionOperations() throws Exception { // Partiton Key value same as what is specified in the stored procedure body RequestOptions options = new RequestOptions(); options.setPartitionKey(PartitionKey.None); - int result = Integer.parseInt(createdSproc.execute(null, options).block().responseAsString()); + int result = Integer.parseInt(createdSproc.execute(null, new CosmosStoredProcedureRequestOptions()).block().responseAsString()); assertThat(result).isEqualTo(1); // 3 previous items + 1 created from the sproc expectedIds.add(documentCreatedBySprocId); - queryFlux = createdContainer.listItems(feedOptions); + queryFlux = createdContainer.readAllItems(feedOptions); queryValidator = new FeedResponseListValidator.Builder() .totalSize(4) .numberOfPages(1) @@ -243,7 +243,7 @@ public void testNonPartitionedCollectionOperations() throws Exception { .nullResource().build(); validateSuccess(deleteMono, validator); - queryFlux = createdContainer.listItems(feedOptions); + queryFlux = createdContainer.readAllItems(feedOptions); queryValidator = new FeedResponseListValidator.Builder() .totalSize(0) .numberOfPages(1) diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java b/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java index 26a98d9d0344b..798e57c1099b2 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java @@ -61,7 +61,7 @@ public void validate(T resourceResponse) { return this; } - private Resource getResource(T resourceResponse) { + private Resource getResource(T resourceResponse) { if (resourceResponse instanceof CosmosDatabaseResponse) { return ((CosmosDatabaseResponse)resourceResponse).properties(); } else if (resourceResponse instanceof CosmosContainerResponse) { @@ -73,9 +73,9 @@ private Resource getResource(T resourceResponse) { } else if (resourceResponse instanceof CosmosTriggerResponse) { return ((CosmosTriggerResponse)resourceResponse).properties(); } else if (resourceResponse instanceof CosmosUserDefinedFunctionResponse) { - return ((CosmosUserDefinedFunctionResponse)resourceResponse).settings(); + return ((CosmosUserDefinedFunctionResponse)resourceResponse).properties(); } else if (resourceResponse instanceof CosmosUserResponse) { - return ((CosmosUserResponse)resourceResponse).settings(); + return ((CosmosUserResponse)resourceResponse).properties(); } else if (resourceResponse instanceof CosmosPermissionResponse) { return ((CosmosPermissionResponse) resourceResponse).properties(); } @@ -249,7 +249,7 @@ public Builder withUserDefinedFunctionBody(String functionBody) { @Override public void validate(CosmosUserDefinedFunctionResponse resourceResponse) { - assertThat(resourceResponse.settings().body()).isEqualTo(functionBody); + assertThat(resourceResponse.properties().body()).isEqualTo(functionBody); } }); return this; diff --git a/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java b/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java index d26fc1562d70a..deb7b0166ac96 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.google.common.base.Strings; import org.testng.ITest; import org.testng.annotations.AfterMethod; diff --git a/sdk/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java b/sdk/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java index 1f26c981df43c..da0998b22235d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java @@ -23,6 +23,7 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.DocumentCollection; import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; diff --git a/sdk/src/test/java/com/azure/data/cosmos/DocumentTests.java b/sdk/src/test/java/com/azure/data/cosmos/DocumentTests.java index 656c8e93d542e..e336876d67fd9 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/DocumentTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/DocumentTests.java @@ -23,11 +23,13 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Document; import org.testng.annotations.Test; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import static com.azure.data.cosmos.BridgeInternal.setTimestamp; import static org.assertj.core.api.Assertions.assertThat; public class DocumentTests { @@ -36,7 +38,7 @@ public class DocumentTests { public void timestamp() { Document d = new Document(); OffsetDateTime time = OffsetDateTime.of(2019, 8, 6, 12, 53, 29, 0, ZoneOffset.UTC); - d.timestamp(time); + setTimestamp(d, time); assertThat(d.timestamp()).isEqualTo(time); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java b/sdk/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java index cd91eec212194..ed390db320b51 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java @@ -1,5 +1,6 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Document; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; @@ -7,6 +8,7 @@ import java.io.Serializable; +import static com.azure.data.cosmos.BridgeInternal.setProperty; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.fail; @@ -53,29 +55,29 @@ public enum enums { public void getObjectAndCastToClass() { Document document = new Document(); // numeric values - document.set("intValue", Integer.MAX_VALUE); - document.set("doubleValue", Double.MAX_VALUE); - document.set("longValue", Long.MAX_VALUE); + setProperty(document, "intValue", Integer.MAX_VALUE); + setProperty(document, "doubleValue", Double.MAX_VALUE); + setProperty(document, "longValue", Long.MAX_VALUE); assertThat(document.getObject("intValue", Integer.class).intValue()).isEqualTo(Integer.MAX_VALUE); assertThat(document.getObject("doubleValue", Double.class).doubleValue()).isEqualTo(Double.MAX_VALUE); assertThat(document.getObject("longValue", Long.class).longValue()).isEqualTo(Long.MAX_VALUE); // string - document.set("stringValue", "stringField"); + setProperty(document, "stringValue", "stringField"); assertThat(document.getObject("stringValue", String.class)).isEqualTo("stringField"); // boolean - document.set("boolValue", true); + setProperty(document, "boolValue", true); assertThat(document.getObject("boolValue", Boolean.class)).isEqualTo(true); // enum - document.set("enumValue", "third"); + setProperty(document, "enumValue", "third"); assertThat(document.getObject("enumValue", enums.class)).isEqualTo(enums.third); // Pojo Pojo pojo = new Pojo(1, 2); - document.set("pojoValue", pojo); + setProperty(document, "pojoValue", pojo); Pojo readPojo = document.getObject("pojoValue", Pojo.class); assertThat(readPojo.getA()).isEqualTo(pojo.getA()); assertThat(readPojo.getB()).isEqualTo(pojo.getB()); @@ -83,7 +85,7 @@ public void getObjectAndCastToClass() { // JsonSerializable Document innerDocument = new Document(); innerDocument.id("innerDocument"); - document.set("innerDocument", innerDocument); + setProperty(document, "innerDocument", innerDocument); Document readInnerDocument = document.getObject("innerDocument", Document.class); assertThat(readInnerDocument.id()).isEqualTo(innerDocument.id()); } diff --git a/sdk/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java b/sdk/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java index bb40a6e61b63c..36b117ce4d249 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java @@ -1,5 +1,6 @@ package com.azure.data.cosmos; +import com.azure.data.cosmos.internal.Undefined; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.fasterxml.jackson.databind.node.NullNode; import org.testng.annotations.Test; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java index 30c7127d1d666..2c2487447be0a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java @@ -23,18 +23,12 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKind; -import com.azure.data.cosmos.internal.FailureValidator; -import com.azure.data.cosmos.internal.ResourceResponseValidator; -import com.azure.data.cosmos.internal.TestConfigurations; import org.testng.SkipException; import org.testng.annotations.Test; import reactor.core.publisher.Flux; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java index 5a37940dbc4cd..9a58d4b056795 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java @@ -23,14 +23,11 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java index 4ab441b19f369..7dbdddea5586b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java @@ -26,14 +26,10 @@ import com.azure.data.cosmos.AccessCondition; import com.azure.data.cosmos.AccessConditionType; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKind; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java index 543da492abc08..266ace95c5764 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java @@ -22,15 +22,10 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.AsyncDocumentClient.Builder; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.SpyClientBuilder; import com.azure.data.cosmos.internal.http.HttpRequest; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java index aedb8d046173f..4da9e76512226 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java @@ -25,7 +25,6 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.Document; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.Resource; import com.fasterxml.jackson.databind.node.ArrayNode; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java index 46f6ea1967e6d..c045cd9cb6670 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java @@ -23,10 +23,6 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.internal.FailureValidator; import org.mockito.Mockito; import org.testng.annotations.AfterClass; import org.testng.annotations.Factory; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java index 169557c82f532..7a03819197c2e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java @@ -24,8 +24,6 @@ import com.azure.data.cosmos.BadRequestException; import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.caches.RxClientCollectionCache; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java b/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java index 6f4174777e031..8a2ca2755902f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java @@ -22,9 +22,7 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.Attachment; import com.azure.data.cosmos.CompositePath; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.IndexingMode; import com.azure.data.cosmos.PermissionMode; import com.azure.data.cosmos.Resource; @@ -253,17 +251,6 @@ public void validate(ResourceResponse resourceResponse) { return this; } - public Builder withContentType(final String contentType) { - validators.add(new ResourceResponseValidator() { - - @Override - public void validate(ResourceResponse resourceResponse) { - assertThat(resourceResponse.getResource().getContentType()).isEqualTo(contentType); - } - }); - return this; - } - public Builder withOfferThroughput(int throughput) { validators.add(new ResourceResponseValidator() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java index c3c5547c94915..061694d03f1b3 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java @@ -23,15 +23,8 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; -import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosError; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; -import com.azure.data.cosmos.internal.FailureValidator; -import com.azure.data.cosmos.internal.ResourceResponseValidator; import com.google.common.collect.ImmutableMap; import org.mockito.Mockito; import org.mockito.stubbing.Answer; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java index 8361ff9fbf718..1f8e1c2fe381a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java @@ -23,17 +23,10 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.RetryOptions; -import com.azure.data.cosmos.internal.ResourceResponseValidator; -import com.azure.data.cosmos.internal.TestConfigurations; import org.mockito.stubbing.Answer; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java index ed4149961ab94..f7415164cfd3e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java @@ -25,7 +25,6 @@ import com.azure.data.cosmos.ClientUnderTestBuilder; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpRequest; import com.azure.data.cosmos.internal.http.HttpResponse; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java index 32e446ccb385b..f6463cd8530cd 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java @@ -23,7 +23,6 @@ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.Document; import org.apache.commons.collections4.map.HashedMap; import org.apache.commons.lang3.StringUtils; import org.testng.annotations.DataProvider; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java index f451bc37838dc..41579731c3f5d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java @@ -25,10 +25,8 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.ISessionContainer; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpRequest; -import com.azure.data.cosmos.internal.FailureValidator; import io.netty.handler.timeout.ReadTimeoutException; import io.reactivex.subscribers.TestSubscriber; import org.mockito.Mockito; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java index 08c6f759f8531..3ec00b7246b68 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java @@ -22,12 +22,8 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.internal.http.HttpRequest; diff --git a/sdk/src/test/java/com/azure/data/cosmos/SpyClientBuilder.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientBuilder.java similarity index 96% rename from sdk/src/test/java/com/azure/data/cosmos/SpyClientBuilder.java rename to sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientBuilder.java index a463f8832964b..ea0a005922b12 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/SpyClientBuilder.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientBuilder.java @@ -20,9 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ -package com.azure.data.cosmos; - -import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; +package com.azure.data.cosmos.internal; public class SpyClientBuilder extends AsyncDocumentClient.Builder { diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java index 20fa70001d066..5a7c776721ec8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java @@ -22,12 +22,9 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.SpyClientBuilder; import com.azure.data.cosmos.internal.directconnectivity.Protocol; import com.azure.data.cosmos.internal.directconnectivity.ReflectionUtils; import com.azure.data.cosmos.internal.http.HttpClient; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java b/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java index d94f7a3f708e3..f748a4e325fdb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java @@ -22,10 +22,6 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java index 11cdb831f745f..e353afbdbefa8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java @@ -22,8 +22,8 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.Resource; +import com.azure.data.cosmos.internal.AsyncDocumentClient.Builder; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CompositePath; import com.azure.data.cosmos.CompositePathSortOrder; @@ -32,10 +32,7 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.DataType; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; import com.azure.data.cosmos.DocumentClientTest; -import com.azure.data.cosmos.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.IncludedPath; @@ -43,10 +40,8 @@ import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; -import com.azure.data.cosmos.Undefined; import com.azure.data.cosmos.internal.directconnectivity.Protocol; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; @@ -458,7 +453,7 @@ public Flux> bulkInsert(AsyncDocumentClient client, } public static ConsistencyLevel getAccountDefaultConsistencyLevel(AsyncDocumentClient client) { - return client.getDatabaseAccount().single().block().getConsistencyPolicy().getDefaultConsistencyLevel(); + return client.getDatabaseAccount().single().block().getConsistencyPolicy().defaultConsistencyLevel(); } public static User createUser(AsyncDocumentClient client, String databaseId, User user) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java b/sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java index 607b030714b9c..1c8ef3590d025 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java @@ -22,8 +22,6 @@ */ package com.azure.data.cosmos.internal; -import com.azure.data.cosmos.Database; - public class TestUtils { private static final String DATABASES_PATH_SEGMENT = "dbs"; private static final String COLLECTIONS_PATH_SEGMENT = "colls"; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java index d2fd5b7d63d4c..64676e488db0b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.PartitionKeyRangeGoneException; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; @@ -37,10 +37,6 @@ import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; import com.azure.data.cosmos.internal.caches.RxCollectionCache; -import com.azure.data.cosmos.internal.directconnectivity.AddressInformation; -import com.azure.data.cosmos.internal.directconnectivity.AddressResolver; -import com.azure.data.cosmos.internal.directconnectivity.IAddressCache; -import com.azure.data.cosmos.internal.directconnectivity.Protocol; import com.azure.data.cosmos.internal.routing.CollectionRoutingMap; import com.azure.data.cosmos.internal.routing.IServerIdentity; import com.azure.data.cosmos.internal.routing.InMemoryCollectionRoutingMap; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java index a5e6788486ae5..ce6f3a44a13fb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java @@ -23,17 +23,14 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.internal.directconnectivity.BarrierRequestHelper; +import com.azure.data.cosmos.internal.AsyncDocumentClient; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.internal.HttpConstants; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import com.azure.data.cosmos.internal.OperationType; import com.azure.data.cosmos.internal.ResourceType; import com.azure.data.cosmos.internal.RxDocumentClientImpl; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.directconnectivity.BarrierRequestHelper; -import com.azure.data.cosmos.internal.directconnectivity.WFConstants; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; import com.azure.data.cosmos.internal.TestConfigurations; import org.testng.annotations.DataProvider; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java index c0d7ddf54c1af..f73b6db88a505 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java @@ -25,9 +25,8 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.RequestRateTooLargeException; -import com.azure.data.cosmos.internal.directconnectivity.*; import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.NotFoundException; import com.google.common.collect.ImmutableList; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java index 29df907718c12..3087a4e2cca0e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java @@ -23,8 +23,7 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.internal.directconnectivity.*; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.internal.Configs; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; import org.mockito.Mockito; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java index 3713bb9e7fd5d..46148fd7214c4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java @@ -24,12 +24,9 @@ package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.PartitionKeyRangeGoneException; import com.azure.data.cosmos.RequestTimeoutException; -import com.azure.data.cosmos.internal.directconnectivity.AddressSelector; -import com.azure.data.cosmos.internal.directconnectivity.ConsistencyWriter; -import com.azure.data.cosmos.internal.directconnectivity.GatewayServiceConfigurationReader; import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.PartitionIsMigratingException; import com.azure.data.cosmos.PartitionKeyRangeIsSplittingException; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java index 9230206614d4c..0ae3b193740dd 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java @@ -22,14 +22,14 @@ */ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.internal.AsyncDocumentClient.Builder; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; @@ -47,7 +47,6 @@ import com.azure.data.cosmos.internal.FeedResponseListValidator; import com.azure.data.cosmos.internal.ResourceResponseValidator; import com.azure.data.cosmos.internal.TestConfigurations; -import com.azure.data.cosmos.internal.directconnectivity.Protocol; import org.mockito.stubbing.Answer; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java index cb0f54695e096..c6e7fc457f412 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java @@ -22,14 +22,13 @@ */ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.internal.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient.Builder; import com.azure.data.cosmos.internal.*; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.internal.directconnectivity.*; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpClientConfig; import com.azure.data.cosmos.internal.routing.PartitionKeyRangeIdentity; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java index d530ec3177379..99ce070900378 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java @@ -23,15 +23,14 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.internal.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient.Builder; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.DatabaseAccount; +import com.azure.data.cosmos.internal.DatabaseAccount; import com.azure.data.cosmos.internal.BaseAuthorizationTokenProvider; import com.azure.data.cosmos.internal.SpyClientUnderTestFactory; import com.azure.data.cosmos.internal.TestSuiteBase; -import com.azure.data.cosmos.internal.directconnectivity.GatewayServiceConfigurationReader; import com.azure.data.cosmos.internal.http.HttpClient; import com.azure.data.cosmos.internal.http.HttpHeaders; import com.azure.data.cosmos.internal.http.HttpRequest; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java index 9b0c4968078c3..9d97801ce09eb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java @@ -24,9 +24,8 @@ package com.azure.data.cosmos.internal.directconnectivity; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.DatabaseAccount; +import com.azure.data.cosmos.internal.DatabaseAccount; import com.azure.data.cosmos.internal.ReplicationPolicy; -import com.azure.data.cosmos.internal.directconnectivity.GatewayServiceConfigurationReader; import org.mockito.Mockito; import reactor.core.publisher.Mono; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java index 1847d8e817f8e..a6a05b430d380 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.internal.PartitionKeyRange; import com.azure.data.cosmos.internal.GlobalEndpointManager; import com.azure.data.cosmos.internal.IAuthorizationTokenProvider; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java index 7e3ddece36567..b93d46d986bde 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.CommonsBridgeInternal; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PartitionKind; -import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Undefined; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.routing.PartitionKeyInternal; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java index 8c56da5cc5757..d793868d99213 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; -import com.azure.data.cosmos.Undefined; +import com.azure.data.cosmos.internal.Undefined; import com.azure.data.cosmos.internal.RMResources; import com.azure.data.cosmos.internal.routing.PartitionKeyInternalHelper; import com.google.common.collect.ImmutableList; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java index 639888ddb5e2c..a502c26de2419 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.internal.*; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableList; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java index 814cac509c1dc..a3fd8b6a3e4ef 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java @@ -23,7 +23,7 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.internal.RxDocumentClientImpl; import com.azure.data.cosmos.internal.http.HttpClient; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java index 78d5352117376..5891bde18a51b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java @@ -26,9 +26,8 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.GoneException; -import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.ServiceUnavailableException; -import com.azure.data.cosmos.internal.directconnectivity.StoreReader; import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.InvalidPartitionException; import io.reactivex.subscribers.TestSubscriber; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java index eb8270a92a447..af3c084974043 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java @@ -26,10 +26,9 @@ import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.GoneException; -import com.azure.data.cosmos.ISessionContainer; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.PartitionKeyRangeGoneException; import com.azure.data.cosmos.RequestRateTooLargeException; -import com.azure.data.cosmos.internal.directconnectivity.StoreReader; import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.NotFoundException; import com.azure.data.cosmos.PartitionIsMigratingException; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java index 9a643567cd604..8577010c40243 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java @@ -23,12 +23,8 @@ package com.azure.data.cosmos.internal.directconnectivity; -import com.azure.data.cosmos.ISessionContainer; -import com.azure.data.cosmos.internal.directconnectivity.AddressSelector; -import com.azure.data.cosmos.internal.directconnectivity.ReadMode; -import com.azure.data.cosmos.internal.directconnectivity.StoreReader; +import com.azure.data.cosmos.internal.ISessionContainer; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; -import com.azure.data.cosmos.internal.directconnectivity.*; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.tuple.Pair; import reactor.core.publisher.Mono; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java index 57854fe55438b..ae5f57aa55a93 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java @@ -25,7 +25,7 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.CosmosError; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.PartitionKeyRange; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java index b8ec8137b1094..3260d52d6f2e4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java @@ -24,7 +24,7 @@ package com.azure.data.cosmos.internal.query; import com.azure.data.cosmos.ChangeFeedOptions; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.RxDocumentServiceRequest; diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java b/sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java index 0ce61cf39f4d7..a61f303c754e6 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java @@ -26,9 +26,9 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.BridgeUtils; import com.azure.data.cosmos.ConnectionPolicy; -import com.azure.data.cosmos.DatabaseAccount; -import com.azure.data.cosmos.DatabaseAccountLocation; -import com.azure.data.cosmos.DatabaseAccountManagerInternal; +import com.azure.data.cosmos.internal.DatabaseAccount; +import com.azure.data.cosmos.internal.DatabaseAccountLocation; +import com.azure.data.cosmos.internal.DatabaseAccountManagerInternal; import com.azure.data.cosmos.internal.*; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java index ebfcfceede647..f206d107c2283 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java @@ -27,7 +27,7 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosItemProperties; -import com.azure.data.cosmos.Document; +import com.azure.data.cosmos.internal.Document; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.FeedResponseListValidator; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java index 1c69d9c4d6a3b..91b1a8d53952c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java @@ -186,10 +186,9 @@ public void query(String query, int maxItemCount, int maxExpectedBufferedCountFo @BeforeClass(groups = { "long" }, timeOut = SETUP_TIMEOUT) public void beforeClass() { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); - options.offerThroughput(20000); client = new ClientUnderTestBuilder(clientBuilder()).build(); createdDatabase = getSharedCosmosDatabase(client); - createdCollection = createCollection(createdDatabase, getCollectionDefinition(), options); + createdCollection = createCollection(createdDatabase, getCollectionDefinition(), options, 20000); ArrayList docDefList = new ArrayList<>(); for(int i = 0; i < numberOfDocs; i++) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java index 103eb852b99b3..fca0b1e68e5d2 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java @@ -88,7 +88,7 @@ public void readFeed() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(1); options.enableCrossPartitionQuery(true); - Flux> queryObservable = createdCollection.listItems(options); + Flux> queryObservable = createdCollection.readAllItems(options); RxDocumentClientUnderTest rxClient = (RxDocumentClientUnderTest)CosmosBridgeInternal.getAsyncDocumentClient(client); rxClient.httpRequests.clear(); @@ -165,11 +165,10 @@ public void query() throws Exception { public void beforeClass() throws Exception { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); - options.offerThroughput(1000); client = new ClientUnderTestBuilder(clientBuilder()).build(); createdDatabase = getSharedCosmosDatabase(client); - createdCollection = createCollection(createdDatabase, getSinglePartitionCollectionDefinition(), options); + createdCollection = createCollection(createdDatabase, getSinglePartitionCollectionDefinition(), options, 1000); RxDocumentClientUnderTest rxClient = (RxDocumentClientUnderTest)CosmosBridgeInternal.getAsyncDocumentClient(client); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java index e4b1e477552dd..136a4789f6ee5 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java @@ -244,7 +244,7 @@ public void afterMethod() { @AfterClass(groups = { "emulator" }, timeOut = 2 * SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { // try { -// client.listDatabases() +// client.readAllDatabases() // .flatMap(cosmosDatabaseSettingsFeedResponse -> reactor.core.publisher.Flux.fromIterable(cosmosDatabaseSettingsFeedResponse.results())) // .flatMap(cosmosDatabaseSettings -> { // CosmosDatabase cosmosDatabase = client.getDatabase(cosmosDatabaseSettings.id()); @@ -281,15 +281,13 @@ private CosmosItemProperties getDocumentDefinition() { private CosmosContainer createFeedCollection() { CosmosContainerRequestOptions optionsFeedCollection = new CosmosContainerRequestOptions(); - optionsFeedCollection.offerThroughput(10100); - return createCollection(createdDatabase, getCollectionDefinition(), optionsFeedCollection); + return createCollection(createdDatabase, getCollectionDefinition(), optionsFeedCollection, 10100); } private CosmosContainer createLeaseCollection() { CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); - options.offerThroughput(400); CosmosContainerProperties collectionDefinition = new CosmosContainerProperties(UUID.randomUUID().toString(), "/id"); - return createCollection(createdDatabase, collectionDefinition, options); + return createCollection(createdDatabase, collectionDefinition, options, 400); } private static synchronized void processItem(CosmosItemProperties item) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java index 1d7fe9736be5c..60c81ce3ac11e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java @@ -22,12 +22,12 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ChangeFeedOptions; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java index 24e525a20d7cf..63de9f5e16f36 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java @@ -38,7 +38,7 @@ import com.azure.data.cosmos.CosmosItemRequestOptions; import com.azure.data.cosmos.CosmosItemResponse; import com.azure.data.cosmos.CosmosResponseValidator; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.IndexingMode; import com.azure.data.cosmos.IndexingPolicy; import com.azure.data.cosmos.PartitionKey; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java index 4c4e502b7bc2c..62d6d330a21b4 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java @@ -58,7 +58,7 @@ public void readConflicts_toBlocking_toIterator() { FeedOptions options = new FeedOptions(); options.maxItemCount(requestPageSize); - Flux> conflictReadFeedFlux = createdCollection.listConflicts(options); + Flux> conflictReadFeedFlux = createdCollection.readAllConflicts(options); Iterator> it = conflictReadFeedFlux.toIterable().iterator(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java index 13ad6ed077108..131a83dfeba3c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java @@ -22,11 +22,11 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.AsyncDocumentClient.Builder; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient.Builder; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.internal.*; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java index 7cc185e867544..f6fe31df0045b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java @@ -22,10 +22,10 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.AsyncDocumentClient; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.internal.*; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.internal.TestSuiteBase; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java index b671e35bcf8e9..4dae14a588277 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java @@ -400,7 +400,7 @@ public void queryDocumentsWithInvalidOrderByContinuationTokensString(String sort public CosmosItemProperties createDocument(CosmosContainer cosmosContainer, Map keyValueProps) throws CosmosClientException { CosmosItemProperties docDefinition = getDocumentDefinition(keyValueProps); - return cosmosContainer.createItem(docDefinition, new CosmosItemProperties()).block().properties(); + return cosmosContainer.createItem(docDefinition).block().properties(); } public List bulkInsert(CosmosContainer cosmosContainer, List> keyValuePropsList) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java index e7b8a697d8a96..3bfcaa3679bc8 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java @@ -334,7 +334,7 @@ public CosmosItemProperties createDocument(CosmosContainer cosmosContainer, int CosmosItemProperties docDefinition = getDocumentDefinition(cnt); - return cosmosContainer.createItem(docDefinition, new CosmosItemProperties()).block().properties(); + return cosmosContainer.createItem(docDefinition).block().properties(); } private void queryWithContinuationTokensAndPageSizes(String query, int[] pageSizes, List expectedDocs) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java index c734b0c7bb639..bf24efffd94ab 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java @@ -22,11 +22,11 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.CosmosClientException; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.internal.*; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PermissionMode; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java index fa12d9f70a001..0cba3b0535bca 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java @@ -69,7 +69,7 @@ public void readCollections() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdDatabase.listContainers(options); + Flux> feedObservable = createdDatabase.readAllContainers(options); int expectedPageSize = (createdCollections.size() + options.maxItemCount() - 1) / options.maxItemCount(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java index d450701123a01..3aebc3b916975 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java @@ -60,7 +60,7 @@ public void readDatabases() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = client.listDatabases(options); + Flux> feedObservable = client.readAllDatabases(options); int expectedPageSize = (allDatabases.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() @@ -77,7 +77,7 @@ public void readDatabases() throws Exception { @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void beforeClass() throws URISyntaxException { client = clientBuilder().build(); - allDatabases = client.listDatabases(null) + allDatabases = client.readAllDatabases(null) .map(frp -> frp.results()) .collectList() .map(list -> list.stream().flatMap(x -> x.stream()).collect(Collectors.toList())) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java index ffbf27c83ed3a..eee99f3003f1c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java @@ -63,7 +63,7 @@ public void readDocuments() { options.enableCrossPartitionQuery(true); options.maxItemCount(2); - Flux> feedObservable = createdCollection.listItems(options); + Flux> feedObservable = createdCollection.readAllItems(options); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() .totalSize(createdDocuments.size()) .numberOfPagesIsGreaterThanOrEqualTo(1) @@ -81,7 +81,7 @@ public void readDocuments_withoutEnableCrossPartitionQuery() { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdCollection.listItems(options); + Flux> feedObservable = createdCollection.readAllItems(options); FailureValidator validator = FailureValidator.builder().instanceOf(CosmosClientException.class) .statusCode(400) .errorMessageContains("Cross partition query is required but disabled." + diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java index 7dc535fd7c78c..623bbd1090ffa 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java @@ -25,7 +25,6 @@ import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; -import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosDatabaseProperties; import com.azure.data.cosmos.FeedResponse; import io.reactivex.subscribers.TestSubscriber; @@ -65,9 +64,9 @@ public void readFeedException() throws Exception { .mergeWith(Flux.fromIterable(frps)); final CosmosClient mockClient = Mockito.spy(client); - Mockito.when(mockClient.listDatabases(null)).thenReturn(response); + Mockito.when(mockClient.readAllDatabases(null)).thenReturn(response); TestSubscriber> subscriber = new TestSubscriber>(); - mockClient.listDatabases(null).subscribe(subscriber); + mockClient.readAllDatabases(null).subscribe(subscriber); assertThat(subscriber.valueCount()).isEqualTo(2); assertThat(subscriber.assertNotComplete()); assertThat(subscriber.assertTerminated()); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java index dc3bfeb1a23a6..69fd0cd1a5028 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java @@ -22,10 +22,10 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.AsyncDocumentClient; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.internal.*; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKeyDefinition; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java index daff264fc38e0..7581457b333eb 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java @@ -22,8 +22,8 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.AsyncDocumentClient; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.AsyncDocumentClient; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.internal.*; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java index 80096c246f619..0b5150755c89d 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java @@ -22,7 +22,7 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.CosmosBridgeInternal; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java index 416b310838ca8..144e5c6e7c1c0 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java @@ -61,7 +61,7 @@ public void readStoredProcedures() throws Exception { options.maxItemCount(2); Flux> feedObservable = createdCollection.getScripts() - .listStoredProcedures(options); + .readAllStoredProcedures(options); int expectedPageSize = (createdStoredProcedures.size() + options.maxItemCount() - 1) / options.maxItemCount(); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java index da71bc3506dcf..18d106d58135c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java @@ -25,7 +25,6 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosTriggerProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; @@ -62,7 +61,7 @@ public void readTriggers() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdCollection.getScripts().listTriggers(options); + Flux> feedObservable = createdCollection.getScripts().readAllTriggers(options); int expectedPageSize = (createdTriggers.size() + options.maxItemCount() - 1) / options.maxItemCount(); @@ -101,6 +100,6 @@ public CosmosTriggerProperties createTriggers(CosmosContainer cosmosContainer) { trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - return cosmosContainer.getScripts().createTrigger(trigger, new CosmosRequestOptions()).block().properties(); + return cosmosContainer.getScripts().createTrigger(trigger).block().properties(); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java index c53783e06ca10..687ab8268640e 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java @@ -25,9 +25,8 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosUserDefinedFunctionProperties; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.FeedResponseListValidator; @@ -63,7 +62,7 @@ public void readUserDefinedFunctions() throws Exception { options.maxItemCount(2); Flux> feedObservable = createdCollection.getScripts() - .listUserDefinedFunctions(options); + .readAllUserDefinedFunctions(options); int expectedPageSize = (createdUserDefinedFunctions.size() + options.maxItemCount() - 1) / options.maxItemCount(); @@ -101,8 +100,8 @@ public CosmosUserDefinedFunctionProperties createUserDefinedFunctions(CosmosCont CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); - return cosmosContainer.getScripts().createUserDefinedFunction(udf, new CosmosRequestOptions()).block() - .settings(); + return cosmosContainer.getScripts().createUserDefinedFunction(udf).block() + .properties(); } private String getCollectionLink() { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java index 50ab2ff1c57ff..47331a6725f96 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java @@ -31,7 +31,6 @@ import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.FeedResponseListValidator; import com.azure.data.cosmos.internal.FeedResponseValidator; -import com.azure.data.cosmos.internal.RequestOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -62,7 +61,7 @@ public void readUsers() throws Exception { FeedOptions options = new FeedOptions(); options.maxItemCount(2); - Flux> feedObservable = createdDatabase.listUsers(options); + Flux> feedObservable = createdDatabase.readAllUsers(options); int expectedPageSize = (createdUsers.size() + options.maxItemCount() - 1) / options.maxItemCount(); @@ -97,6 +96,6 @@ public void afterClass() { public CosmosUserProperties createUsers(CosmosDatabase cosmosDatabase) { CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); - return cosmosDatabase.createUser(user, new RequestOptions()).block().settings(); + return cosmosDatabase.createUser(user).block().properties(); } } diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java index aa7472cd620f0..388b03cd7ca3b 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java @@ -22,13 +22,13 @@ */ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.internal.*; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.Document; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.PartitionKey; import com.azure.data.cosmos.PartitionKeyDefinition; import com.azure.data.cosmos.PermissionMode; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java index 01f3614e156a3..56e4cbe282812 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java @@ -28,7 +28,7 @@ import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemRequestOptions; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.SqlParameter; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java index afe1a849b8e30..af1a5ab29b591 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java @@ -58,7 +58,7 @@ public void readDocuments() { final FeedOptions options = new FeedOptions(); options.enableCrossPartitionQuery(true); options.maxItemCount(2); - final Flux> feedObservable = createdCollection.listItems(options); + final Flux> feedObservable = createdCollection.readAllItems(options); final int expectedPageSize = (createdDocuments.size() + options.maxItemCount() - 1) / options.maxItemCount(); FeedResponseListValidator validator = new FeedResponseListValidator.Builder() diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java index 5639ef21df480..b4370517e7074 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java @@ -28,11 +28,10 @@ import com.azure.data.cosmos.CosmosContainer; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosStoredProcedure; +import com.azure.data.cosmos.CosmosStoredProcedureProperties; import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; import com.azure.data.cosmos.CosmosStoredProcedureResponse; -import com.azure.data.cosmos.CosmosStoredProcedureProperties; import com.azure.data.cosmos.PartitionKey; -import com.azure.data.cosmos.internal.RequestOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -79,7 +78,7 @@ public void replaceStoredProcedure() throws Exception { readBackSp.body("function() {var x = 11;}"); Mono replaceObservable = createdCollection.getScripts() - .getStoredProcedure(readBackSp.id()).replace(readBackSp, new RequestOptions()); + .getStoredProcedure(readBackSp.id()).replace(readBackSp); // validate stored procedure replace CosmosResponseValidator validatorForReplace = new CosmosResponseValidator.Builder() @@ -103,8 +102,8 @@ public void executeStoredProcedure() throws Exception { String result = null; - RequestOptions options = new RequestOptions(); - options.setPartitionKey(PartitionKey.None); + CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions(); + options.partitionKey(PartitionKey.None); result = storedProcedure.execute(null, options).block().responseAsString(); assertThat(result).isEqualTo("\"0123456789\""); diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java index ddeddd6008e2c..2495347ac1169 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java @@ -43,9 +43,9 @@ import com.azure.data.cosmos.CosmosItem; import com.azure.data.cosmos.CosmosItemProperties; import com.azure.data.cosmos.CosmosItemResponse; -import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponse; import com.azure.data.cosmos.CosmosResponseValidator; +import com.azure.data.cosmos.CosmosStoredProcedureRequestOptions; import com.azure.data.cosmos.CosmosUser; import com.azure.data.cosmos.CosmosUserProperties; import com.azure.data.cosmos.DataType; @@ -59,8 +59,13 @@ import com.azure.data.cosmos.Resource; import com.azure.data.cosmos.RetryOptions; import com.azure.data.cosmos.SqlQuerySpec; +import com.azure.data.cosmos.internal.Configs; +import com.azure.data.cosmos.internal.FailureValidator; +import com.azure.data.cosmos.internal.FeedResponseListValidator; +import com.azure.data.cosmos.internal.PathParser; +import com.azure.data.cosmos.internal.TestConfigurations; +import com.azure.data.cosmos.internal.Utils; import com.azure.data.cosmos.internal.directconnectivity.Protocol; -import com.azure.data.cosmos.internal.*; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -87,6 +92,8 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import static com.azure.data.cosmos.BridgeInternal.extractConfigs; +import static com.azure.data.cosmos.BridgeInternal.injectConfigs; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.spy; @@ -199,11 +206,9 @@ public static void beforeSuite() { CosmosDatabaseForTest dbForTest = CosmosDatabaseForTest.create(DatabaseManagerImpl.getInstance(houseKeepingClient)); SHARED_DATABASE = dbForTest.createdDatabase; CosmosContainerRequestOptions options = new CosmosContainerRequestOptions(); - options.offerThroughput(10100); - SHARED_MULTI_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options); + SHARED_MULTI_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options, 10100); SHARED_MULTI_PARTITION_COLLECTION_WITH_COMPOSITE_AND_SPATIAL_INDEXES = createCollection(SHARED_DATABASE, getCollectionDefinitionMultiPartitionWithCompositeAndSpatialIndexes(), options); - options.offerThroughput(6000); - SHARED_SINGLE_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options); + SHARED_SINGLE_PARTITION_COLLECTION = createCollection(SHARED_DATABASE, getCollectionDefinitionWithRangeRangeIndex(), options, 6000); } } @@ -252,14 +257,12 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(trigger -> { - CosmosRequestOptions requestOptions = new CosmosRequestOptions(); - // if (paths != null && !paths.isEmpty()) { // Object propertyValue = trigger.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getScripts().getTrigger(trigger.id()).delete(requestOptions); + return cosmosContainer.getScripts().getTrigger(trigger.id()).delete(); }).then().block(); logger.info("Truncating collection {} storedProcedures ...", cosmosContainerId); @@ -268,14 +271,13 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(storedProcedure -> { - CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = storedProcedure.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getScripts().getStoredProcedure(storedProcedure.id()).delete(requestOptions); + return cosmosContainer.getScripts().getStoredProcedure(storedProcedure.id()).delete(new CosmosStoredProcedureRequestOptions()); }).then().block(); logger.info("Truncating collection {} udfs ...", cosmosContainerId); @@ -284,21 +286,20 @@ protected static void truncateCollection(CosmosContainer cosmosContainer) { .publishOn(Schedulers.parallel()) .flatMap(page -> Flux.fromIterable(page.results())) .flatMap(udf -> { - CosmosRequestOptions requestOptions = new CosmosRequestOptions(); // if (paths != null && !paths.isEmpty()) { // Object propertyValue = udf.getObjectByPath(PathParser.getPathParts(paths.get(0))); // requestOptions.partitionKey(new PartitionKey(propertyValue)); // } - return cosmosContainer.getScripts().getUserDefinedFunction(udf.id()).delete(requestOptions); + return cosmosContainer.getScripts().getUserDefinedFunction(udf.id()).delete(); }).then().block(); logger.info("Finished truncating collection {}.", cosmosContainerId); } protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clientBuilder) { - switch (clientBuilder.getDesiredConsistencyLevel()) { + switch (clientBuilder.consistencyLevel()) { case EVENTUAL: case CONSISTENT_PREFIX: logger.info(" additional wait in EVENTUAL mode so the replica catch up"); @@ -317,6 +318,11 @@ protected static void waitIfNeededForReplicasToCatchUp(CosmosClientBuilder clien } } + public static CosmosContainer createCollection(CosmosDatabase database, CosmosContainerProperties cosmosContainerProperties, + CosmosContainerRequestOptions options, int throughput) { + return database.createContainer(cosmosContainerProperties, throughput, options).block().container(); + } + public static CosmosContainer createCollection(CosmosDatabase database, CosmosContainerProperties cosmosContainerProperties, CosmosContainerRequestOptions options) { return database.createContainer(cosmosContainerProperties, options).block().container(); @@ -590,7 +596,7 @@ public static void deleteUserIfExists(CosmosClient client, String databaseId, St } public static void deleteUser(CosmosDatabase database, String userId) { - database.getUser(userId).read().block().user().delete(null).block(); + database.getUser(userId).read().block().user().delete().block(); } static private CosmosDatabase safeCreateDatabase(CosmosClient client, CosmosDatabaseProperties databaseSettings) { @@ -627,7 +633,7 @@ static protected void safeDeleteDatabase(CosmosDatabase database) { static protected void safeDeleteAllCollections(CosmosDatabase database) { if (database != null) { - List collections = database.listContainers() + List collections = database.readAllContainers() .flatMap(p -> Flux.fromIterable(p.results())) .collectList() .block(); @@ -830,9 +836,9 @@ private static Object[][] simpleClientBuildersWithDirect(Protocol... protocols) } cosmosConfigurations.forEach(c -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", - c.getConnectionPolicy().connectionMode(), - c.getDesiredConsistencyLevel(), - c.getConfigs().getProtocol() + c.connectionPolicy().connectionMode(), + c.consistencyLevel(), + extractConfigs(c).getProtocol() )); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, false, null)); @@ -921,9 +927,9 @@ private static Object[][] clientBuildersWithDirect(List testCo } cosmosConfigurations.forEach(c -> logger.info("Will Use ConnectionMode [{}], Consistency [{}], Protocol [{}]", - c.getConnectionPolicy().connectionMode(), - c.getDesiredConsistencyLevel(), - c.getConfigs().getProtocol() + c.connectionPolicy().connectionMode(), + c.consistencyLevel(), + extractConfigs(c).getProtocol() )); cosmosConfigurations.add(createGatewayRxDocumentClient(ConsistencyLevel.SESSION, isMultiMasterEnabled, preferredLocations)); @@ -976,11 +982,12 @@ static protected CosmosClientBuilder createDirectRxDocumentClient(ConsistencyLev Configs configs = spy(new Configs()); doAnswer((Answer)invocation -> protocol).when(configs).getProtocol(); - return CosmosClient.builder().endpoint(TestConfigurations.HOST) + CosmosClientBuilder builder = CosmosClient.builder().endpoint(TestConfigurations.HOST) .key(TestConfigurations.MASTER_KEY) .connectionPolicy(connectionPolicy) - .consistencyLevel(consistencyLevel) - .configs(configs); + .consistencyLevel(consistencyLevel); + + return injectConfigs(builder, configs); } protected int expectedNumberOfPages(int totalExpectedResult, int maxPageSize) { diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java index 3a50d0b52e9d8..597ad47ca7f67 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java @@ -23,16 +23,16 @@ package com.azure.data.cosmos.rx; -import com.azure.data.cosmos.AsyncDocumentClient; +import com.azure.data.cosmos.internal.AsyncDocumentClient; import com.azure.data.cosmos.BridgeInternal; import com.azure.data.cosmos.ChangeFeedOptions; import com.azure.data.cosmos.ConnectionMode; import com.azure.data.cosmos.ConnectionPolicy; import com.azure.data.cosmos.ConsistencyLevel; import com.azure.data.cosmos.CosmosResourceType; -import com.azure.data.cosmos.Database; -import com.azure.data.cosmos.Document; -import com.azure.data.cosmos.DocumentCollection; +import com.azure.data.cosmos.internal.Database; +import com.azure.data.cosmos.internal.Document; +import com.azure.data.cosmos.internal.DocumentCollection; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.PartitionKey; diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java index 1f46ecdcb91d5..f152077f4d19a 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java @@ -25,13 +25,11 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponse; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosTrigger; import com.azure.data.cosmos.CosmosTriggerProperties; import com.azure.data.cosmos.CosmosTriggerResponse; -import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; import org.testng.annotations.AfterClass; @@ -62,7 +60,7 @@ public void createTrigger() throws Exception { trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - Mono createObservable = createdCollection.getScripts().createTrigger(trigger, new CosmosRequestOptions()); + Mono createObservable = createdCollection.getScripts().createTrigger(trigger); // validate trigger creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -82,11 +80,11 @@ public void readTrigger() throws Exception { trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - CosmosTrigger readBackTrigger = createdCollection.getScripts().createTrigger(trigger, new CosmosRequestOptions()).block().trigger(); + CosmosTrigger readBackTrigger = createdCollection.getScripts().createTrigger(trigger).block().trigger(); // read trigger waitIfNeededForReplicasToCatchUp(clientBuilder()); - Mono readObservable = readBackTrigger.read(new RequestOptions()); + Mono readObservable = readBackTrigger.read(); // validate read trigger CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -106,10 +104,10 @@ public void deleteTrigger() throws Exception { trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - CosmosTrigger readBackTrigger = createdCollection.getScripts().createTrigger(trigger, new CosmosRequestOptions()).block().trigger(); + CosmosTrigger readBackTrigger = createdCollection.getScripts().createTrigger(trigger).block().trigger(); // delete trigger - Mono deleteObservable = readBackTrigger.delete(new CosmosRequestOptions()); + Mono deleteObservable = readBackTrigger.delete(); // validate delete trigger CosmosResponseValidator validator = new CosmosResponseValidator.Builder() diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java index 957853b757d74..f0fd9b6785f0c 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java @@ -26,7 +26,6 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosTriggerProperties; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; @@ -152,7 +151,7 @@ public void invalidQuerySytax() throws Exception { public CosmosTriggerProperties createTrigger(CosmosContainer cosmosContainer) { CosmosTriggerProperties storedProcedure = getTriggerDef(); - return cosmosContainer.getScripts().createTrigger(storedProcedure, new CosmosRequestOptions()).block().properties(); + return cosmosContainer.getScripts().createTrigger(storedProcedure).block().properties(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java index 353f2315d14a0..39f0c0addc345 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java @@ -25,11 +25,9 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosTriggerProperties; import com.azure.data.cosmos.CosmosTriggerResponse; -import com.azure.data.cosmos.internal.RequestOptions; import com.azure.data.cosmos.TriggerOperation; import com.azure.data.cosmos.TriggerType; import org.testng.annotations.AfterClass; @@ -60,11 +58,11 @@ public void replaceTrigger() throws Exception { trigger.body("function() {var x = 10;}"); trigger.triggerOperation(TriggerOperation.CREATE); trigger.triggerType(TriggerType.PRE); - CosmosTriggerProperties readBackTrigger = createdCollection.getScripts().createTrigger(trigger, new CosmosRequestOptions()).block().properties(); + CosmosTriggerProperties readBackTrigger = createdCollection.getScripts().createTrigger(trigger).block().properties(); // read trigger to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder()); - Mono readObservable = createdCollection.getScripts().getTrigger(readBackTrigger.id()).read(new RequestOptions()); + Mono readObservable = createdCollection.getScripts().getTrigger(readBackTrigger.id()).read(); // validate trigger creation CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() @@ -78,7 +76,7 @@ public void replaceTrigger() throws Exception { //update trigger readBackTrigger.body("function() {var x = 11;}"); - Mono updateObservable = createdCollection.getScripts().getTrigger(readBackTrigger.id()).replace(readBackTrigger, new RequestOptions()); + Mono updateObservable = createdCollection.getScripts().getTrigger(readBackTrigger.id()).replace(readBackTrigger); // validate trigger replace CosmosResponseValidator validatorForUpdate = new CosmosResponseValidator.Builder() diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java index a408063fd2f2f..61f47f895a7af 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java @@ -59,7 +59,7 @@ public void createUser() throws Exception { CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); - Mono createObservable = createdDatabase.createUser(user, null); + Mono createObservable = createdDatabase.createUser(user); // validate user creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -76,10 +76,10 @@ public void readUser() throws Exception { CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); - CosmosUser readBackUser = createdDatabase.createUser(user, null).block().user(); + CosmosUser readBackUser = createdDatabase.createUser(user).block().user(); // read user - Mono readObservable = readBackUser.read(null); + Mono readObservable = readBackUser.read(); //validate user read CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -96,10 +96,10 @@ public void deleteUser() throws Exception { CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); - CosmosUser readBackUser = createdDatabase.createUser(user, null).block().user(); + CosmosUser readBackUser = createdDatabase.createUser(user).block().user(); // delete user - Mono deleteObservable = readBackUser.delete(null); + Mono deleteObservable = readBackUser.delete(); // validate user delete CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -108,7 +108,7 @@ public void deleteUser() throws Exception { validateSuccess(deleteObservable, validator); // attempt to read the user which was deleted - Mono readObservable = readBackUser.read(null); + Mono readObservable = readBackUser.read(); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); validateFailure(readObservable, notFoundValidator); } @@ -120,7 +120,7 @@ public void upsertUser() throws Exception { CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); - Mono upsertObservable = createdDatabase.upsertUser(user, null); + Mono upsertObservable = createdDatabase.upsertUser(user); //validate user upsert CosmosResponseValidator validatorForUpsert = new CosmosResponseValidator.Builder() @@ -138,7 +138,7 @@ public void replaceUser() throws Exception { CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); - CosmosUserProperties readBackUser = createdDatabase.createUser(user, null).block().settings(); + CosmosUserProperties readBackUser = createdDatabase.createUser(user).block().properties(); // read user to validate creation Mono readObservable = createdDatabase.getUser(user.id()).read(); @@ -155,7 +155,7 @@ public void replaceUser() throws Exception { String oldId = readBackUser.id(); readBackUser.id(UUID.randomUUID().toString()); - Mono updateObservable = createdDatabase.getUser(oldId).replace(readBackUser, null); + Mono updateObservable = createdDatabase.getUser(oldId).replace(readBackUser); // validate user replace CosmosResponseValidator validatorForUpdate = new CosmosResponseValidator.Builder() diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java index f3dcf66396ca1..d00e74ac9f499 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java @@ -25,7 +25,6 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponse; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosUserDefinedFunction; @@ -56,7 +55,7 @@ public void createUserDefinedFunction() throws Exception { udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); - Mono createObservable = createdCollection.getScripts().createUserDefinedFunction(udf, new CosmosRequestOptions()); + Mono createObservable = createdCollection.getScripts().createUserDefinedFunction(udf); // validate udf creation CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -73,11 +72,11 @@ public void readUserDefinedFunction() throws Exception { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); - CosmosUserDefinedFunction readBackUdf = createdCollection.getScripts().createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); + CosmosUserDefinedFunction readBackUdf = createdCollection.getScripts().createUserDefinedFunction(udf).block().userDefinedFunction(); // read udf waitIfNeededForReplicasToCatchUp(clientBuilder()); - Mono readObservable = readBackUdf.read(null); + Mono readObservable = readBackUdf.read(); //validate udf read CosmosResponseValidator validator = new CosmosResponseValidator.Builder() @@ -94,10 +93,10 @@ public void deleteUserDefinedFunction() throws Exception { CosmosUserDefinedFunctionProperties udf = new CosmosUserDefinedFunctionProperties(); udf.id(UUID.randomUUID().toString()); udf.body("function() {var x = 10;}"); - CosmosUserDefinedFunction readBackUdf = createdCollection.getScripts().createUserDefinedFunction(udf, new CosmosRequestOptions()).block().userDefinedFunction(); + CosmosUserDefinedFunction readBackUdf = createdCollection.getScripts().createUserDefinedFunction(udf).block().userDefinedFunction(); // delete udf - Mono deleteObservable = readBackUdf.delete(new CosmosRequestOptions()); + Mono deleteObservable = readBackUdf.delete(); // validate udf delete CosmosResponseValidator validator = new CosmosResponseValidator.Builder() diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java index 4f1fc6f20e8eb..b77d030affd43 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java @@ -26,9 +26,8 @@ import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosClientException; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosUserDefinedFunctionProperties; -import com.azure.data.cosmos.Database; +import com.azure.data.cosmos.internal.Database; import com.azure.data.cosmos.FeedOptions; import com.azure.data.cosmos.FeedResponse; import com.azure.data.cosmos.internal.FailureValidator; @@ -151,7 +150,7 @@ public void invalidQuerySytax() throws Exception { public CosmosUserDefinedFunctionProperties createUserDefinedFunction(CosmosContainer cosmosContainer) { CosmosUserDefinedFunctionProperties storedProcedure = getUserDefinedFunctionDef(); - return cosmosContainer.getScripts().createUserDefinedFunction(storedProcedure, new CosmosRequestOptions()).block().settings(); + return cosmosContainer.getScripts().createUserDefinedFunction(storedProcedure).block().properties(); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java index 34811b0d57da1..3f18c39be096f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java @@ -25,11 +25,9 @@ import com.azure.data.cosmos.CosmosClient; import com.azure.data.cosmos.CosmosClientBuilder; import com.azure.data.cosmos.CosmosContainer; -import com.azure.data.cosmos.CosmosRequestOptions; import com.azure.data.cosmos.CosmosResponseValidator; import com.azure.data.cosmos.CosmosUserDefinedFunctionProperties; import com.azure.data.cosmos.CosmosUserDefinedFunctionResponse; -import com.azure.data.cosmos.internal.RequestOptions; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; @@ -59,11 +57,11 @@ public void replaceUserDefinedFunction() throws Exception { CosmosUserDefinedFunctionProperties readBackUdf = null; - readBackUdf = createdCollection.getScripts().createUserDefinedFunction(udf, new CosmosRequestOptions()).block().settings(); + readBackUdf = createdCollection.getScripts().createUserDefinedFunction(udf).block().properties(); // read udf to validate creation waitIfNeededForReplicasToCatchUp(clientBuilder()); - Mono readObservable = createdCollection.getScripts().getUserDefinedFunction(readBackUdf.id()).read(new RequestOptions()); + Mono readObservable = createdCollection.getScripts().getUserDefinedFunction(readBackUdf.id()).read(); // validate udf creation CosmosResponseValidator validatorForRead = new CosmosResponseValidator.Builder() @@ -76,7 +74,7 @@ public void replaceUserDefinedFunction() throws Exception { //update udf readBackUdf.body("function() {var x = 11;}"); - Mono replaceObservable = createdCollection.getScripts().getUserDefinedFunction(readBackUdf.id()).replace(readBackUdf, new RequestOptions()); + Mono replaceObservable = createdCollection.getScripts().getUserDefinedFunction(readBackUdf.id()).replace(readBackUdf); //validate udf replace CosmosResponseValidator validatorForReplace = new CosmosResponseValidator.Builder() diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java b/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java index 875475db35abb..3845c32f4db0f 100644 --- a/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java +++ b/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java @@ -140,7 +140,7 @@ public void beforeClass() throws Exception { for(int i = 0; i < 5; i++) { CosmosUserProperties user = new CosmosUserProperties(); user.id(UUID.randomUUID().toString()); - createdUsers.add(createUser(client, databaseId, user).read().block().settings()); + createdUsers.add(createUser(client, databaseId, user).read().block().properties()); } waitIfNeededForReplicasToCatchUp(clientBuilder()); From d7fd1e7bbb6bb70efca741bed5442ddcd65ea584 Mon Sep 17 00:00:00 2001 From: Christopher Anderson Date: Fri, 28 Jun 2019 03:44:52 -0700 Subject: [PATCH 58/85] 3.0.0 (#218) --- benchmark/pom.xml | 2 +- examples/pom.xml | 2 +- pom.xml | 8 ++++---- sdk/pom.xml | 2 +- .../com/azure/data/cosmos/internal/HttpConstants.java | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/benchmark/pom.xml b/benchmark/pom.xml index 528436328ce84..491a48a51ee6b 100644 --- a/benchmark/pom.xml +++ b/benchmark/pom.xml @@ -29,7 +29,7 @@ com.microsoft.azure azure-cosmos-parent - 3.0.0-a1-SNAPSHOT + 3.0.0 azure-cosmos-benchmark diff --git a/examples/pom.xml b/examples/pom.xml index 72b825a563ae5..f7c52f9f530e5 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -29,7 +29,7 @@ com.microsoft.azure azure-cosmos-parent - 3.0.0-a1-SNAPSHOT + 3.0.0 azure-cosmos-examples diff --git a/pom.xml b/pom.xml index 053caac4bba66..2c3e793e2c91a 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ 4.0.0 com.microsoft.azure azure-cosmos-parent - 3.0.0-a1-SNAPSHOT + 3.0.0 pom Azure Cosmos DB SQL API Java Async SDK (with Reactive Extension RX support) for Azure Cosmos DB SQL API @@ -45,8 +45,8 @@ 1.6 1.6 1.6 - 3.0.0-a1-SNAPSHOT - 3.0.0-a1-SNAPSHOT + 3.0.0 + 3.0.0 27.0.1-jre 1.3 2.9.8 @@ -60,7 +60,7 @@ 3.2.2.RELEASE Californium-SR7 2.2.4 - 3.0.0-a1-SNAPSHOT + 3.0.0 1.7.6 unit 6.14.3 diff --git a/sdk/pom.xml b/sdk/pom.xml index 6660f0a860581..9481c2952c1b8 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -27,7 +27,7 @@ SOFTWARE. com.microsoft.azure azure-cosmos-parent - 3.0.0-a1-SNAPSHOT + 3.0.0 azure-cosmos Async SDK for SQL API of Azure Cosmos DB Service diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java b/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java index f1af93352ca66..d1a31ecd600af 100644 --- a/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java +++ b/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java @@ -272,7 +272,7 @@ public static class Versions { // TODO: FIXME we can use maven plugin for generating a version file // @see // https://stackoverflow.com/questions/2469922/generate-a-version-java-file-in-maven - public static final String SDK_VERSION = "3.0.0-a1-SNAPSHOT"; + public static final String SDK_VERSION = "3.0.0"; public static final String SDK_NAME = "cosmosdb-java-sdk"; } From bb83ba0a1c7cbb0d3a3d6033a022868111577f91 Mon Sep 17 00:00:00 2001 From: Vinay Gera Date: Tue, 9 Jul 2019 15:59:45 -0400 Subject: [PATCH 59/85] folder restructure --- CODEOWNERS => sdk/cosmos/CODEOWNERS | 0 LICENSE => sdk/cosmos/LICENSE | 0 README.md => sdk/cosmos/README.md | 0 {benchmark => sdk/cosmos/benchmark}/README.md | 0 {benchmark => sdk/cosmos/benchmark}/pom.xml | 0 .../azure/data/cosmos/benchmark/AsyncBenchmark.java | 0 .../data/cosmos/benchmark/AsyncMixedBenchmark.java | 0 .../data/cosmos/benchmark/AsyncQueryBenchmark.java | 0 .../AsyncQuerySinglePartitionMultiple.java | 0 .../data/cosmos/benchmark/AsyncReadBenchmark.java | 0 .../data/cosmos/benchmark/AsyncWriteBenchmark.java | 0 .../azure/data/cosmos/benchmark/Configuration.java | 0 .../com/azure/data/cosmos/benchmark/DocDBUtils.java | 0 .../java/com/azure/data/cosmos/benchmark/Main.java | 0 .../data/cosmos/benchmark/ReadMyWriteWorkflow.java | 0 .../benchmark}/src/main/resources/log4j.properties | 0 .../data/cosmos/benchmark/QueryBuilderTest.java | 0 .../benchmark/ReadMyWritesConsistencyTest.java | 0 .../java/com/azure/data/cosmos/benchmark/Utils.java | 0 .../azure/data/cosmos/benchmark/WorkflowTest.java | 0 {changelog => sdk/cosmos/changelog}/README.md | 0 {examples => sdk/cosmos/examples}/pom.xml | 0 .../azure/data/cosmos/examples/AccountSettings.java | 0 .../com/azure/data/cosmos/examples/BasicDemo.java | 0 .../ChangeFeed/SampleChangeFeedProcessor.java | 0 .../examples/ChangeFeed/SampleConfigurations.java | 0 .../examples/multimaster/ConfigurationManager.java | 0 .../cosmos/rx/examples/multimaster/Helpers.java | 0 .../multimaster/samples/ConflictWorker.java | 0 .../rx/examples/multimaster/samples/Main.java | 0 .../multimaster/samples/MultiMasterScenario.java | 0 .../rx/examples/multimaster/samples/Worker.java | 0 .../examples}/src/main/resources/log4j.properties | 0 .../resources/multi-master-sample-config.properties | 0 .../src/main/resources/resolver-storedproc.txt | 0 .../com/azure/data/cosmos/DocumentClientTest.java | 0 .../rx/examples/CollectionCRUDAsyncAPITest.java | 0 .../data/cosmos/rx/examples/ConflictAPITest.java | 0 .../rx/examples/DatabaseCRUDAsyncAPITest.java | 0 .../rx/examples/DocumentCRUDAsyncAPITest.java | 0 .../rx/examples/DocumentQueryAsyncAPITest.java | 0 .../cosmos/rx/examples/InMemoryGroupbyTest.java | 0 .../cosmos/rx/examples/OfferCRUDAsyncAPITest.java | 0 .../rx/examples/StoredProcedureAsyncAPITest.java | 0 .../data/cosmos/rx/examples/TestConfigurations.java | 0 .../data/cosmos/rx/examples/TokenResolverTest.java | 0 .../cosmos/rx/examples/UniqueIndexAsyncAPITest.java | 0 .../com/azure/data/cosmos/rx/examples/Utils.java | 0 .../examples}/src/test/resources/log4j.properties | 0 {faq => sdk/cosmos/faq}/README.md | 0 pom.xml => sdk/cosmos/pom.xml | 0 sdk/{ => cosmos/sdk}/CosmosConflict | 0 sdk/{ => cosmos/sdk}/pom.xml | 0 .../java/com/azure/data/cosmos/AccessCondition.java | 0 .../com/azure/data/cosmos/AccessConditionType.java | 0 .../com/azure/data/cosmos/BadRequestException.java | 0 .../java/com/azure/data/cosmos/BridgeInternal.java | 0 .../com/azure/data/cosmos/ChangeFeedOptions.java | 0 .../com/azure/data/cosmos/ChangeFeedProcessor.java | 0 .../data/cosmos/ChangeFeedProcessorOptions.java | 0 .../data/cosmos/ClientSideRequestStatistics.java | 0 .../azure/data/cosmos/CommonsBridgeInternal.java | 0 .../java/com/azure/data/cosmos/CompositePath.java | 0 .../azure/data/cosmos/CompositePathSortOrder.java | 0 .../com/azure/data/cosmos/ConflictException.java | 0 .../azure/data/cosmos/ConflictResolutionMode.java | 0 .../azure/data/cosmos/ConflictResolutionPolicy.java | 0 .../java/com/azure/data/cosmos/ConnectionMode.java | 0 .../com/azure/data/cosmos/ConnectionPolicy.java | 0 .../com/azure/data/cosmos/ConsistencyLevel.java | 0 .../com/azure/data/cosmos/ConsistencyPolicy.java | 0 .../com/azure/data/cosmos/CosmosBridgeInternal.java | 0 .../java/com/azure/data/cosmos/CosmosClient.java | 0 .../com/azure/data/cosmos/CosmosClientBuilder.java | 0 .../azure/data/cosmos/CosmosClientException.java | 0 .../java/com/azure/data/cosmos/CosmosConflict.java | 0 .../azure/data/cosmos/CosmosConflictProperties.java | 0 .../data/cosmos/CosmosConflictRequestOptions.java | 0 .../azure/data/cosmos/CosmosConflictResponse.java | 0 .../java/com/azure/data/cosmos/CosmosContainer.java | 0 .../data/cosmos/CosmosContainerProperties.java | 0 .../data/cosmos/CosmosContainerRequestOptions.java | 0 .../azure/data/cosmos/CosmosContainerResponse.java | 0 .../java/com/azure/data/cosmos/CosmosDatabase.java | 0 .../azure/data/cosmos/CosmosDatabaseProperties.java | 0 .../data/cosmos/CosmosDatabaseRequestOptions.java | 0 .../azure/data/cosmos/CosmosDatabaseResponse.java | 0 .../java/com/azure/data/cosmos/CosmosError.java | 0 .../main/java/com/azure/data/cosmos/CosmosItem.java | 0 .../com/azure/data/cosmos/CosmosItemProperties.java | 0 .../azure/data/cosmos/CosmosItemRequestOptions.java | 0 .../com/azure/data/cosmos/CosmosItemResponse.java | 0 .../com/azure/data/cosmos/CosmosPermission.java | 0 .../data/cosmos/CosmosPermissionProperties.java | 0 .../data/cosmos/CosmosPermissionRequestOptions.java | 0 .../azure/data/cosmos/CosmosPermissionResponse.java | 0 .../com/azure/data/cosmos/CosmosResourceType.java | 0 .../java/com/azure/data/cosmos/CosmosResponse.java | 0 .../data/cosmos/CosmosResponseDiagnostics.java | 0 .../java/com/azure/data/cosmos/CosmosScripts.java | 0 .../azure/data/cosmos/CosmosStoredProcedure.java | 0 .../cosmos/CosmosStoredProcedureProperties.java | 0 .../cosmos/CosmosStoredProcedureRequestOptions.java | 0 .../data/cosmos/CosmosStoredProcedureResponse.java | 0 .../java/com/azure/data/cosmos/CosmosTrigger.java | 0 .../azure/data/cosmos/CosmosTriggerProperties.java | 0 .../azure/data/cosmos/CosmosTriggerResponse.java | 0 .../main/java/com/azure/data/cosmos/CosmosUser.java | 0 .../data/cosmos/CosmosUserDefinedFunction.java | 0 .../cosmos/CosmosUserDefinedFunctionProperties.java | 0 .../cosmos/CosmosUserDefinedFunctionResponse.java | 0 .../com/azure/data/cosmos/CosmosUserProperties.java | 0 .../com/azure/data/cosmos/CosmosUserResponse.java | 0 .../main/java/com/azure/data/cosmos/DataType.java | 0 .../java/com/azure/data/cosmos/ExcludedPath.java | 0 .../java/com/azure/data/cosmos/FeedOptions.java | 0 .../java/com/azure/data/cosmos/FeedResponse.java | 0 .../azure/data/cosmos/FeedResponseDiagnostics.java | 0 .../com/azure/data/cosmos/ForbiddenException.java | 0 .../java/com/azure/data/cosmos/GoneException.java | 0 .../main/java/com/azure/data/cosmos/HashIndex.java | 0 .../java/com/azure/data/cosmos/IncludedPath.java | 0 .../src/main/java/com/azure/data/cosmos/Index.java | 0 .../main/java/com/azure/data/cosmos/IndexKind.java | 0 .../com/azure/data/cosmos/IndexingDirective.java | 0 .../java/com/azure/data/cosmos/IndexingMode.java | 0 .../java/com/azure/data/cosmos/IndexingPolicy.java | 0 .../data/cosmos/InternalServerErrorException.java | 0 .../data/cosmos/InvalidPartitionException.java | 0 .../com/azure/data/cosmos/JsonSerializable.java | 0 .../java/com/azure/data/cosmos/LockedException.java | 0 .../data/cosmos/MethodNotAllowedException.java | 0 .../com/azure/data/cosmos/NotFoundException.java | 0 .../data/cosmos/PartitionIsMigratingException.java | 0 .../java/com/azure/data/cosmos/PartitionKey.java | 0 .../azure/data/cosmos/PartitionKeyDefinition.java | 0 .../data/cosmos/PartitionKeyDefinitionVersion.java | 0 .../data/cosmos/PartitionKeyRangeGoneException.java | 0 .../PartitionKeyRangeIsSplittingException.java | 0 .../java/com/azure/data/cosmos/PartitionKind.java | 0 .../java/com/azure/data/cosmos/PermissionMode.java | 0 .../data/cosmos/PreconditionFailedException.java | 0 .../main/java/com/azure/data/cosmos/RangeIndex.java | 0 .../data/cosmos/RequestEntityTooLargeException.java | 0 .../data/cosmos/RequestRateTooLargeException.java | 0 .../azure/data/cosmos/RequestTimeoutException.java | 0 .../main/java/com/azure/data/cosmos/Resource.java | 0 .../java/com/azure/data/cosmos/RetryOptions.java | 0 .../com/azure/data/cosmos/RetryWithException.java | 0 .../data/cosmos/SerializationFormattingPolicy.java | 0 .../data/cosmos/ServiceUnavailableException.java | 0 .../java/com/azure/data/cosmos/SpatialIndex.java | 0 .../java/com/azure/data/cosmos/SpatialSpec.java | 0 .../java/com/azure/data/cosmos/SpatialType.java | 0 .../java/com/azure/data/cosmos/SqlParameter.java | 0 .../com/azure/data/cosmos/SqlParameterList.java | 0 .../java/com/azure/data/cosmos/SqlQuerySpec.java | 0 .../java/com/azure/data/cosmos/TokenResolver.java | 0 .../com/azure/data/cosmos/TriggerOperation.java | 0 .../java/com/azure/data/cosmos/TriggerType.java | 0 .../azure/data/cosmos/UnauthorizedException.java | 0 .../main/java/com/azure/data/cosmos/UniqueKey.java | 0 .../java/com/azure/data/cosmos/UniqueKeyPolicy.java | 0 .../data/cosmos/internal/AsyncDocumentClient.java | 0 .../cosmos/internal/AuthorizationTokenProvider.java | 0 .../cosmos/internal/AuthorizationTokenType.java | 0 .../data/cosmos/internal/BackoffRetryUtility.java | 0 .../internal/BaseAuthorizationTokenProvider.java | 0 .../BaseDatabaseAccountConfigurationProvider.java | 0 .../java/com/azure/data/cosmos/internal/Bytes.java | 0 .../data/cosmos/internal/ChangeFeedQueryImpl.java | 0 .../ClearingSessionContainerClientRetryPolicy.java | 0 .../data/cosmos/internal/ClientRetryPolicy.java | 0 .../com/azure/data/cosmos/internal/Configs.java | 0 .../com/azure/data/cosmos/internal/Conflict.java | 0 .../com/azure/data/cosmos/internal/Constants.java | 0 .../cosmos/internal/ContentSerializationFormat.java | 0 .../com/azure/data/cosmos/internal/Database.java | 0 .../azure/data/cosmos/internal/DatabaseAccount.java | 0 .../DatabaseAccountConfigurationProvider.java | 0 .../cosmos/internal/DatabaseAccountLocation.java | 0 .../internal/DatabaseAccountManagerInternal.java | 0 .../azure/data/cosmos/internal/DatabaseForTest.java | 0 .../com/azure/data/cosmos/internal/Document.java | 0 .../data/cosmos/internal/DocumentCollection.java | 0 .../internal/DocumentServiceRequestContext.java | 0 .../data/cosmos/internal/EnumerationDirection.java | 0 .../com/azure/data/cosmos/internal/Exceptions.java | 0 .../data/cosmos/internal/FanoutOperationState.java | 0 .../data/cosmos/internal/GlobalEndpointManager.java | 0 .../azure/data/cosmos/internal/HttpConstants.java | 0 .../internal/IAuthorizationTokenProvider.java | 0 .../cosmos/internal/ICollectionRoutingMapCache.java | 0 .../cosmos/internal/IDocumentClientRetryPolicy.java | 0 .../azure/data/cosmos/internal/IRetryPolicy.java | 0 .../data/cosmos/internal/IRetryPolicyFactory.java | 0 .../data/cosmos/internal/IRoutingMapProvider.java | 0 .../data/cosmos/internal/ISessionContainer.java | 0 .../azure/data/cosmos/internal/ISessionToken.java | 0 .../com/azure/data/cosmos/internal/Integers.java | 0 .../data/cosmos/internal/InternalConstants.java | 0 .../InvalidPartitionExceptionRetryPolicy.java | 0 .../azure/data/cosmos/internal/JavaStreamUtils.java | 0 .../azure/data/cosmos/internal/LifeCycleUtils.java | 0 .../java/com/azure/data/cosmos/internal/Lists.java | 0 .../java/com/azure/data/cosmos/internal/Longs.java | 0 .../cosmos/internal/MigrateCollectionDirective.java | 0 .../azure/data/cosmos/internal/MutableVolatile.java | 0 .../data/cosmos/internal/ObservableHelper.java | 0 .../java/com/azure/data/cosmos/internal/Offer.java | 0 .../azure/data/cosmos/internal/OperationType.java | 0 .../internal/PartitionKeyMismatchRetryPolicy.java | 0 .../data/cosmos/internal/PartitionKeyRange.java | 0 .../internal/PartitionKeyRangeGoneRetryPolicy.java | 0 .../com/azure/data/cosmos/internal/PathInfo.java | 0 .../com/azure/data/cosmos/internal/PathParser.java | 0 .../java/com/azure/data/cosmos/internal/Paths.java | 0 .../com/azure/data/cosmos/internal/PathsHelper.java | 0 .../com/azure/data/cosmos/internal/Permission.java | 0 .../com/azure/data/cosmos/internal/Quadruple.java | 0 .../cosmos/internal/QueryCompatibilityMode.java | 0 .../azure/data/cosmos/internal/QueryMetrics.java | 0 .../data/cosmos/internal/QueryMetricsConstants.java | 0 .../data/cosmos/internal/QueryMetricsUtils.java | 0 .../data/cosmos/internal/QueryPreparationTimes.java | 0 .../com/azure/data/cosmos/internal/RMResources.java | 0 .../azure/data/cosmos/internal/ReadFeedKeyType.java | 0 .../data/cosmos/internal/RemoteStorageType.java | 0 .../RenameCollectionAwareClientRetryPolicy.java | 0 .../internal/ReplicatedResourceClientUtils.java | 0 .../data/cosmos/internal/ReplicationPolicy.java | 0 .../data/cosmos/internal/RequestChargeTracker.java | 0 .../azure/data/cosmos/internal/RequestOptions.java | 0 .../ResetSessionTokenRetryPolicyFactory.java | 0 .../com/azure/data/cosmos/internal/ResourceId.java | 0 .../data/cosmos/internal/ResourceResponse.java | 0 .../internal/ResourceThrottleRetryPolicy.java | 0 .../internal/ResourceTokenAuthorizationHelper.java | 0 .../azure/data/cosmos/internal/ResourceType.java | 0 .../com/azure/data/cosmos/internal/RetryPolicy.java | 0 .../com/azure/data/cosmos/internal/RetryUtils.java | 0 .../data/cosmos/internal/RuntimeConstants.java | 0 .../data/cosmos/internal/RuntimeExecutionTimes.java | 0 .../data/cosmos/internal/RxDocumentClientImpl.java | 0 .../cosmos/internal/RxDocumentServiceRequest.java | 0 .../cosmos/internal/RxDocumentServiceResponse.java | 0 .../data/cosmos/internal/RxGatewayStoreModel.java | 0 .../azure/data/cosmos/internal/RxStoreModel.java | 0 .../data/cosmos/internal/SessionContainer.java | 0 .../data/cosmos/internal/SessionTokenHelper.java | 0 .../azure/data/cosmos/internal/StoredProcedure.java | 0 .../cosmos/internal/StoredProcedureResponse.java | 0 .../com/azure/data/cosmos/internal/Strings.java | 0 .../data/cosmos/internal/TestConfigurations.java | 0 .../com/azure/data/cosmos/internal/Trigger.java | 0 .../com/azure/data/cosmos/internal/Undefined.java | 0 .../java/com/azure/data/cosmos/internal/User.java | 0 .../data/cosmos/internal/UserAgentContainer.java | 0 .../data/cosmos/internal/UserDefinedFunction.java | 0 .../java/com/azure/data/cosmos/internal/Utils.java | 0 .../data/cosmos/internal/VectorSessionToken.java | 0 .../cosmos/internal/WebExceptionRetryPolicy.java | 0 .../data/cosmos/internal/caches/AsyncCache.java | 0 .../data/cosmos/internal/caches/AsyncLazy.java | 0 .../cosmos/internal/caches/IEqualityComparer.java | 0 .../internal/caches/IPartitionKeyRangeCache.java | 0 .../internal/caches/RxClientCollectionCache.java | 0 .../cosmos/internal/caches/RxCollectionCache.java | 0 .../internal/caches/RxPartitionKeyRangeCache.java | 0 .../cosmos/internal/changefeed/Bootstrapper.java | 0 .../internal/changefeed/CancellationToken.java | 0 .../changefeed/CancellationTokenSource.java | 0 .../changefeed/ChangeFeedContextClient.java | 0 .../internal/changefeed/ChangeFeedObserver.java | 0 .../changefeed/ChangeFeedObserverCloseReason.java | 0 .../changefeed/ChangeFeedObserverContext.java | 0 .../changefeed/ChangeFeedObserverFactory.java | 0 .../internal/changefeed/CheckpointFrequency.java | 0 .../cosmos/internal/changefeed/HealthMonitor.java | 0 .../internal/changefeed/HealthMonitoringRecord.java | 0 .../data/cosmos/internal/changefeed/Lease.java | 0 .../internal/changefeed/LeaseCheckpointer.java | 0 .../cosmos/internal/changefeed/LeaseContainer.java | 0 .../cosmos/internal/changefeed/LeaseManager.java | 0 .../cosmos/internal/changefeed/LeaseRenewer.java | 0 .../data/cosmos/internal/changefeed/LeaseStore.java | 0 .../internal/changefeed/LeaseStoreManager.java | 0 .../changefeed/LeaseStoreManagerSettings.java | 0 .../internal/changefeed/PartitionCheckpointer.java | 0 .../internal/changefeed/PartitionController.java | 0 .../internal/changefeed/PartitionLoadBalancer.java | 0 .../changefeed/PartitionLoadBalancingStrategy.java | 0 .../internal/changefeed/PartitionManager.java | 0 .../internal/changefeed/PartitionProcessor.java | 0 .../changefeed/PartitionProcessorFactory.java | 0 .../internal/changefeed/PartitionSupervisor.java | 0 .../changefeed/PartitionSupervisorFactory.java | 0 .../internal/changefeed/PartitionSynchronizer.java | 0 .../internal/changefeed/ProcessorSettings.java | 0 .../internal/changefeed/RemainingPartitionWork.java | 0 .../internal/changefeed/RemainingWorkEstimator.java | 0 .../internal/changefeed/RequestOptionsFactory.java | 0 .../internal/changefeed/ServiceItemLease.java | 0 .../changefeed/ServiceItemLeaseUpdater.java | 0 .../changefeed/exceptions/LeaseLostException.java | 0 .../changefeed/exceptions/ObserverException.java | 0 .../changefeed/exceptions/PartitionException.java | 0 .../exceptions/PartitionNotFoundException.java | 0 .../exceptions/PartitionSplitException.java | 0 .../exceptions/TaskCancelledException.java | 0 .../changefeed/implementation/AutoCheckpointer.java | 0 .../changefeed/implementation/BootstrapperImpl.java | 0 .../implementation/ChangeFeedContextClientImpl.java | 0 .../changefeed/implementation/ChangeFeedHelper.java | 0 .../ChangeFeedObserverContextImpl.java | 0 .../ChangeFeedObserverFactoryImpl.java | 0 .../ChangeFeedProcessorBuilderImpl.java | 0 .../implementation/CheckpointerObserverFactory.java | 0 .../changefeed/implementation/Constants.java | 0 .../changefeed/implementation/DefaultObserver.java | 0 .../implementation/DefaultObserverFactory.java | 0 .../implementation/DocumentServiceLeaseStore.java | 0 .../DocumentServiceLeaseUpdaterImpl.java | 0 .../EqualPartitionsBalancingStrategy.java | 0 .../implementation/ExceptionClassifier.java | 0 ...ealthMonitoringPartitionControllerDecorator.java | 0 .../changefeed/implementation/LeaseRenewerImpl.java | 0 .../implementation/LeaseStoreManagerImpl.java | 0 ...xceptionWrappingChangeFeedObserverDecorator.java | 0 .../implementation/PartitionCheckpointerImpl.java | 0 .../implementation/PartitionControllerImpl.java | 0 .../implementation/PartitionLoadBalancerImpl.java | 0 .../implementation/PartitionManagerImpl.java | 0 .../PartitionProcessorFactoryImpl.java | 0 .../implementation/PartitionProcessorImpl.java | 0 .../PartitionSupervisorFactoryImpl.java | 0 .../implementation/PartitionSupervisorImpl.java | 0 .../implementation/PartitionSynchronizerImpl.java | 0 ...titionedByIdCollectionRequestOptionsFactory.java | 0 .../implementation/RemainingPartitionWorkImpl.java | 0 .../implementation/RemainingWorkEstimatorImpl.java | 0 .../implementation/StatusCodeErrorType.java | 0 .../implementation/TraceHealthMonitor.java | 0 .../changefeed/implementation/WorkerTask.java | 0 .../cosmos/internal/directconnectivity/Address.java | 0 .../directconnectivity/AddressInformation.java | 0 .../directconnectivity/AddressResolver.java | 0 .../directconnectivity/AddressSelector.java | 0 .../directconnectivity/BarrierRequestHelper.java | 0 .../directconnectivity/ConsistencyReader.java | 0 .../directconnectivity/ConsistencyWriter.java | 0 .../internal/directconnectivity/CustomHeaders.java | 0 .../internal/directconnectivity/ErrorUtils.java | 0 .../directconnectivity/GatewayAddressCache.java | 0 .../GatewayServiceConfigurationReader.java | 0 .../directconnectivity/GlobalAddressResolver.java | 0 .../GoneAndRetryWithRetryPolicy.java | 0 .../directconnectivity/HttpClientUtils.java | 0 .../directconnectivity/HttpTransportClient.java | 0 .../internal/directconnectivity/HttpUtils.java | 0 .../internal/directconnectivity/IAddressCache.java | 0 .../directconnectivity/IAddressResolver.java | 0 .../internal/directconnectivity/IStoreClient.java | 0 .../internal/directconnectivity/Protocol.java | 0 .../QueryRequestPerformanceActivity.java | 0 .../internal/directconnectivity/QuorumReader.java | 0 .../internal/directconnectivity/ReadMode.java | 0 .../ReplicatedResourceClient.java | 0 .../internal/directconnectivity/RequestHelper.java | 0 .../directconnectivity/ResourceOperation.java | 0 .../internal/directconnectivity/ResponseUtils.java | 0 .../directconnectivity/RntbdTransportClient.java | 0 .../directconnectivity/ServerProperties.java | 0 .../directconnectivity/ServerStoreModel.java | 0 .../internal/directconnectivity/ServiceConfig.java | 0 .../internal/directconnectivity/StoreClient.java | 0 .../directconnectivity/StoreClientFactory.java | 0 .../internal/directconnectivity/StoreReader.java | 0 .../internal/directconnectivity/StoreResponse.java | 0 .../internal/directconnectivity/StoreResult.java | 0 .../internal/directconnectivity/TimeoutHelper.java | 0 .../directconnectivity/TransportClient.java | 0 .../directconnectivity/TransportException.java | 0 .../internal/directconnectivity/WFConstants.java | 0 .../directconnectivity/WebExceptionUtility.java | 0 .../rntbd/RntbdClientChannelHandler.java | 0 .../rntbd/RntbdClientChannelPool.java | 0 .../directconnectivity/rntbd/RntbdConstants.java | 0 .../directconnectivity/rntbd/RntbdContext.java | 0 .../rntbd/RntbdContextDecoder.java | 0 .../rntbd/RntbdContextException.java | 0 .../rntbd/RntbdContextNegotiator.java | 0 .../rntbd/RntbdContextRequest.java | 0 .../rntbd/RntbdContextRequestDecoder.java | 0 .../rntbd/RntbdContextRequestEncoder.java | 0 .../directconnectivity/rntbd/RntbdEndpoint.java | 0 .../directconnectivity/rntbd/RntbdFramer.java | 0 .../directconnectivity/rntbd/RntbdMetrics.java | 0 .../directconnectivity/rntbd/RntbdObjectMapper.java | 0 .../directconnectivity/rntbd/RntbdReporter.java | 0 .../directconnectivity/rntbd/RntbdRequest.java | 0 .../directconnectivity/rntbd/RntbdRequestArgs.java | 0 .../rntbd/RntbdRequestDecoder.java | 0 .../rntbd/RntbdRequestEncoder.java | 0 .../directconnectivity/rntbd/RntbdRequestFrame.java | 0 .../rntbd/RntbdRequestFramer.java | 0 .../rntbd/RntbdRequestHeaders.java | 0 .../rntbd/RntbdRequestManager.java | 0 .../rntbd/RntbdRequestRecord.java | 0 .../directconnectivity/rntbd/RntbdRequestTimer.java | 0 .../directconnectivity/rntbd/RntbdResponse.java | 0 .../rntbd/RntbdResponseDecoder.java | 0 .../rntbd/RntbdResponseHeaders.java | 0 .../rntbd/RntbdResponseStatus.java | 0 .../rntbd/RntbdServiceEndpoint.java | 0 .../directconnectivity/rntbd/RntbdToken.java | 0 .../directconnectivity/rntbd/RntbdTokenStream.java | 0 .../directconnectivity/rntbd/RntbdTokenType.java | 0 .../directconnectivity/rntbd/RntbdUUID.java | 0 .../cosmos/internal/http/BufferedHttpResponse.java | 0 .../azure/data/cosmos/internal/http/HttpClient.java | 0 .../data/cosmos/internal/http/HttpClientConfig.java | 0 .../azure/data/cosmos/internal/http/HttpHeader.java | 0 .../data/cosmos/internal/http/HttpHeaders.java | 0 .../data/cosmos/internal/http/HttpRequest.java | 0 .../data/cosmos/internal/http/HttpResponse.java | 0 .../cosmos/internal/http/ReactorNettyClient.java | 0 .../AggregateDocumentQueryExecutionContext.java | 0 .../internal/query/CompositeContinuationToken.java | 0 .../query/DefaultDocumentQueryExecutionContext.java | 0 .../cosmos/internal/query/DocumentProducer.java | 0 .../query/DocumentQueryExecutionContextBase.java | 0 .../query/DocumentQueryExecutionContextFactory.java | 0 .../data/cosmos/internal/query/ExceptionHelper.java | 0 .../azure/data/cosmos/internal/query/Fetcher.java | 0 .../cosmos/internal/query/IDocumentQueryClient.java | 0 .../query/IDocumentQueryExecutionComponent.java | 0 .../query/IDocumentQueryExecutionContext.java | 0 .../data/cosmos/internal/query/ItemComparator.java | 0 .../azure/data/cosmos/internal/query/ItemType.java | 0 .../data/cosmos/internal/query/ItemTypeHelper.java | 0 .../internal/query/OrderByContinuationToken.java | 0 .../internal/query/OrderByDocumentProducer.java | 0 .../query/OrderByDocumentQueryExecutionContext.java | 0 .../data/cosmos/internal/query/OrderByUtils.java | 0 .../azure/data/cosmos/internal/query/Paginator.java | 0 .../ParallelDocumentQueryExecutionContext.java | 0 .../ParallelDocumentQueryExecutionContextBase.java | 0 .../cosmos/internal/query/ParallelQueryConfig.java | 0 .../query/PartitionedQueryExecutionInfo.java | 0 .../PartitionedQueryExecutionInfoInternal.java | 0 .../PipelinedDocumentQueryExecutionContext.java | 0 .../query/ProxyDocumentQueryExecutionContext.java | 0 .../azure/data/cosmos/internal/query/QueryInfo.java | 0 .../azure/data/cosmos/internal/query/QueryItem.java | 0 .../azure/data/cosmos/internal/query/SortOrder.java | 0 .../internal/query/TakeContinuationToken.java | 0 .../query/TopDocumentQueryExecutionContext.java | 0 .../data/cosmos/internal/query/TriFunction.java | 0 .../query/aggregation/AggregateOperator.java | 0 .../internal/query/aggregation/Aggregator.java | 0 .../query/aggregation/AverageAggregator.java | 0 .../internal/query/aggregation/CountAggregator.java | 0 .../internal/query/aggregation/MaxAggregator.java | 0 .../internal/query/aggregation/MinAggregator.java | 0 .../internal/query/aggregation/SumAggregator.java | 0 .../internal/query/metrics/ClientSideMetrics.java | 0 .../internal/query/metrics/FetchExecutionRange.java | 0 .../metrics/FetchExecutionRangeAccumulator.java | 0 .../query/metrics/QueryMetricsTextWriter.java | 0 .../internal/query/metrics/QueryMetricsWriter.java | 0 .../internal/query/metrics/SchedulingStopwatch.java | 0 .../internal/query/metrics/SchedulingTimeSpan.java | 0 .../cosmos/internal/query/metrics/TextTable.java | 0 .../query/orderbyquery/OrderByRowResult.java | 0 .../query/orderbyquery/OrderbyRowComparer.java | 0 .../internal/routing/BoolPartitionKeyComponent.java | 0 .../internal/routing/CaseInsensitiveHashMap.java | 0 .../internal/routing/CollectionRoutingMap.java | 0 .../internal/routing/IPartitionKeyComponent.java | 0 .../cosmos/internal/routing/IServerIdentity.java | 0 .../routing/InMemoryCollectionRoutingMap.java | 0 .../routing/InfinityPartitionKeyComponent.java | 0 .../azure/data/cosmos/internal/routing/Int128.java | 0 .../data/cosmos/internal/routing/LocationCache.java | 0 .../cosmos/internal/routing/LocationHelper.java | 0 .../routing/MaxNumberPartitionKeyComponent.java | 0 .../routing/MaxStringPartitionKeyComponent.java | 0 .../routing/MinNumberPartitionKeyComponent.java | 0 .../routing/MinStringPartitionKeyComponent.java | 0 .../cosmos/internal/routing/MurmurHash3_128.java | 0 .../cosmos/internal/routing/MurmurHash3_32.java | 0 .../internal/routing/NullPartitionKeyComponent.java | 0 .../routing/NumberPartitionKeyComponent.java | 0 .../routing/PartitionKeyAndResourceTokenPair.java | 0 .../internal/routing/PartitionKeyComponentType.java | 0 .../internal/routing/PartitionKeyInternal.java | 0 .../routing/PartitionKeyInternalHelper.java | 0 .../internal/routing/PartitionKeyRangeIdentity.java | 0 .../azure/data/cosmos/internal/routing/Range.java | 0 .../cosmos/internal/routing/RoutingMapProvider.java | 0 .../internal/routing/RoutingMapProviderHelper.java | 0 .../routing/StringPartitionKeyComponent.java | 0 .../azure/data/cosmos/internal/routing/UInt128.java | 0 .../routing/UndefinedPartitionKeyComponent.java | 0 .../java/com/azure/data/cosmos/package-info.java | 0 .../java/com/azure/data/cosmos/BridgeUtils.java | 0 .../azure/data/cosmos/ClientUnderTestBuilder.java | 0 .../java/com/azure/data/cosmos/ConflictTests.java | 0 .../com/azure/data/cosmos/ConnectionPolicyTest.java | 0 .../data/cosmos/CosmosClientExceptionTest.java | 0 .../com/azure/data/cosmos/CosmosClientTest.java | 0 .../azure/data/cosmos/CosmosDatabaseForTest.java | 0 .../azure/data/cosmos/CosmosPartitionKeyTests.java | 0 .../azure/data/cosmos/CosmosResponseValidator.java | 0 .../com/azure/data/cosmos/DocumentClientTest.java | 0 .../azure/data/cosmos/DocumentCollectionTests.java | 0 .../java/com/azure/data/cosmos/DocumentTests.java | 0 .../com/azure/data/cosmos/GatewayTestUtils.java | 0 .../com/azure/data/cosmos/IncludedPathTest.java | 0 .../azure/data/cosmos/JsonSerializableTests.java | 0 .../azure/data/cosmos/PartitionKeyHashingTests.java | 0 .../java/com/azure/data/cosmos/PermissionTest.java | 0 .../java/com/azure/data/cosmos/ResourceIdTests.java | 0 .../data/cosmos/internal/ClientRetryPolicyTest.java | 0 .../azure/data/cosmos/internal/ConfigsBuilder.java | 0 .../azure/data/cosmos/internal/ConfigsTests.java | 0 .../data/cosmos/internal/ConsistencyTests1.java | 0 .../data/cosmos/internal/ConsistencyTests2.java | 0 .../data/cosmos/internal/ConsistencyTestsBase.java | 0 .../internal/DocumentQuerySpyWireContentTest.java | 0 .../DocumentServiceRequestContextValidator.java | 0 .../internal/DocumentServiceRequestValidator.java | 0 .../data/cosmos/internal/FailureValidator.java | 0 .../cosmos/internal/FeedResponseListValidator.java | 0 .../data/cosmos/internal/FeedResponseValidator.java | 0 .../cosmos/internal/HttpClientUnderTestWrapper.java | 0 .../data/cosmos/internal/LocationHelperTest.java | 0 .../data/cosmos/internal/NetworkFailureTest.java | 0 .../azure/data/cosmos/internal/ParallelAsync.java | 0 .../azure/data/cosmos/internal/PathsHelperTest.java | 0 .../RenameCollectionAwareClientRetryPolicyTest.java | 0 .../cosmos/internal/ResourceResponseValidator.java | 0 .../data/cosmos/internal/ResourceValidator.java | 0 .../azure/data/cosmos/internal/RetryAnalyzer.java | 0 .../cosmos/internal/RetryCreateDocumentTest.java | 0 .../data/cosmos/internal/RetryThrottleTest.java | 0 .../azure/data/cosmos/internal/RetryUtilsTest.java | 0 .../cosmos/internal/RxDocumentClientUnderTest.java | 0 .../internal/RxDocumentServiceRequestTest.java | 0 .../cosmos/internal/RxGatewayStoreModelTest.java | 0 .../data/cosmos/internal/SessionContainerTest.java | 0 .../com/azure/data/cosmos/internal/SessionTest.java | 0 .../data/cosmos/internal/SessionTokenTest.java | 0 .../data/cosmos/internal/ShouldRetryValidator.java | 0 .../data/cosmos/internal/SpyClientBuilder.java | 0 .../cosmos/internal/SpyClientUnderTestFactory.java | 0 .../data/cosmos/internal/StoreHeaderTests.java | 0 .../data/cosmos/internal/StoreResponseBuilder.java | 0 .../azure/data/cosmos/internal/TestSuiteBase.java | 0 .../com/azure/data/cosmos/internal/TestUtils.java | 0 .../azure/data/cosmos/internal/TimeTokenTest.java | 0 .../data/cosmos/internal/caches/AsyncCacheTest.java | 0 .../directconnectivity/AddressResolverTest.java | 0 .../directconnectivity/AddressSelectorTest.java | 0 .../directconnectivity/AddressSelectorWrapper.java | 0 .../directconnectivity/AddressValidator.java | 0 .../BarrierRequestHelperTest.java | 0 .../directconnectivity/ConsistencyReaderTest.java | 0 .../ConsistencyReaderUnderTest.java | 0 .../directconnectivity/ConsistencyWriterTest.java | 0 .../directconnectivity/DCDocumentCrudTest.java | 0 .../internal/directconnectivity/EndpointMock.java | 0 .../directconnectivity/ExceptionBuilder.java | 0 .../Function1WithCheckedException.java | 0 .../Function2WithCheckedException.java | 0 .../directconnectivity/GatewayAddressCacheTest.java | 0 .../GatewayServiceConfigurationReaderTest.java | 0 .../GatewayServiceConfiguratorReaderMock.java | 0 .../GlobalAddressResolverTest.java | 0 .../GoneAndRetryWithRetryPolicyTest.java | 0 .../directconnectivity/HttpClientMockWrapper.java | 0 .../directconnectivity/HttpTransportClientTest.java | 0 .../internal/directconnectivity/HttpUtilsTest.java | 0 .../MultiStoreResultValidator.java | 0 .../directconnectivity/MurmurHash3_32Test.java | 0 .../PartitionKeyInternalTest.java | 0 .../directconnectivity/PartitionKeyTest.java | 0 .../PartitionReplicasAddressesValidator.java | 0 .../directconnectivity/QuorumReaderTest.java | 0 .../directconnectivity/ReflectionUtils.java | 0 .../directconnectivity/ReplicaAddressFactory.java | 0 .../ReplicatedResourceClientPartitionSplitTest.java | 0 .../ReplicatedResourceClientTest.java | 0 .../RntbdTransportClientTest.java | 0 .../directconnectivity/StoreReaderDotNetTest.java | 0 .../directconnectivity/StoreReaderTest.java | 0 .../directconnectivity/StoreReaderUnderTest.java | 0 .../directconnectivity/StoreResponseTest.java | 0 .../directconnectivity/StoreResponseValidator.java | 0 .../directconnectivity/StoreResultValidator.java | 0 .../directconnectivity/TimeoutHelperTest.java | 0 .../directconnectivity/TransportClientWrapper.java | 0 .../directconnectivity/WebExceptionUtilityTest.java | 0 .../cosmos/internal/query/DocumentProducerTest.java | 0 .../cosmos/internal/query/FeedResponseBuilder.java | 0 .../data/cosmos/internal/query/FetcherTest.java | 0 .../routing/InMemoryCollectionRoutingMapTest.java | 0 .../cosmos/internal/routing/LocationCacheTest.java | 0 .../internal/routing/PartitionKeyInternalUtils.java | 0 .../routing/RoutingMapProviderHelperTest.java | 0 .../routing/StringPartitionKeyComponentTest.java | 0 .../azure/data/cosmos/rx/AggregateQueryTests.java | 0 .../cosmos/rx/BackPressureCrossPartitionTest.java | 0 .../com/azure/data/cosmos/rx/BackPressureTest.java | 0 .../data/cosmos/rx/ChangeFeedProcessorTest.java | 0 .../com/azure/data/cosmos/rx/ChangeFeedTest.java | 0 .../azure/data/cosmos/rx/CollectionCrudTest.java | 0 .../azure/data/cosmos/rx/CollectionQueryTest.java | 0 .../azure/data/cosmos/rx/CosmosConflictTest.java | 0 .../com/azure/data/cosmos/rx/DatabaseCrudTest.java | 0 .../com/azure/data/cosmos/rx/DatabaseQueryTest.java | 0 .../cosmos/rx/DocumentClientResourceLeakTest.java | 0 .../com/azure/data/cosmos/rx/DocumentCrudTest.java | 0 .../java/com/azure/data/cosmos/rx/LogLevelTest.java | 0 .../rx/MultiMasterConflictResolutionTest.java | 0 .../data/cosmos/rx/MultiOrderByQueryTests.java | 0 .../com/azure/data/cosmos/rx/OfferQueryTest.java | 0 .../azure/data/cosmos/rx/OfferReadReplaceTest.java | 0 .../data/cosmos/rx/OrderbyDocumentQueryTest.java | 0 .../data/cosmos/rx/ParallelDocumentQueryTest.java | 0 .../com/azure/data/cosmos/rx/ParsingEnvTest.java | 0 .../azure/data/cosmos/rx/PermissionCrudTest.java | 0 .../azure/data/cosmos/rx/PermissionQueryTest.java | 0 .../com/azure/data/cosmos/rx/ProxyHostTest.java | 0 .../data/cosmos/rx/ReadFeedCollectionsTest.java | 0 .../azure/data/cosmos/rx/ReadFeedDatabasesTest.java | 0 .../azure/data/cosmos/rx/ReadFeedDocumentsTest.java | 0 .../cosmos/rx/ReadFeedExceptionHandlingTest.java | 0 .../azure/data/cosmos/rx/ReadFeedOffersTest.java | 0 .../data/cosmos/rx/ReadFeedPermissionsTest.java | 0 .../com/azure/data/cosmos/rx/ReadFeedPkrTests.java | 0 .../cosmos/rx/ReadFeedStoredProceduresTest.java | 0 .../azure/data/cosmos/rx/ReadFeedTriggersTest.java | 0 .../com/azure/data/cosmos/rx/ReadFeedUdfsTest.java | 0 .../com/azure/data/cosmos/rx/ReadFeedUsersTest.java | 0 .../com/azure/data/cosmos/rx/ResourceTokenTest.java | 0 .../data/cosmos/rx/SimpleSerializationTest.java | 0 .../cosmos/rx/SinglePartitionDocumentQueryTest.java | 0 .../rx/SinglePartitionReadFeedDocumentsTest.java | 0 .../data/cosmos/rx/StoredProcedureCrudTest.java | 0 .../data/cosmos/rx/StoredProcedureQueryTest.java | 0 .../cosmos/rx/StoredProcedureUpsertReplaceTest.java | 0 .../com/azure/data/cosmos/rx/TestSuiteBase.java | 0 .../com/azure/data/cosmos/rx/TokenResolverTest.java | 0 .../com/azure/data/cosmos/rx/TopQueryTests.java | 0 .../com/azure/data/cosmos/rx/TriggerCrudTest.java | 0 .../com/azure/data/cosmos/rx/TriggerQueryTest.java | 0 .../data/cosmos/rx/TriggerUpsertReplaceTest.java | 0 .../com/azure/data/cosmos/rx/UniqueIndexTest.java | 0 .../java/com/azure/data/cosmos/rx/UserCrudTest.java | 0 .../data/cosmos/rx/UserDefinedFunctionCrudTest.java | 0 .../cosmos/rx/UserDefinedFunctionQueryTest.java | 0 .../rx/UserDefinedFunctionUpsertReplaceTest.java | 0 .../com/azure/data/cosmos/rx/UserQueryTest.java | 0 .../data/cosmos/rx/VeryLargeDocumentQueryTest.java | 0 .../rx/proxy/HttpProxyChannelInitializer.java | 0 .../cosmos/rx/proxy/HttpProxyClientHandler.java | 0 .../data/cosmos/rx/proxy/HttpProxyClientHeader.java | 0 .../cosmos/rx/proxy/HttpProxyRemoteHandler.java | 0 .../azure/data/cosmos/rx/proxy/HttpProxyServer.java | 0 .../sdk}/src/test/resources/Microsoft.jpg | Bin .../sdk}/src/test/resources/cosmosdb-1.png | Bin .../sdk}/src/test/resources/databaseAccount.json | 0 .../sdk}/src/test/resources/emulator-testng.xml | 0 .../sdk}/src/test/resources/fast-testng.xml | 0 .../sdk}/src/test/resources/log4j.properties | 0 .../sdk}/src/test/resources/long-testng.xml | 0 .../sdk}/src/test/resources/sampleConflict.json | 0 679 files changed, 0 insertions(+), 0 deletions(-) rename CODEOWNERS => sdk/cosmos/CODEOWNERS (100%) rename LICENSE => sdk/cosmos/LICENSE (100%) rename README.md => sdk/cosmos/README.md (100%) rename {benchmark => sdk/cosmos/benchmark}/README.md (100%) rename {benchmark => sdk/cosmos/benchmark}/pom.xml (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/java/com/azure/data/cosmos/benchmark/Main.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/main/resources/log4j.properties (100%) rename {benchmark => sdk/cosmos/benchmark}/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/test/java/com/azure/data/cosmos/benchmark/Utils.java (100%) rename {benchmark => sdk/cosmos/benchmark}/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java (100%) rename {changelog => sdk/cosmos/changelog}/README.md (100%) rename {examples => sdk/cosmos/examples}/pom.xml (100%) rename {examples => sdk/cosmos/examples}/src/main/java/com/azure/data/cosmos/examples/AccountSettings.java (100%) rename {examples => sdk/cosmos/examples}/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java (100%) rename {examples => sdk/cosmos/examples}/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java (100%) rename {examples => sdk/cosmos/examples}/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleConfigurations.java (100%) rename {examples => sdk/cosmos/examples}/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/ConfigurationManager.java (100%) rename {examples => sdk/cosmos/examples}/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java (100%) rename {examples => sdk/cosmos/examples}/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java (100%) rename {examples => sdk/cosmos/examples}/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Main.java (100%) rename {examples => sdk/cosmos/examples}/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java (100%) rename {examples => sdk/cosmos/examples}/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java (100%) rename {examples => sdk/cosmos/examples}/src/main/resources/log4j.properties (100%) rename {examples => sdk/cosmos/examples}/src/main/resources/multi-master-sample-config.properties (100%) rename {examples => sdk/cosmos/examples}/src/main/resources/resolver-storedproc.txt (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/DocumentClientTest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java (100%) rename {examples => sdk/cosmos/examples}/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java (100%) rename {examples => sdk/cosmos/examples}/src/test/resources/log4j.properties (100%) rename {faq => sdk/cosmos/faq}/README.md (100%) rename pom.xml => sdk/cosmos/pom.xml (100%) rename sdk/{ => cosmos/sdk}/CosmosConflict (100%) rename sdk/{ => cosmos/sdk}/pom.xml (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/AccessCondition.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/AccessConditionType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/BadRequestException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/BridgeInternal.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CompositePath.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ConflictException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ConnectionMode.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosClientException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosConflict.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosContainer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosDatabase.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosError.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosItem.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosPermission.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosPermissionRequestOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosResourceType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosResponseDiagnostics.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosScripts.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosTrigger.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosUser.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/DataType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ExcludedPath.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/FeedOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/FeedResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/FeedResponseDiagnostics.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ForbiddenException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/GoneException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/HashIndex.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/IncludedPath.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/Index.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/IndexKind.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/IndexingDirective.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/IndexingMode.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/IndexingPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/JsonSerializable.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/LockedException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/NotFoundException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/PartitionKey.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/PartitionKind.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/PermissionMode.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/RangeIndex.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/Resource.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/RetryOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/RetryWithException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/SpatialIndex.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/SpatialSpec.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/SpatialType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/SqlParameter.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/SqlParameterList.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/TokenResolver.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/TriggerOperation.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/TriggerType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/UnauthorizedException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/UniqueKey.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/AsyncDocumentClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Bytes.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Configs.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Conflict.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Constants.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Database.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/DatabaseAccount.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountLocation.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountManagerInternal.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Document.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/DocumentCollection.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Exceptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ISessionContainer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Integers.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Lists.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Longs.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Offer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/OperationType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/PathInfo.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/PathParser.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Paths.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Permission.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Quadruple.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RMResources.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ResourceId.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/ResourceType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Strings.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/TestConfigurations.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Trigger.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Undefined.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/User.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/Utils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/Bootstrapper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationToken.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationTokenSource.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserver.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverCloseReason.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/CheckpointFrequency.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitor.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitoringRecord.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/Lease.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseCheckpointer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseContainer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseManager.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseRenewer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStore.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManager.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionCheckpointer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionController.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancingStrategy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionManager.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessor.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessorFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisor.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisorFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSynchronizer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingPartitionWork.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingWorkEstimator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/RequestOptionsFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLeaseUpdater.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/LeaseLostException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/ObserverException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionNotFoundException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionSplitException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/TaskCancelledException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/BootstrapperImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverFactoryImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/CheckpointerObserverFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/Constants.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserver.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserverFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseUpdaterImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ExceptionClassifier.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/HealthMonitoringPartitionControllerDecorator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseRenewerImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionCheckpointerImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionControllerImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionLoadBalancerImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionManagerImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingPartitionWorkImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingWorkEstimatorImpl.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/StatusCodeErrorType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/TraceHealthMonitor.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Address.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressInformation.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelector.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/CustomHeaders.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ErrorUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressCache.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressResolver.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IStoreClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Protocol.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QueryRequestPerformanceActivity.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReader.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReadMode.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RequestHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResourceOperation.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResponseUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerProperties.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerStoreModel.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServiceConfig.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClientFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResult.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WFConstants.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtility.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHandler.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelPool.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdConstants.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextDecoder.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextException.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextNegotiator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequest.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdEndpoint.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdFramer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdMetrics.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdObjectMapper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdReporter.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequest.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestArgs.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestDecoder.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestEncoder.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFrame.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFramer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestHeaders.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestManager.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseDecoder.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseHeaders.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseStatus.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdToken.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenStream.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdUUID.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/Range.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java (100%) rename sdk/{ => cosmos/sdk}/src/main/java/com/azure/data/cosmos/package-info.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/BridgeUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/ConflictTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/CosmosClientTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/DocumentClientTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/DocumentTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/IncludedPathTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/PermissionTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/ResourceIdTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/ConfigsBuilder.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestContextValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/FailureValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/FeedResponseValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/HttpClientUnderTestWrapper.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/ResourceValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/RetryAnalyzer.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/SessionTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/SpyClientBuilder.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/StoreResponseBuilder.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/TestUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorWrapper.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/EndpointMock.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ExceptionBuilder.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function1WithCheckedException.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function2WithCheckedException.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientMockWrapper.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClientTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtilsTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MultiStoreResultValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MurmurHash3_32Test.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionReplicasAddressesValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicaAddressFactory.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResultValidator.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelperTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TransportClientWrapper.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtilityTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHeader.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java (100%) rename sdk/{ => cosmos/sdk}/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java (100%) rename sdk/{ => cosmos/sdk}/src/test/resources/Microsoft.jpg (100%) rename sdk/{ => cosmos/sdk}/src/test/resources/cosmosdb-1.png (100%) rename sdk/{ => cosmos/sdk}/src/test/resources/databaseAccount.json (100%) rename sdk/{ => cosmos/sdk}/src/test/resources/emulator-testng.xml (100%) rename sdk/{ => cosmos/sdk}/src/test/resources/fast-testng.xml (100%) rename sdk/{ => cosmos/sdk}/src/test/resources/log4j.properties (100%) rename sdk/{ => cosmos/sdk}/src/test/resources/long-testng.xml (100%) rename sdk/{ => cosmos/sdk}/src/test/resources/sampleConflict.json (100%) diff --git a/CODEOWNERS b/sdk/cosmos/CODEOWNERS similarity index 100% rename from CODEOWNERS rename to sdk/cosmos/CODEOWNERS diff --git a/LICENSE b/sdk/cosmos/LICENSE similarity index 100% rename from LICENSE rename to sdk/cosmos/LICENSE diff --git a/README.md b/sdk/cosmos/README.md similarity index 100% rename from README.md rename to sdk/cosmos/README.md diff --git a/benchmark/README.md b/sdk/cosmos/benchmark/README.md similarity index 100% rename from benchmark/README.md rename to sdk/cosmos/benchmark/README.md diff --git a/benchmark/pom.xml b/sdk/cosmos/benchmark/pom.xml similarity index 100% rename from benchmark/pom.xml rename to sdk/cosmos/benchmark/pom.xml diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java b/sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java similarity index 100% rename from benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java rename to sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncBenchmark.java diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java b/sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java similarity index 100% rename from benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java rename to sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncMixedBenchmark.java diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java b/sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java similarity index 100% rename from benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java rename to sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQueryBenchmark.java diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java b/sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java similarity index 100% rename from benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java rename to sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncQuerySinglePartitionMultiple.java diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java b/sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java similarity index 100% rename from benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java rename to sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncReadBenchmark.java diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java b/sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java similarity index 100% rename from benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java rename to sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/AsyncWriteBenchmark.java diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java b/sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java similarity index 100% rename from benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java rename to sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Configuration.java diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java b/sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java similarity index 100% rename from benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java rename to sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/DocDBUtils.java diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Main.java b/sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Main.java similarity index 100% rename from benchmark/src/main/java/com/azure/data/cosmos/benchmark/Main.java rename to sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/Main.java diff --git a/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java b/sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java similarity index 100% rename from benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java rename to sdk/cosmos/benchmark/src/main/java/com/azure/data/cosmos/benchmark/ReadMyWriteWorkflow.java diff --git a/benchmark/src/main/resources/log4j.properties b/sdk/cosmos/benchmark/src/main/resources/log4j.properties similarity index 100% rename from benchmark/src/main/resources/log4j.properties rename to sdk/cosmos/benchmark/src/main/resources/log4j.properties diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java b/sdk/cosmos/benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java similarity index 100% rename from benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java rename to sdk/cosmos/benchmark/src/test/java/com/azure/data/cosmos/benchmark/QueryBuilderTest.java diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java b/sdk/cosmos/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java similarity index 100% rename from benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java rename to sdk/cosmos/benchmark/src/test/java/com/azure/data/cosmos/benchmark/ReadMyWritesConsistencyTest.java diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java b/sdk/cosmos/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java similarity index 100% rename from benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java rename to sdk/cosmos/benchmark/src/test/java/com/azure/data/cosmos/benchmark/Utils.java diff --git a/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java b/sdk/cosmos/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java similarity index 100% rename from benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java rename to sdk/cosmos/benchmark/src/test/java/com/azure/data/cosmos/benchmark/WorkflowTest.java diff --git a/changelog/README.md b/sdk/cosmos/changelog/README.md similarity index 100% rename from changelog/README.md rename to sdk/cosmos/changelog/README.md diff --git a/examples/pom.xml b/sdk/cosmos/examples/pom.xml similarity index 100% rename from examples/pom.xml rename to sdk/cosmos/examples/pom.xml diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/AccountSettings.java b/sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/examples/AccountSettings.java similarity index 100% rename from examples/src/main/java/com/azure/data/cosmos/examples/AccountSettings.java rename to sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/examples/AccountSettings.java diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java b/sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java similarity index 100% rename from examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java rename to sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/examples/BasicDemo.java diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java b/sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java similarity index 100% rename from examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java rename to sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleChangeFeedProcessor.java diff --git a/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleConfigurations.java b/sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleConfigurations.java similarity index 100% rename from examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleConfigurations.java rename to sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/examples/ChangeFeed/SampleConfigurations.java diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/ConfigurationManager.java b/sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/ConfigurationManager.java similarity index 100% rename from examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/ConfigurationManager.java rename to sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/ConfigurationManager.java diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java b/sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java similarity index 100% rename from examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java rename to sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/Helpers.java diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java b/sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java similarity index 100% rename from examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java rename to sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/ConflictWorker.java diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Main.java b/sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Main.java similarity index 100% rename from examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Main.java rename to sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Main.java diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java b/sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java similarity index 100% rename from examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java rename to sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/MultiMasterScenario.java diff --git a/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java b/sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java similarity index 100% rename from examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java rename to sdk/cosmos/examples/src/main/java/com/azure/data/cosmos/rx/examples/multimaster/samples/Worker.java diff --git a/examples/src/main/resources/log4j.properties b/sdk/cosmos/examples/src/main/resources/log4j.properties similarity index 100% rename from examples/src/main/resources/log4j.properties rename to sdk/cosmos/examples/src/main/resources/log4j.properties diff --git a/examples/src/main/resources/multi-master-sample-config.properties b/sdk/cosmos/examples/src/main/resources/multi-master-sample-config.properties similarity index 100% rename from examples/src/main/resources/multi-master-sample-config.properties rename to sdk/cosmos/examples/src/main/resources/multi-master-sample-config.properties diff --git a/examples/src/main/resources/resolver-storedproc.txt b/sdk/cosmos/examples/src/main/resources/resolver-storedproc.txt similarity index 100% rename from examples/src/main/resources/resolver-storedproc.txt rename to sdk/cosmos/examples/src/main/resources/resolver-storedproc.txt diff --git a/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/DocumentClientTest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/CollectionCRUDAsyncAPITest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/ConflictAPITest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentCRUDAsyncAPITest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/DocumentQueryAsyncAPITest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/InMemoryGroupbyTest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/OfferCRUDAsyncAPITest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/StoredProcedureAsyncAPITest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/TestConfigurations.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/TokenResolverTest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/UniqueIndexAsyncAPITest.java diff --git a/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java b/sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java similarity index 100% rename from examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java rename to sdk/cosmos/examples/src/test/java/com/azure/data/cosmos/rx/examples/Utils.java diff --git a/examples/src/test/resources/log4j.properties b/sdk/cosmos/examples/src/test/resources/log4j.properties similarity index 100% rename from examples/src/test/resources/log4j.properties rename to sdk/cosmos/examples/src/test/resources/log4j.properties diff --git a/faq/README.md b/sdk/cosmos/faq/README.md similarity index 100% rename from faq/README.md rename to sdk/cosmos/faq/README.md diff --git a/pom.xml b/sdk/cosmos/pom.xml similarity index 100% rename from pom.xml rename to sdk/cosmos/pom.xml diff --git a/sdk/CosmosConflict b/sdk/cosmos/sdk/CosmosConflict similarity index 100% rename from sdk/CosmosConflict rename to sdk/cosmos/sdk/CosmosConflict diff --git a/sdk/pom.xml b/sdk/cosmos/sdk/pom.xml similarity index 100% rename from sdk/pom.xml rename to sdk/cosmos/sdk/pom.xml diff --git a/sdk/src/main/java/com/azure/data/cosmos/AccessCondition.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/AccessCondition.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/AccessCondition.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/AccessCondition.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/AccessConditionType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/AccessConditionType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/AccessConditionType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/AccessConditionType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/BadRequestException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/BadRequestException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/BadRequestException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/BadRequestException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/BridgeInternal.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessor.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ChangeFeedProcessorOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ClientSideRequestStatistics.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CommonsBridgeInternal.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CompositePath.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CompositePath.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CompositePath.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CompositePath.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CompositePathSortOrder.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConflictException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConflictException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ConflictException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConflictException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionMode.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConflictResolutionPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConnectionMode.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConnectionMode.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ConnectionMode.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConnectionMode.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConnectionPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConsistencyLevel.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ConsistencyPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosBridgeInternal.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosClientBuilder.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosClientException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosClientException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosClientException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosClientException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosConflict.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictProperties.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictRequestOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosConflictResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosContainer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerProperties.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerRequestOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosContainerResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabase.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseProperties.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseRequestOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosDatabaseResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosError.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosError.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosError.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosError.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosItem.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosItemProperties.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosItemRequestOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosItemResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosPermission.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionProperties.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionRequestOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionRequestOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionRequestOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionRequestOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosPermissionResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosResourceType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosResourceType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosResourceType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosResourceType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosResponseDiagnostics.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosResponseDiagnostics.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosResponseDiagnostics.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosResponseDiagnostics.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosScripts.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedure.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureProperties.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureRequestOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosStoredProcedureResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosTrigger.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerProperties.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosTriggerResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUser.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunction.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionProperties.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUserDefinedFunctionResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUserProperties.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/CosmosUserResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/DataType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/DataType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/DataType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/DataType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ExcludedPath.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ExcludedPath.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ExcludedPath.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ExcludedPath.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/FeedOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/FeedOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/FeedOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/FeedOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/FeedResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/FeedResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/FeedResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/FeedResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/FeedResponseDiagnostics.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/FeedResponseDiagnostics.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/FeedResponseDiagnostics.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/FeedResponseDiagnostics.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ForbiddenException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ForbiddenException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ForbiddenException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ForbiddenException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/GoneException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/GoneException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/GoneException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/GoneException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/HashIndex.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/HashIndex.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/HashIndex.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/HashIndex.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/IncludedPath.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/IncludedPath.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/IncludedPath.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/IncludedPath.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/Index.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/Index.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/Index.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/Index.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/IndexKind.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/IndexKind.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/IndexKind.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/IndexKind.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/IndexingDirective.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/IndexingDirective.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/IndexingDirective.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/IndexingDirective.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/IndexingMode.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/IndexingMode.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/IndexingMode.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/IndexingMode.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/IndexingPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/IndexingPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/IndexingPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/IndexingPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/InternalServerErrorException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/InvalidPartitionException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/JsonSerializable.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/JsonSerializable.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/JsonSerializable.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/JsonSerializable.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/LockedException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/LockedException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/LockedException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/LockedException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/MethodNotAllowedException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/NotFoundException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/NotFoundException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/NotFoundException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/NotFoundException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionIsMigratingException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/PartitionKey.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKey.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/PartitionKey.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKey.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinition.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyDefinitionVersion.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeGoneException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKeyRangeIsSplittingException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/PartitionKind.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKind.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/PartitionKind.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PartitionKind.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/PermissionMode.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PermissionMode.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/PermissionMode.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PermissionMode.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/PreconditionFailedException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/RangeIndex.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RangeIndex.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/RangeIndex.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RangeIndex.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RequestEntityTooLargeException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RequestRateTooLargeException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RequestTimeoutException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/Resource.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/Resource.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/Resource.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/Resource.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/RetryOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RetryOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/RetryOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RetryOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/RetryWithException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RetryWithException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/RetryWithException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/RetryWithException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SerializationFormattingPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/ServiceUnavailableException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/SpatialIndex.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SpatialIndex.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/SpatialIndex.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SpatialIndex.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/SpatialSpec.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SpatialSpec.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/SpatialSpec.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SpatialSpec.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/SpatialType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SpatialType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/SpatialType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SpatialType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/SqlParameter.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SqlParameter.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/SqlParameter.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SqlParameter.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/SqlParameterList.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SqlParameterList.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/SqlParameterList.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SqlParameterList.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/SqlQuerySpec.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/TokenResolver.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/TokenResolver.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/TokenResolver.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/TokenResolver.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/TriggerOperation.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/TriggerOperation.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/TriggerOperation.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/TriggerOperation.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/TriggerType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/TriggerType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/TriggerType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/TriggerType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/UnauthorizedException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/UnauthorizedException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/UnauthorizedException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/UnauthorizedException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/UniqueKey.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/UniqueKey.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/UniqueKey.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/UniqueKey.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/UniqueKeyPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/AsyncDocumentClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/AsyncDocumentClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/AsyncDocumentClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/AsyncDocumentClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenProvider.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/AuthorizationTokenType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/BackoffRetryUtility.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/BaseAuthorizationTokenProvider.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/BaseDatabaseAccountConfigurationProvider.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Bytes.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Bytes.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Bytes.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Bytes.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ChangeFeedQueryImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ClearingSessionContainerClientRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ClientRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Configs.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Configs.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Configs.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Configs.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Conflict.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Conflict.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Conflict.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Conflict.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Constants.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Constants.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Constants.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Constants.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ContentSerializationFormat.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Database.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Database.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Database.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Database.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccount.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccount.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccount.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccount.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountConfigurationProvider.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountLocation.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountLocation.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountLocation.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountLocation.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountManagerInternal.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountManagerInternal.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountManagerInternal.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseAccountManagerInternal.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DatabaseForTest.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Document.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Document.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Document.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Document.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentCollection.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentCollection.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/DocumentCollection.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentCollection.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/DocumentServiceRequestContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/EnumerationDirection.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Exceptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Exceptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Exceptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Exceptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/FanoutOperationState.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/GlobalEndpointManager.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/IAuthorizationTokenProvider.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ICollectionRoutingMapCache.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/IDocumentClientRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/IRetryPolicyFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/IRoutingMapProvider.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ISessionContainer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ISessionContainer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ISessionContainer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ISessionContainer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ISessionToken.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Integers.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Integers.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Integers.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Integers.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/InternalConstants.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/InvalidPartitionExceptionRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/JavaStreamUtils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/LifeCycleUtils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Lists.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Lists.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Lists.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Lists.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Longs.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Longs.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Longs.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Longs.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/MigrateCollectionDirective.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/MutableVolatile.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ObservableHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Offer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Offer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Offer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Offer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/OperationType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/OperationType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/OperationType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/OperationType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyMismatchRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRange.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PartitionKeyRangeGoneRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/PathInfo.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PathInfo.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/PathInfo.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PathInfo.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/PathParser.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PathParser.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/PathParser.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PathParser.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Paths.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Paths.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Paths.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Paths.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/PathsHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Permission.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Permission.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Permission.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Permission.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Quadruple.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Quadruple.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Quadruple.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Quadruple.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/QueryCompatibilityMode.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetrics.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsConstants.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/QueryMetricsUtils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/QueryPreparationTimes.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RMResources.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RMResources.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RMResources.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RMResources.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ReadFeedKeyType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RemoteStorageType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ReplicatedResourceClientUtils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ReplicationPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RequestChargeTracker.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RequestOptions.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResetSessionTokenRetryPolicyFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceId.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceId.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ResourceId.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceId.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceThrottleRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceTokenAuthorizationHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/ResourceType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/ResourceType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RetryUtils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeConstants.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RuntimeExecutionTimes.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentClientImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceRequest.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RxDocumentServiceResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RxGatewayStoreModel.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/RxStoreModel.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/SessionContainer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/SessionTokenHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedure.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/StoredProcedureResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Strings.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Strings.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Strings.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Strings.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/TestConfigurations.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/TestConfigurations.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/TestConfigurations.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/TestConfigurations.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Trigger.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Trigger.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Trigger.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Trigger.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Undefined.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Undefined.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Undefined.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Undefined.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/User.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/User.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/User.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/User.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/UserAgentContainer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/UserDefinedFunction.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/Utils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Utils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/Utils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/Utils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/VectorSessionToken.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/WebExceptionRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncCache.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/AsyncLazy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/IEqualityComparer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/IPartitionKeyRangeCache.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxClientCollectionCache.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxCollectionCache.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/caches/RxPartitionKeyRangeCache.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Bootstrapper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Bootstrapper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Bootstrapper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Bootstrapper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationToken.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationToken.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationToken.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationToken.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationTokenSource.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationTokenSource.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationTokenSource.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CancellationTokenSource.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedContextClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserver.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserver.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserver.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserver.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverCloseReason.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverCloseReason.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverCloseReason.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverCloseReason.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ChangeFeedObserverFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CheckpointFrequency.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CheckpointFrequency.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CheckpointFrequency.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/CheckpointFrequency.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitor.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitor.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitor.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitor.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitoringRecord.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitoringRecord.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitoringRecord.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/HealthMonitoringRecord.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Lease.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Lease.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Lease.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/Lease.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseCheckpointer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseCheckpointer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseCheckpointer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseCheckpointer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseContainer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseContainer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseContainer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseContainer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseManager.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseManager.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseManager.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseManager.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseRenewer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseRenewer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseRenewer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseRenewer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStore.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStore.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStore.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStore.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManager.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManager.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManager.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManager.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/LeaseStoreManagerSettings.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionCheckpointer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionCheckpointer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionCheckpointer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionCheckpointer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionController.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionController.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionController.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionController.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancingStrategy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancingStrategy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancingStrategy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionLoadBalancingStrategy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionManager.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionManager.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionManager.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionManager.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessor.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessor.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessor.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessor.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessorFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessorFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessorFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionProcessorFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisor.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisor.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisor.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisor.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisorFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisorFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisorFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSupervisorFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSynchronizer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSynchronizer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSynchronizer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/PartitionSynchronizer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ProcessorSettings.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingPartitionWork.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingPartitionWork.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingPartitionWork.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingPartitionWork.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingWorkEstimator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingWorkEstimator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingWorkEstimator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RemainingWorkEstimator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RequestOptionsFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RequestOptionsFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RequestOptionsFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/RequestOptionsFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLease.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLeaseUpdater.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLeaseUpdater.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLeaseUpdater.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/ServiceItemLeaseUpdater.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/LeaseLostException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/LeaseLostException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/LeaseLostException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/LeaseLostException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/ObserverException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/ObserverException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/ObserverException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/ObserverException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionNotFoundException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionNotFoundException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionNotFoundException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionNotFoundException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionSplitException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionSplitException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionSplitException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/PartitionSplitException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/TaskCancelledException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/TaskCancelledException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/TaskCancelledException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/exceptions/TaskCancelledException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/AutoCheckpointer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/BootstrapperImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/BootstrapperImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/BootstrapperImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/BootstrapperImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedContextClientImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverContextImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverFactoryImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverFactoryImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverFactoryImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedObserverFactoryImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ChangeFeedProcessorBuilderImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/CheckpointerObserverFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/CheckpointerObserverFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/CheckpointerObserverFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/CheckpointerObserverFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/Constants.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/Constants.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/Constants.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/Constants.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserver.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserver.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserver.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserver.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserverFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserverFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserverFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DefaultObserverFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseStore.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseUpdaterImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseUpdaterImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseUpdaterImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/DocumentServiceLeaseUpdaterImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/EqualPartitionsBalancingStrategy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ExceptionClassifier.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ExceptionClassifier.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ExceptionClassifier.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ExceptionClassifier.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/HealthMonitoringPartitionControllerDecorator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/HealthMonitoringPartitionControllerDecorator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/HealthMonitoringPartitionControllerDecorator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/HealthMonitoringPartitionControllerDecorator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseRenewerImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseRenewerImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseRenewerImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseRenewerImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/LeaseStoreManagerImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/ObserverExceptionWrappingChangeFeedObserverDecorator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionCheckpointerImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionCheckpointerImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionCheckpointerImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionCheckpointerImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionControllerImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionControllerImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionControllerImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionControllerImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionLoadBalancerImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionLoadBalancerImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionLoadBalancerImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionLoadBalancerImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionManagerImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionManagerImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionManagerImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionManagerImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorFactoryImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionProcessorImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorFactoryImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSupervisorImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionSynchronizerImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/PartitionedByIdCollectionRequestOptionsFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingPartitionWorkImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingPartitionWorkImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingPartitionWorkImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingPartitionWorkImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingWorkEstimatorImpl.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingWorkEstimatorImpl.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingWorkEstimatorImpl.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/RemainingWorkEstimatorImpl.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/StatusCodeErrorType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/StatusCodeErrorType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/StatusCodeErrorType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/StatusCodeErrorType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/TraceHealthMonitor.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/TraceHealthMonitor.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/TraceHealthMonitor.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/TraceHealthMonitor.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/changefeed/implementation/WorkerTask.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Address.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Address.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Address.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Address.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressInformation.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressInformation.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressInformation.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressInformation.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolver.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelector.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelector.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelector.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelector.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReader.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriter.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/CustomHeaders.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/CustomHeaders.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/CustomHeaders.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/CustomHeaders.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ErrorUtils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ErrorUtils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ErrorUtils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ErrorUtils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCache.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReader.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolver.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicy.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientUtils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientUtils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientUtils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientUtils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressCache.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressCache.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressCache.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressCache.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressResolver.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressResolver.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressResolver.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IAddressResolver.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IStoreClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IStoreClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IStoreClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/IStoreClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Protocol.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Protocol.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Protocol.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/Protocol.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QueryRequestPerformanceActivity.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QueryRequestPerformanceActivity.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QueryRequestPerformanceActivity.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QueryRequestPerformanceActivity.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReader.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReader.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReader.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReader.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReadMode.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReadMode.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReadMode.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReadMode.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RequestHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RequestHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RequestHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RequestHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResourceOperation.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResourceOperation.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResourceOperation.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResourceOperation.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResponseUtils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResponseUtils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResponseUtils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ResponseUtils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerProperties.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerProperties.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerProperties.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerProperties.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerStoreModel.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerStoreModel.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerStoreModel.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServerStoreModel.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServiceConfig.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServiceConfig.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServiceConfig.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/ServiceConfig.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClientFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClientFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClientFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreClientFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreReader.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResult.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResult.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResult.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/StoreResult.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/TransportException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WFConstants.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WFConstants.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WFConstants.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WFConstants.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtility.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtility.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtility.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtility.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHandler.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHandler.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHandler.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHandler.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelPool.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelPool.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelPool.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelPool.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdConstants.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdConstants.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdConstants.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdConstants.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextDecoder.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextDecoder.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextDecoder.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextDecoder.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextException.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextException.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextException.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextException.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextNegotiator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextNegotiator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextNegotiator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextNegotiator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequest.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequest.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequest.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequest.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestDecoder.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdContextRequestEncoder.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdEndpoint.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdEndpoint.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdEndpoint.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdEndpoint.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdFramer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdFramer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdFramer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdFramer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdMetrics.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdMetrics.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdMetrics.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdMetrics.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdObjectMapper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdObjectMapper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdObjectMapper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdObjectMapper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdReporter.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdReporter.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdReporter.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdReporter.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequest.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequest.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequest.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequest.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestArgs.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestArgs.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestArgs.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestArgs.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestDecoder.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestDecoder.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestDecoder.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestDecoder.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestEncoder.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestEncoder.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestEncoder.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestEncoder.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFrame.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFrame.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFrame.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFrame.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFramer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFramer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFramer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestFramer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestHeaders.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestHeaders.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestHeaders.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestHeaders.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestManager.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestManager.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestManager.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestManager.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseDecoder.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseDecoder.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseDecoder.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseDecoder.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseHeaders.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseHeaders.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseHeaders.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseHeaders.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseStatus.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseStatus.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseStatus.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdResponseStatus.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdToken.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdToken.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdToken.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdToken.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenStream.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenStream.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenStream.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenStream.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdTokenType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdUUID.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdUUID.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdUUID.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdUUID.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/BufferedHttpResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpClientConfig.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeader.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpHeaders.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpRequest.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/HttpResponse.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/AggregateDocumentQueryExecutionContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/CompositeContinuationToken.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/DefaultDocumentQueryExecutionContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentProducer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextBase.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/DocumentQueryExecutionContextFactory.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ExceptionHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/Fetcher.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryClient.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/IDocumentQueryExecutionContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemComparator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ItemTypeHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByContinuationToken.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentProducer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByDocumentQueryExecutionContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/OrderByUtils.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/Paginator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelDocumentQueryExecutionContextBase.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ParallelQueryConfig.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfo.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/PartitionedQueryExecutionInfoInternal.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/PipelinedDocumentQueryExecutionContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/ProxyDocumentQueryExecutionContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryInfo.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/QueryItem.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/SortOrder.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/TakeContinuationToken.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/TopDocumentQueryExecutionContext.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/TriFunction.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AggregateOperator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/Aggregator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/AverageAggregator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/CountAggregator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MaxAggregator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/MinAggregator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/aggregation/SumAggregator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/ClientSideMetrics.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRange.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/FetchExecutionRangeAccumulator.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsTextWriter.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/QueryMetricsWriter.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingStopwatch.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/SchedulingTimeSpan.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/metrics/TextTable.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderByRowResult.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/query/orderbyquery/OrderbyRowComparer.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/BoolPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/CaseInsensitiveHashMap.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/CollectionRoutingMap.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/IPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/IServerIdentity.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMap.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/InfinityPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/Int128.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationCache.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/LocationHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxNumberPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MaxStringPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinNumberPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MinStringPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_128.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/MurmurHash3_32.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/NullPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/NumberPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyAndResourceTokenPair.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyComponentType.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternal.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/PartitionKeyRangeIdentity.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/Range.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/Range.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/Range.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/Range.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProvider.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelper.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/UInt128.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/internal/routing/UndefinedPartitionKeyComponent.java diff --git a/sdk/src/main/java/com/azure/data/cosmos/package-info.java b/sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/package-info.java similarity index 100% rename from sdk/src/main/java/com/azure/data/cosmos/package-info.java rename to sdk/cosmos/sdk/src/main/java/com/azure/data/cosmos/package-info.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/BridgeUtils.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/BridgeUtils.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/BridgeUtils.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/BridgeUtils.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/ClientUnderTestBuilder.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/ConflictTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/ConflictTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/ConflictTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/ConflictTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/ConnectionPolicyTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/CosmosClientExceptionTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/CosmosClientTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/CosmosDatabaseForTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/CosmosPartitionKeyTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/CosmosResponseValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/DocumentClientTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/DocumentCollectionTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/DocumentTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/DocumentTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/DocumentTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/DocumentTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/GatewayTestUtils.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/IncludedPathTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/IncludedPathTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/IncludedPathTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/IncludedPathTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/JsonSerializableTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/PartitionKeyHashingTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/PermissionTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/PermissionTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/PermissionTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/PermissionTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/ResourceIdTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/ResourceIdTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/ResourceIdTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/ResourceIdTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ClientRetryPolicyTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsBuilder.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsBuilder.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsBuilder.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsBuilder.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ConfigsTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests1.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTests2.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ConsistencyTestsBase.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentQuerySpyWireContentTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestContextValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestContextValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestContextValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestContextValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/DocumentServiceRequestValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/FailureValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/FailureValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/FailureValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/FailureValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseListValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/FeedResponseValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/HttpClientUnderTestWrapper.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/HttpClientUnderTestWrapper.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/HttpClientUnderTestWrapper.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/HttpClientUnderTestWrapper.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/LocationHelperTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/NetworkFailureTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ParallelAsync.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/PathsHelperTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RenameCollectionAwareClientRetryPolicyTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceResponseValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/ResourceValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ResourceValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryAnalyzer.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RetryAnalyzer.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/RetryAnalyzer.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RetryAnalyzer.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RetryCreateDocumentTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RetryThrottleTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RetryUtilsTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentClientUnderTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RxDocumentServiceRequestTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/RxGatewayStoreModelTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/SessionContainerTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/SessionTokenTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/ShouldRetryValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientBuilder.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientBuilder.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientBuilder.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientBuilder.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/SpyClientUnderTestFactory.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/StoreHeaderTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/StoreResponseBuilder.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/StoreResponseBuilder.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/StoreResponseBuilder.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/StoreResponseBuilder.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/TestSuiteBase.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/TestUtils.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/TimeTokenTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/caches/AsyncCacheTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressResolverTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorWrapper.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorWrapper.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorWrapper.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressSelectorWrapper.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/AddressValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/BarrierRequestHelperTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyReaderUnderTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ConsistencyWriterTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/DCDocumentCrudTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/EndpointMock.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/EndpointMock.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/EndpointMock.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/EndpointMock.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ExceptionBuilder.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ExceptionBuilder.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ExceptionBuilder.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ExceptionBuilder.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function1WithCheckedException.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function1WithCheckedException.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function1WithCheckedException.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function1WithCheckedException.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function2WithCheckedException.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function2WithCheckedException.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function2WithCheckedException.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/Function2WithCheckedException.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayAddressCacheTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfigurationReaderTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GatewayServiceConfiguratorReaderMock.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GlobalAddressResolverTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/GoneAndRetryWithRetryPolicyTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientMockWrapper.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientMockWrapper.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientMockWrapper.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpClientMockWrapper.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClientTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClientTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClientTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpTransportClientTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtilsTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtilsTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtilsTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/HttpUtilsTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MultiStoreResultValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MultiStoreResultValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MultiStoreResultValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MultiStoreResultValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MurmurHash3_32Test.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MurmurHash3_32Test.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MurmurHash3_32Test.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/MurmurHash3_32Test.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyInternalTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionKeyTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionReplicasAddressesValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionReplicasAddressesValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionReplicasAddressesValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/PartitionReplicasAddressesValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/QuorumReaderTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReflectionUtils.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicaAddressFactory.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicaAddressFactory.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicaAddressFactory.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicaAddressFactory.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientPartitionSplitTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/ReplicatedResourceClientTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderDotNetTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreReaderUnderTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResponseValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResultValidator.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResultValidator.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResultValidator.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/StoreResultValidator.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelperTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelperTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelperTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TimeoutHelperTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TransportClientWrapper.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TransportClientWrapper.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TransportClientWrapper.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/TransportClientWrapper.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtilityTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtilityTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtilityTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/directconnectivity/WebExceptionUtilityTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/query/DocumentProducerTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/query/FeedResponseBuilder.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/query/FetcherTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/routing/InMemoryCollectionRoutingMapTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/routing/LocationCacheTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/routing/PartitionKeyInternalUtils.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/routing/RoutingMapProviderHelperTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/internal/routing/StringPartitionKeyComponentTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/AggregateQueryTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureCrossPartitionTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/BackPressureTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedProcessorTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ChangeFeedTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionCrudTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/CollectionQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/CosmosConflictTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseCrudTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/DatabaseQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentClientResourceLeakTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/DocumentCrudTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/LogLevelTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/MultiMasterConflictResolutionTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/MultiOrderByQueryTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/OfferQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/OfferReadReplaceTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/OrderbyDocumentQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ParallelDocumentQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ParsingEnvTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionCrudTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/PermissionQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ProxyHostTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedCollectionsTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDatabasesTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedDocumentsTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedExceptionHandlingTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedOffersTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPermissionsTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedPkrTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedStoredProceduresTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedTriggersTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUdfsTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ReadFeedUsersTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/ResourceTokenTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/SimpleSerializationTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionDocumentQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/SinglePartitionReadFeedDocumentsTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureCrudTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/StoredProcedureUpsertReplaceTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TestSuiteBase.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TokenResolverTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TopQueryTests.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerCrudTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/TriggerUpsertReplaceTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UniqueIndexTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UserCrudTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionCrudTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UserDefinedFunctionUpsertReplaceTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/UserQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/VeryLargeDocumentQueryTest.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyChannelInitializer.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHandler.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHeader.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHeader.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHeader.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyClientHeader.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyRemoteHandler.java diff --git a/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java b/sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java similarity index 100% rename from sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java rename to sdk/cosmos/sdk/src/test/java/com/azure/data/cosmos/rx/proxy/HttpProxyServer.java diff --git a/sdk/src/test/resources/Microsoft.jpg b/sdk/cosmos/sdk/src/test/resources/Microsoft.jpg similarity index 100% rename from sdk/src/test/resources/Microsoft.jpg rename to sdk/cosmos/sdk/src/test/resources/Microsoft.jpg diff --git a/sdk/src/test/resources/cosmosdb-1.png b/sdk/cosmos/sdk/src/test/resources/cosmosdb-1.png similarity index 100% rename from sdk/src/test/resources/cosmosdb-1.png rename to sdk/cosmos/sdk/src/test/resources/cosmosdb-1.png diff --git a/sdk/src/test/resources/databaseAccount.json b/sdk/cosmos/sdk/src/test/resources/databaseAccount.json similarity index 100% rename from sdk/src/test/resources/databaseAccount.json rename to sdk/cosmos/sdk/src/test/resources/databaseAccount.json diff --git a/sdk/src/test/resources/emulator-testng.xml b/sdk/cosmos/sdk/src/test/resources/emulator-testng.xml similarity index 100% rename from sdk/src/test/resources/emulator-testng.xml rename to sdk/cosmos/sdk/src/test/resources/emulator-testng.xml diff --git a/sdk/src/test/resources/fast-testng.xml b/sdk/cosmos/sdk/src/test/resources/fast-testng.xml similarity index 100% rename from sdk/src/test/resources/fast-testng.xml rename to sdk/cosmos/sdk/src/test/resources/fast-testng.xml diff --git a/sdk/src/test/resources/log4j.properties b/sdk/cosmos/sdk/src/test/resources/log4j.properties similarity index 100% rename from sdk/src/test/resources/log4j.properties rename to sdk/cosmos/sdk/src/test/resources/log4j.properties diff --git a/sdk/src/test/resources/long-testng.xml b/sdk/cosmos/sdk/src/test/resources/long-testng.xml similarity index 100% rename from sdk/src/test/resources/long-testng.xml rename to sdk/cosmos/sdk/src/test/resources/long-testng.xml diff --git a/sdk/src/test/resources/sampleConflict.json b/sdk/cosmos/sdk/src/test/resources/sampleConflict.json similarity index 100% rename from sdk/src/test/resources/sampleConflict.json rename to sdk/cosmos/sdk/src/test/resources/sampleConflict.json From 3f4343590947eb19fe17025a65d2308c5353ad48 Mon Sep 17 00:00:00 2001 From: Pareekshit Singh <35941423+praries880@users.noreply.github.com> Date: Wed, 10 Jul 2019 14:27:17 -0700 Subject: [PATCH 60/85] Ado mgmt ci support (#4273) * add support for ADO CI * fix pipeline config file * update file matching patern * Add script to generate the mgmt pom file at runtime * add step to generate the mgmt pom file * fix yml * fix file paths * fix build options * remove unwanted flag * remove the am flag * add debuging info to script * add more debugging info and modify build cmd * update build cmd * add back options * add debug flag to mvn cmd * add new script to build each sdk individually * add simpler script to do the build * move script to under eng/pipelines * fix script path * add script working directory * add more options to the shell script cmd * fix path under which cmd executes * move the mgmt yml to eng/pipelines * move the mgmt yml directly under eng/pipelines * add debug info * Add more debug infoi * Add java version args to script and suport java 7 and 8 * Fix script * uncomment build cmd in script * move default options to script * add suport for custom maven goals * fix arguments passed to mvn cmd * fix arg checks in script * Fix pipeline yml * change variable type from external to pipeline * fix script * fix script --- eng/pipelines/mgmt.yml | 38 ++++++++++++++ eng/pipelines/scripts/mgmt_sdk_compiler.sh | 58 ++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 eng/pipelines/mgmt.yml create mode 100644 eng/pipelines/scripts/mgmt_sdk_compiler.sh diff --git a/eng/pipelines/mgmt.yml b/eng/pipelines/mgmt.yml new file mode 100644 index 0000000000000..c9c850dcc8202 --- /dev/null +++ b/eng/pipelines/mgmt.yml @@ -0,0 +1,38 @@ +trigger: + - master + +variables: + MavenGoals: 'clean,compile' + +jobs: + - job: 'Build' + + strategy: + matrix: + Java 8: + ArtifactName: 'packages' + JavaVersion: '1.8' + Java 7: + ArtifactName: 'packages' + JavaVersion: '1.7' + + pool: + vmImage: 'ubuntu-16.04' + + steps: + - task: ShellScript@2 + displayName: 'call mvn for each mgmt sdk individually' + inputs: + scriptPath: "$(System.DefaultWorkingDirectory)/eng/pipelines/scripts/mgmt_sdk_compiler.sh" + workingDirectory: "$(System.DefaultWorkingDirectory)" + failOnStandardError: true + args: "$(JavaVersion) $(MavenGoals)" + + - task: PublishTestResults@2 + condition: succeededOrFailed() + inputs: + mergeTestResults: true + testRunTitle: 'On Java $(JavaVersion)' + + + \ No newline at end of file diff --git a/eng/pipelines/scripts/mgmt_sdk_compiler.sh b/eng/pipelines/scripts/mgmt_sdk_compiler.sh new file mode 100644 index 0000000000000..af6ce2f2c2dd5 --- /dev/null +++ b/eng/pipelines/scripts/mgmt_sdk_compiler.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash + +#args expected +# $1. Java version : 1.7 or 1,8, defaults to "1.8" +# $2. Goals, defaults to "clean compile", value expected is a comma delemited string eg : "clean,compile" + +echo "#### CWD : " +pwd + +echo "#### versions of java available:" +ls /usr/lib/jvm + +echo "#### Original java home $JAVA_HOME" + +JAVA7HOME="/usr/lib/jvm/zulu-7-azure-amd64" +JAVA8HOME="/usr/lib/jvm/zulu-8-azure-amd64" + +JAVAHOME="$JAVA8HOME" + +MAVENGOALS="clean compile" + +if [ -n "$1" ] && [ "$1" == "1.7" ]; +then + JAVAHOME="$JAVA7HOME"; + echo "runing java 7 build"; +fi + + +if [ -n "$2" ]; +then + TEMP_VAL=$(echo "$2" | sed -r 's/,/ /g') + MAVENGOALS="$TEMP_VAL"; + echo "maven goals overriden to $MAVENGOALS" +fi + +export JAVA_HOME="$JAVAHOME" + +echo "#### Using java at : $JAVA_HOME" + +echo "#### Maven properties:" +mvn --version + +#TODO: +#for some reason the workingdirectory dos not seem to work... +#fix the following cd cmd once we figure out how to get it to work +#change to the root of the sources repo +cd ../../.. + +for i in `ls -d */*/v20* | grep -v "node_modules/*/*"`; +do + echo "######## building folder $i" + cd $i; + mvn --batch-mode -Dgpg.skip -Dmaven.wagon.http.pool=false -Dorg.slf4j.simpleLogger.defaultLogLevel=error -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warns $MAVENGOALS; + if [ $? != 0 ]; + then cd -; exit -1; + else cd -; + fi; +done From 5b351d333bedc24ac9d65b734359cdd8679aa3ed Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Wed, 10 Jul 2019 15:01:14 -0700 Subject: [PATCH 61/85] Setup eventhubs ci configs. (#4378) --- sdk/eventhubs/ci.yml | 23 +++++++++++++++++++++++ sdk/eventhubs/pom.service.xml | 17 +++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 sdk/eventhubs/ci.yml create mode 100644 sdk/eventhubs/pom.service.xml diff --git a/sdk/eventhubs/ci.yml b/sdk/eventhubs/ci.yml new file mode 100644 index 0000000000000..545d53726cace --- /dev/null +++ b/sdk/eventhubs/ci.yml @@ -0,0 +1,23 @@ +# DO NOT EDIT THIS FILE +# This file is generated automatically and any changes will be lost. + +trigger: + branches: + include: + - master + paths: + include: + - sdk/eventhubs/ + +pr: + branches: + include: + - master + paths: + include: + - sdk/eventhubs/ + +jobs: + - template: ../../eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: eventhubs \ No newline at end of file diff --git a/sdk/eventhubs/pom.service.xml b/sdk/eventhubs/pom.service.xml new file mode 100644 index 0000000000000..d95966da50fc7 --- /dev/null +++ b/sdk/eventhubs/pom.service.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + com.azure + azure-eventhubs-service + pom + 1.0.0 + + + + + + + From d7f7db257cdff89aaac61ff603ab85d94239ba23 Mon Sep 17 00:00:00 2001 From: Shawn Fang <45607042+mssfang@users.noreply.github.com> Date: Wed, 10 Jul 2019 15:21:24 -0700 Subject: [PATCH 62/85] suppress ExternalDependencyExposedCheck for track 1 (#4377) * suppression for track 1 * add no check on tests * add suppression for implementation --- .../src/main/resources/checkstyle/checkstyle-suppressions.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml b/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml index 09da6af09b39e..1f9752c52de54 100755 --- a/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml +++ b/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml @@ -85,4 +85,8 @@ + + + + From 728cc1cadba6930e71dd74d85bdec3e7ddbbb674 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Wed, 10 Jul 2019 15:59:35 -0700 Subject: [PATCH 63/85] Move eventhubs (#4380) * Base move. * Tweak POM files. --- pom.client.xml | 2 +- {eventhubs/client => sdk/eventhubs}/CHANGELOG.md | 0 {eventhubs/client => sdk/eventhubs}/CONTRIBUTING.md | 0 {eventhubs/client => sdk/eventhubs}/README.md | 0 {eventhubs/client => sdk/eventhubs}/azure-eventhubs/pom.xml | 0 .../main/java/com/azure/messaging/eventhubs/EventData.java | 0 .../java/com/azure/messaging/eventhubs/EventDataBatch.java | 0 .../java/com/azure/messaging/eventhubs/EventHubClient.java | 0 .../azure/messaging/eventhubs/EventHubClientBuilder.java | 0 .../com/azure/messaging/eventhubs/EventHubConsumer.java | 0 .../azure/messaging/eventhubs/EventHubConsumerOptions.java | 0 .../com/azure/messaging/eventhubs/EventHubProducer.java | 0 .../azure/messaging/eventhubs/EventHubProducerOptions.java | 0 .../com/azure/messaging/eventhubs/EventHubProperties.java | 0 .../eventhubs/EventHubSharedAccessKeyCredential.java | 0 .../java/com/azure/messaging/eventhubs/EventPosition.java | 0 .../com/azure/messaging/eventhubs/PartitionProperties.java | 0 .../azure/messaging/eventhubs/ProxyAuthenticationType.java | 0 .../com/azure/messaging/eventhubs/ProxyConfiguration.java | 0 .../java/com/azure/messaging/eventhubs/SendOptions.java | 0 .../eventhubs/implementation/ActiveClientTokenManager.java | 0 .../messaging/eventhubs/implementation/AmqpConstants.java | 0 .../messaging/eventhubs/implementation/AmqpErrorCode.java | 0 .../messaging/eventhubs/implementation/AmqpReceiveLink.java | 0 .../eventhubs/implementation/AmqpResponseMapper.java | 0 .../messaging/eventhubs/implementation/AmqpSendLink.java | 0 .../eventhubs/implementation/CBSAuthorizationType.java | 0 .../messaging/eventhubs/implementation/CBSChannel.java | 0 .../messaging/eventhubs/implementation/ClientConstants.java | 0 .../eventhubs/implementation/ConnectionOptions.java | 0 .../implementation/ConnectionStringProperties.java | 0 .../eventhubs/implementation/EndpointStateNotifierBase.java | 0 .../eventhubs/implementation/ErrorContextProvider.java | 0 .../messaging/eventhubs/implementation/EventDataUtil.java | 0 .../eventhubs/implementation/EventHubConnection.java | 0 .../eventhubs/implementation/EventHubManagementNode.java | 0 .../messaging/eventhubs/implementation/EventHubSession.java | 0 .../eventhubs/implementation/ManagementChannel.java | 0 .../eventhubs/implementation/ReactorConnection.java | 0 .../eventhubs/implementation/ReactorDispatcher.java | 0 .../messaging/eventhubs/implementation/ReactorExecutor.java | 0 .../eventhubs/implementation/ReactorHandlerProvider.java | 0 .../messaging/eventhubs/implementation/ReactorProvider.java | 0 .../messaging/eventhubs/implementation/ReactorReceiver.java | 0 .../messaging/eventhubs/implementation/ReactorSender.java | 0 .../messaging/eventhubs/implementation/ReactorSession.java | 0 .../eventhubs/implementation/RequestResponseChannel.java | 0 .../eventhubs/implementation/RetriableWorkItem.java | 0 .../messaging/eventhubs/implementation/StringUtil.java | 0 .../messaging/eventhubs/implementation/TimeoutTracker.java | 0 .../eventhubs/implementation/TokenResourceProvider.java | 0 .../eventhubs/implementation/handler/ConnectionHandler.java | 0 .../eventhubs/implementation/handler/CustomIOHandler.java | 0 .../eventhubs/implementation/handler/DispatchHandler.java | 0 .../messaging/eventhubs/implementation/handler/Handler.java | 0 .../eventhubs/implementation/handler/LinkHandler.java | 0 .../eventhubs/implementation/handler/ReactorHandler.java | 0 .../implementation/handler/ReceiveLinkHandler.java | 0 .../eventhubs/implementation/handler/SendLinkHandler.java | 0 .../eventhubs/implementation/handler/SessionHandler.java | 0 .../eventhubs/implementation/handler/package-info.java | 0 .../messaging/eventhubs/implementation/package-info.java | 0 .../java/com/azure/messaging/eventhubs/package-info.java | 0 .../azure-eventhubs/src/samples/java/ConsumeEvent.java | 0 .../java/ConsumeEventsFromKnownSequenceNumberPosition.java | 0 .../src/samples/java/GetEventHubMetadata.java | 0 .../azure-eventhubs/src/samples/java/PublishEvent.java | 0 .../src/samples/java/PublishEventsToSpecificPartition.java | 0 .../src/samples/java/PublishEventsWithCustomMetadata.java | 0 .../src/samples/java/PublishEventsWithPartitionKey.java | 0 .../messaging/eventhubs/EventDataJavaDocCodeSamples.java | 0 .../eventhubs/EventHubClientBuilderJavaDocCodeSamples.java | 0 .../eventhubs/EventHubConsumerJavaDocCodeSamples.java | 0 .../eventhubs/EventHubProducerJavaDocCodeSamples.java | 0 .../java/com/azure/messaging/eventhubs/BackCompatTest.java | 0 .../messaging/eventhubs/EventDataBatchIntegrationTest.java | 0 .../com/azure/messaging/eventhubs/EventDataBatchTest.java | 0 .../java/com/azure/messaging/eventhubs/EventDataTest.java | 0 .../messaging/eventhubs/EventHubClientBuilderTest.java | 0 .../messaging/eventhubs/EventHubClientIntegrationTest.java | 0 .../eventhubs/EventHubClientMetadataIntegrationTest.java | 0 .../eventhubs/EventHubConsumerIntegrationTest.java | 0 .../messaging/eventhubs/EventHubConsumerOptionsTest.java | 0 .../com/azure/messaging/eventhubs/EventHubConsumerTest.java | 0 .../messaging/eventhubs/EventHubProducerOptionsTest.java | 0 .../com/azure/messaging/eventhubs/EventHubProducerTest.java | 0 .../azure/messaging/eventhubs/EventHubPropertiesTest.java | 0 .../eventhubs/EventHubSharedAccessKeyCredentialTest.java | 0 .../messaging/eventhubs/EventPositionIntegrationTest.java | 0 .../messaging/eventhubs/InteropAmqpPropertiesTest.java | 0 .../azure/messaging/eventhubs/PartitionPropertiesTest.java | 0 .../azure/messaging/eventhubs/ProxyConfigurationTest.java | 0 .../java/com/azure/messaging/eventhubs/SendOptionsTest.java | 0 .../com/azure/messaging/eventhubs/SetPrefetchCountTest.java | 0 .../test/java/com/azure/messaging/eventhubs/TestUtils.java | 0 .../implementation/ActiveClientTokenManagerTest.java | 0 .../messaging/eventhubs/implementation/ApiTestBase.java | 0 .../messaging/eventhubs/implementation/CBSChannelTest.java | 0 .../implementation/ConnectionStringPropertiesTest.java | 0 .../implementation/EndpointStateNotifierBaseTest.java | 0 .../implementation/MockReactorHandlerProvider.java | 0 .../eventhubs/implementation/MockReactorProvider.java | 0 .../implementation/ReactorConnectionIntegrationTest.java | 0 .../eventhubs/implementation/ReactorConnectionTest.java | 0 .../eventhubs/implementation/ReactorReceiverTest.java | 0 .../eventhubs/implementation/ReactorSessionTest.java | 0 .../eventhubs/implementation/TokenResourceProviderTest.java | 0 .../implementation/handler/ConnectionHandlerTest.java | 0 .../implementation/handler/DispatchHandlerTest.java | 0 .../eventhubs/implementation/handler/HandlerTest.java | 0 sdk/eventhubs/pom.service.xml | 6 ++---- 111 files changed, 3 insertions(+), 5 deletions(-) rename {eventhubs/client => sdk/eventhubs}/CHANGELOG.md (100%) rename {eventhubs/client => sdk/eventhubs}/CONTRIBUTING.md (100%) rename {eventhubs/client => sdk/eventhubs}/README.md (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/pom.xml (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventData.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventDataBatch.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClient.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumerOptions.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducer.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducerOptions.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProperties.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubSharedAccessKeyCredential.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventPosition.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionProperties.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/ProxyAuthenticationType.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/ProxyConfiguration.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/SendOptions.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ActiveClientTokenManager.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpConstants.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpErrorCode.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLink.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpResponseMapper.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpSendLink.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/CBSAuthorizationType.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/CBSChannel.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ClientConstants.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ConnectionOptions.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ConnectionStringProperties.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EndpointStateNotifierBase.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ErrorContextProvider.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventDataUtil.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubConnection.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubManagementNode.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubSession.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ManagementChannel.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorConnection.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorDispatcher.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorExecutor.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorHandlerProvider.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorProvider.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorReceiver.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorSender.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorSession.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/RequestResponseChannel.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/RetriableWorkItem.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/StringUtil.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/TimeoutTracker.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/TokenResourceProvider.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ConnectionHandler.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/CustomIOHandler.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/DispatchHandler.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/Handler.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/LinkHandler.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ReactorHandler.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ReceiveLinkHandler.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/SendLinkHandler.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/SessionHandler.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/package-info.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/package-info.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/package-info.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/ConsumeEvent.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/ConsumeEventsFromKnownSequenceNumberPosition.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/GetEventHubMetadata.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/PublishEvent.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/PublishEventsToSpecificPartition.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/PublishEventsWithCustomMetadata.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/PublishEventsWithPartitionKey.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventDataJavaDocCodeSamples.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubClientBuilderJavaDocCodeSamples.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubConsumerJavaDocCodeSamples.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubProducerJavaDocCodeSamples.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/BackCompatTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataBatchIntegrationTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataBatchTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientBuilderTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientIntegrationTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientMetadataIntegrationTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerIntegrationTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerOptionsTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerOptionsTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubPropertiesTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubSharedAccessKeyCredentialTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionPropertiesTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyConfigurationTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SendOptionsTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/TestUtils.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ActiveClientTokenManagerTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ApiTestBase.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/CBSChannelTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ConnectionStringPropertiesTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EndpointStateNotifierBaseTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/MockReactorHandlerProvider.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/MockReactorProvider.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionIntegrationTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorReceiverTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorSessionTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/TokenResourceProviderTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/ConnectionHandlerTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/DispatchHandlerTest.java (100%) rename {eventhubs/client => sdk/eventhubs}/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/HandlerTest.java (100%) diff --git a/pom.client.xml b/pom.client.xml index 0d04e6b9d0273..b09118509b848 100644 --- a/pom.client.xml +++ b/pom.client.xml @@ -738,7 +738,7 @@ ./sdk/appconfiguration/azure-data-appconfiguration ./core - ./eventhubs/client/azure-eventhubs + ./sdk/eventhubs/azure-eventhubs ./sdk/keyvault/azure-keyvault-secrets ./sdk/keyvault/azure-keyvault-keys diff --git a/eventhubs/client/CHANGELOG.md b/sdk/eventhubs/CHANGELOG.md similarity index 100% rename from eventhubs/client/CHANGELOG.md rename to sdk/eventhubs/CHANGELOG.md diff --git a/eventhubs/client/CONTRIBUTING.md b/sdk/eventhubs/CONTRIBUTING.md similarity index 100% rename from eventhubs/client/CONTRIBUTING.md rename to sdk/eventhubs/CONTRIBUTING.md diff --git a/eventhubs/client/README.md b/sdk/eventhubs/README.md similarity index 100% rename from eventhubs/client/README.md rename to sdk/eventhubs/README.md diff --git a/eventhubs/client/azure-eventhubs/pom.xml b/sdk/eventhubs/azure-eventhubs/pom.xml similarity index 100% rename from eventhubs/client/azure-eventhubs/pom.xml rename to sdk/eventhubs/azure-eventhubs/pom.xml diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventData.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventData.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventData.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventData.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventDataBatch.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventDataBatch.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventDataBatch.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventDataBatch.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClient.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClient.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClient.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClient.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumerOptions.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumerOptions.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumerOptions.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumerOptions.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducer.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducer.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducer.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducer.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducerOptions.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducerOptions.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducerOptions.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducerOptions.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProperties.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProperties.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProperties.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProperties.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubSharedAccessKeyCredential.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubSharedAccessKeyCredential.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubSharedAccessKeyCredential.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubSharedAccessKeyCredential.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventPosition.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventPosition.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventPosition.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventPosition.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionProperties.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionProperties.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionProperties.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionProperties.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/ProxyAuthenticationType.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/ProxyAuthenticationType.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/ProxyAuthenticationType.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/ProxyAuthenticationType.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/ProxyConfiguration.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/ProxyConfiguration.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/ProxyConfiguration.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/ProxyConfiguration.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/SendOptions.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/SendOptions.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/SendOptions.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/SendOptions.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ActiveClientTokenManager.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ActiveClientTokenManager.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ActiveClientTokenManager.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ActiveClientTokenManager.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpConstants.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpConstants.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpConstants.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpConstants.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpErrorCode.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpErrorCode.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpErrorCode.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpErrorCode.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLink.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLink.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLink.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpReceiveLink.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpResponseMapper.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpResponseMapper.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpResponseMapper.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpResponseMapper.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpSendLink.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpSendLink.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpSendLink.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/AmqpSendLink.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/CBSAuthorizationType.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/CBSAuthorizationType.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/CBSAuthorizationType.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/CBSAuthorizationType.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/CBSChannel.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/CBSChannel.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/CBSChannel.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/CBSChannel.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ClientConstants.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ClientConstants.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ClientConstants.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ClientConstants.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ConnectionOptions.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ConnectionOptions.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ConnectionOptions.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ConnectionOptions.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ConnectionStringProperties.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ConnectionStringProperties.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ConnectionStringProperties.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ConnectionStringProperties.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EndpointStateNotifierBase.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EndpointStateNotifierBase.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EndpointStateNotifierBase.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EndpointStateNotifierBase.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ErrorContextProvider.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ErrorContextProvider.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ErrorContextProvider.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ErrorContextProvider.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventDataUtil.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventDataUtil.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventDataUtil.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventDataUtil.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubConnection.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubConnection.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubConnection.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubConnection.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubManagementNode.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubManagementNode.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubManagementNode.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubManagementNode.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubSession.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubSession.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubSession.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubSession.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ManagementChannel.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ManagementChannel.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ManagementChannel.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ManagementChannel.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorConnection.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorConnection.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorConnection.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorConnection.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorDispatcher.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorDispatcher.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorDispatcher.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorDispatcher.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorExecutor.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorExecutor.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorExecutor.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorExecutor.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorHandlerProvider.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorHandlerProvider.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorHandlerProvider.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorHandlerProvider.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorProvider.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorProvider.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorProvider.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorProvider.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorReceiver.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorReceiver.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorReceiver.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorReceiver.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorSender.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorSender.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorSender.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorSender.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorSession.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorSession.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorSession.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/ReactorSession.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/RequestResponseChannel.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/RequestResponseChannel.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/RequestResponseChannel.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/RequestResponseChannel.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/RetriableWorkItem.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/RetriableWorkItem.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/RetriableWorkItem.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/RetriableWorkItem.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/StringUtil.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/StringUtil.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/StringUtil.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/StringUtil.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/TimeoutTracker.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/TimeoutTracker.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/TimeoutTracker.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/TimeoutTracker.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/TokenResourceProvider.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/TokenResourceProvider.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/TokenResourceProvider.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/TokenResourceProvider.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ConnectionHandler.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ConnectionHandler.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ConnectionHandler.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ConnectionHandler.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/CustomIOHandler.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/CustomIOHandler.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/CustomIOHandler.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/CustomIOHandler.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/DispatchHandler.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/DispatchHandler.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/DispatchHandler.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/DispatchHandler.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/Handler.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/Handler.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/Handler.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/Handler.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/LinkHandler.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/LinkHandler.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/LinkHandler.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/LinkHandler.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ReactorHandler.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ReactorHandler.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ReactorHandler.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ReactorHandler.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ReceiveLinkHandler.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ReceiveLinkHandler.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ReceiveLinkHandler.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/ReceiveLinkHandler.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/SendLinkHandler.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/SendLinkHandler.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/SendLinkHandler.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/SendLinkHandler.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/SessionHandler.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/SessionHandler.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/SessionHandler.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/SessionHandler.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/package-info.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/package-info.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/package-info.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/handler/package-info.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/package-info.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/package-info.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/package-info.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/package-info.java diff --git a/eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/package-info.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/package-info.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/package-info.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/package-info.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/ConsumeEvent.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/ConsumeEvent.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/ConsumeEvent.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/ConsumeEvent.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/ConsumeEventsFromKnownSequenceNumberPosition.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/ConsumeEventsFromKnownSequenceNumberPosition.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/ConsumeEventsFromKnownSequenceNumberPosition.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/ConsumeEventsFromKnownSequenceNumberPosition.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/GetEventHubMetadata.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/GetEventHubMetadata.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/GetEventHubMetadata.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/GetEventHubMetadata.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/PublishEvent.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/PublishEvent.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/PublishEvent.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/PublishEvent.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/PublishEventsToSpecificPartition.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/PublishEventsToSpecificPartition.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/PublishEventsToSpecificPartition.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/PublishEventsToSpecificPartition.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/PublishEventsWithCustomMetadata.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/PublishEventsWithCustomMetadata.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/PublishEventsWithCustomMetadata.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/PublishEventsWithCustomMetadata.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/PublishEventsWithPartitionKey.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/PublishEventsWithPartitionKey.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/PublishEventsWithPartitionKey.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/PublishEventsWithPartitionKey.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventDataJavaDocCodeSamples.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventDataJavaDocCodeSamples.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventDataJavaDocCodeSamples.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventDataJavaDocCodeSamples.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubClientBuilderJavaDocCodeSamples.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubClientBuilderJavaDocCodeSamples.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubClientBuilderJavaDocCodeSamples.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubClientBuilderJavaDocCodeSamples.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubConsumerJavaDocCodeSamples.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubConsumerJavaDocCodeSamples.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubConsumerJavaDocCodeSamples.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubConsumerJavaDocCodeSamples.java diff --git a/eventhubs/client/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubProducerJavaDocCodeSamples.java b/sdk/eventhubs/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubProducerJavaDocCodeSamples.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubProducerJavaDocCodeSamples.java rename to sdk/eventhubs/azure-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventHubProducerJavaDocCodeSamples.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/BackCompatTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/BackCompatTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/BackCompatTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/BackCompatTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataBatchIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataBatchIntegrationTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataBatchIntegrationTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataBatchIntegrationTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataBatchTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataBatchTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataBatchTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataBatchTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventDataTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientBuilderTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientBuilderTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientBuilderTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientBuilderTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientIntegrationTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientIntegrationTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientIntegrationTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientMetadataIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientMetadataIntegrationTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientMetadataIntegrationTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientMetadataIntegrationTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerIntegrationTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerIntegrationTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerIntegrationTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerOptionsTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerOptionsTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerOptionsTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerOptionsTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerOptionsTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerOptionsTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerOptionsTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerOptionsTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubPropertiesTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubPropertiesTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubPropertiesTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubPropertiesTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubSharedAccessKeyCredentialTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubSharedAccessKeyCredentialTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubSharedAccessKeyCredentialTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubSharedAccessKeyCredentialTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionPropertiesTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionPropertiesTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionPropertiesTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionPropertiesTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyConfigurationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyConfigurationTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyConfigurationTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyConfigurationTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SendOptionsTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SendOptionsTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SendOptionsTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SendOptionsTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/TestUtils.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/TestUtils.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/TestUtils.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/TestUtils.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ActiveClientTokenManagerTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ActiveClientTokenManagerTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ActiveClientTokenManagerTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ActiveClientTokenManagerTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ApiTestBase.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ApiTestBase.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ApiTestBase.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ApiTestBase.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/CBSChannelTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/CBSChannelTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/CBSChannelTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/CBSChannelTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ConnectionStringPropertiesTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ConnectionStringPropertiesTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ConnectionStringPropertiesTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ConnectionStringPropertiesTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EndpointStateNotifierBaseTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EndpointStateNotifierBaseTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EndpointStateNotifierBaseTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EndpointStateNotifierBaseTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/MockReactorHandlerProvider.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/MockReactorHandlerProvider.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/MockReactorHandlerProvider.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/MockReactorHandlerProvider.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/MockReactorProvider.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/MockReactorProvider.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/MockReactorProvider.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/MockReactorProvider.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionIntegrationTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionIntegrationTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionIntegrationTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorReceiverTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorReceiverTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorReceiverTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorReceiverTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorSessionTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorSessionTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorSessionTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorSessionTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/TokenResourceProviderTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/TokenResourceProviderTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/TokenResourceProviderTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/TokenResourceProviderTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/ConnectionHandlerTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/ConnectionHandlerTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/ConnectionHandlerTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/ConnectionHandlerTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/DispatchHandlerTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/DispatchHandlerTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/DispatchHandlerTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/DispatchHandlerTest.java diff --git a/eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/HandlerTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/HandlerTest.java similarity index 100% rename from eventhubs/client/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/HandlerTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/handler/HandlerTest.java diff --git a/sdk/eventhubs/pom.service.xml b/sdk/eventhubs/pom.service.xml index d95966da50fc7..2f81bff7b40e9 100644 --- a/sdk/eventhubs/pom.service.xml +++ b/sdk/eventhubs/pom.service.xml @@ -9,9 +9,7 @@ pom 1.0.0 - - - + ../../core + azure-eventhubs - From f1db5ebf7532eed51a82a84191cb9b2f16d51962 Mon Sep 17 00:00:00 2001 From: Vinay Gera Date: Wed, 10 Jul 2019 19:47:49 -0700 Subject: [PATCH 64/85] Test run time optimizations (#4384) --- .../security/keyvault/keys/KeyAsyncClientTest.java | 12 ++++++------ .../security/keyvault/keys/KeyClientTest.java | 4 ++-- .../keyvault/secrets/SecretAsyncClientTest.java | 14 +++++++------- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/sdk/keyvault/azure-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java b/sdk/keyvault/azure-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java index 2600b68df917c..dd0b711996b88 100644 --- a/sdk/keyvault/azure-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java +++ b/sdk/keyvault/azure-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyAsyncClientTest.java @@ -337,7 +337,7 @@ public void getDeletedKey() { assertNotNull(deletedKey); }).verifyComplete(); pollOnKeyDeletion(keyToDeleteAndGet.name()); - sleep(30000); + sleepInRecordMode(30000); StepVerifier.create(client.getDeletedKey(keyToDeleteAndGet.name())) .assertNext(deletedKeyResponse -> { @@ -353,7 +353,7 @@ public void getDeletedKey() { assertEquals(HttpResponseStatus.NO_CONTENT.code(), voidResponse.statusCode()); }).verifyComplete(); pollOnKeyPurge(keyToDeleteAndGet.name()); - sleep(15000); + sleepInRecordMode(15000); }); } // @@ -421,9 +421,9 @@ public void listKeyVersions() { client.createKey(key).subscribe(keyResponse -> assertKeyEquals(key, keyResponse.value())); sleepInRecordMode(1000); } - sleep(30000); + sleepInRecordMode(30000); client.listKeyVersions(keyName).subscribe(output::add); - sleep(30000); + sleepInRecordMode(30000); assertEquals(keyVersions.size(), output.size()); @@ -455,9 +455,9 @@ public void listKeys() { client.createKey(key).subscribe(keyResponse -> assertKeyEquals(key, keyResponse.value())); sleepInRecordMode(1000); } - sleep(30000); + sleepInRecordMode(30000); client.listKeys().subscribe(output::add); - sleep(30000); + sleepInRecordMode(30000); for (KeyBase actualKey : output) { if (keys.containsKey(actualKey.name())) { diff --git a/sdk/keyvault/azure-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java b/sdk/keyvault/azure-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java index 8b3eb47ac5763..a07fa17a52de8 100644 --- a/sdk/keyvault/azure-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java +++ b/sdk/keyvault/azure-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTest.java @@ -217,7 +217,7 @@ public void restoreKey() { pollOnKeyDeletion(keyToBackupAndRestore.name()); client.purgeDeletedKey(keyToBackupAndRestore.name()); pollOnKeyPurge(keyToBackupAndRestore.name()); - sleep(60000); + sleepInRecordMode(60000); Key restoredKey = client.restoreKey(backupBytes).value(); assertEquals(keyToBackupAndRestore.name(), restoredKey.name()); assertEquals(keyToBackupAndRestore.expires(), restoredKey.expires()); @@ -240,7 +240,7 @@ public void listKeys() { HashMap keysToList = keys; for (KeyCreateOptions key : keysToList.values()) { assertKeyEquals(key, client.createKey(key)); - sleep(5000); + sleepInRecordMode(5000); } for (KeyBase actualKey : client.listKeys()) { diff --git a/sdk/keyvault/azure-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java b/sdk/keyvault/azure-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java index bbae5720cb30b..2e11cd2c52487 100644 --- a/sdk/keyvault/azure-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java +++ b/sdk/keyvault/azure-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretAsyncClientTest.java @@ -217,7 +217,7 @@ public void getDeletedSecret() { assertNotNull(deletedSecret); }).verifyComplete(); pollOnSecretDeletion(secretToDeleteAndGet.name()); - sleep(30000); + sleepInRecordMode(30000); StepVerifier.create(client.getDeletedSecret(secretToDeleteAndGet.name())) .assertNext(deletedSecretResponse -> { @@ -233,7 +233,7 @@ public void getDeletedSecret() { assertEquals(HttpResponseStatus.NO_CONTENT.code(), voidResponse.statusCode()); }).verifyComplete(); pollOnSecretPurge(secretToDeleteAndGet.name()); - sleep(10000); + sleepInRecordMode(10000); }); } @@ -331,7 +331,7 @@ public void restoreSecret() { }).verifyComplete(); pollOnSecretPurge(secretToBackupAndRestore.name()); - sleep(60000); + sleepInRecordMode(60000); StepVerifier.create(client.restoreSecret(backup)) .assertNext(response -> { @@ -416,9 +416,9 @@ public void listSecretVersions() { client.setSecret(secret).subscribe(secretResponse -> assertSecretEquals(secret, secretResponse.value())); sleepInRecordMode(1000); } - sleep(30000); + sleepInRecordMode(30000); client.listSecretVersions(secretName).subscribe(output::add); - sleep(30000); + sleepInRecordMode(30000); assertEquals(secretVersions.size(), output.size()); @@ -450,9 +450,9 @@ public void listSecrets() { client.setSecret(secret).subscribe(secretResponse -> assertSecretEquals(secret, secretResponse.value())); sleepInRecordMode(1000); } - sleep(30000); + sleepInRecordMode(30000); client.listSecrets().subscribe(output::add); - sleep(30000); + sleepInRecordMode(30000); for (SecretBase actualSecret : output) { if (secretsToList.containsKey(actualSecret.name())) { From 20ae4fc5f1f8ad876f9a9083029a649bf4eb2da9 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Wed, 10 Jul 2019 20:20:58 -0700 Subject: [PATCH 65/85] Fix doc link (#4381) * Fixed up broken links. * Relocated eventhubs markdown files. --- README.md | 10 +++++----- sdk/eventhubs/{ => azure-eventhubs}/CHANGELOG.md | 0 sdk/eventhubs/{ => azure-eventhubs}/CONTRIBUTING.md | 0 sdk/eventhubs/{ => azure-eventhubs}/README.md | 0 4 files changed, 5 insertions(+), 5 deletions(-) rename sdk/eventhubs/{ => azure-eventhubs}/CHANGELOG.md (100%) rename sdk/eventhubs/{ => azure-eventhubs}/CONTRIBUTING.md (100%) rename sdk/eventhubs/{ => azure-eventhubs}/README.md (100%) diff --git a/README.md b/README.md index 02243f5344921..729c5d70bc3ca 100644 --- a/README.md +++ b/README.md @@ -29,11 +29,11 @@ New wave of packages that we are currently releasing in **preview**. These libra These preview libraries can be easily identified by their folder, package, and namespaces names starting with `azure-`, e.g. `azure-keyvault`. The libraries released in the July 2019 preview: -- [App Configuration](appconfiguration/client/README.md) -- [Event Hubs](eventhubs/client/README.md) -- [Identity](sdk/identity/azure-identity) -- [Key Vault Keys](keyvault/client/keys/README.md) -- [Key Vault Secrets](keyvault/client/secrets/README.md) +- [App Configuration](sdk/appconfiguration/azure-data-appconfiguration/README.md) +- [Event Hubs](sdk/eventhubs/azure-eventhubs/README.md) +- [Identity](sdk/identity/azure-identity/README.md) +- [Key Vault Keys](sdk/keyvault/azure-keyvault-keys/README.md) +- [Key Vault Secrets](sdk/keyvault/client/azure-keyvault-secrets/README.md) - [Storage Blobs](storage/client/README.md) >NOTE: If you need to ensure your code is ready for production, use one of the stable libraries. diff --git a/sdk/eventhubs/CHANGELOG.md b/sdk/eventhubs/azure-eventhubs/CHANGELOG.md similarity index 100% rename from sdk/eventhubs/CHANGELOG.md rename to sdk/eventhubs/azure-eventhubs/CHANGELOG.md diff --git a/sdk/eventhubs/CONTRIBUTING.md b/sdk/eventhubs/azure-eventhubs/CONTRIBUTING.md similarity index 100% rename from sdk/eventhubs/CONTRIBUTING.md rename to sdk/eventhubs/azure-eventhubs/CONTRIBUTING.md diff --git a/sdk/eventhubs/README.md b/sdk/eventhubs/azure-eventhubs/README.md similarity index 100% rename from sdk/eventhubs/README.md rename to sdk/eventhubs/azure-eventhubs/README.md From 206e51e66ee2857f5767ad8cf4a9d9986868da1a Mon Sep 17 00:00:00 2001 From: Daniel Jurek Date: Thu, 11 Jul 2019 08:54:51 -0700 Subject: [PATCH 66/85] add CODEOWNERS (#4386) --- .github/CODEOWNERS | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000000000..ec0dab9ffce39 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +# See for instructions on this file https://help.github.com/articles/about-codeowners/ From d8a042014a78e8ddc1be789990208405cc340604 Mon Sep 17 00:00:00 2001 From: Vinay Gera Date: Thu, 11 Jul 2019 10:55:13 -0700 Subject: [PATCH 67/85] Kv readme update (#4385) Update KV Readme --- sdk/keyvault/azure-keyvault-keys/README.md | 2 +- sdk/keyvault/azure-keyvault-secrets/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/keyvault/azure-keyvault-keys/README.md b/sdk/keyvault/azure-keyvault-keys/README.md index 33419a0b7dd58..e0899f1f273f7 100644 --- a/sdk/keyvault/azure-keyvault-keys/README.md +++ b/sdk/keyvault/azure-keyvault-keys/README.md @@ -303,7 +303,7 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope [source_code]: https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/keyvault/azure-keyvault-keys/src -[api_documentation]: not-valid-link +[api_documentation]: https://azure.github.io/azure-sdk-for-java/track2reports/index.html [azkeyvault_docs]: https://docs.microsoft.com/en-us/azure/key-vault/ [azure_identity]: https://github.com/Azure/azure-sdk-for-java/tree/master/identity/client [maven]: https://maven.apache.org/ diff --git a/sdk/keyvault/azure-keyvault-secrets/README.md b/sdk/keyvault/azure-keyvault-secrets/README.md index e8ffe95e55d5e..70a2c89a0c2ae 100644 --- a/sdk/keyvault/azure-keyvault-secrets/README.md +++ b/sdk/keyvault/azure-keyvault-secrets/README.md @@ -287,7 +287,7 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope [source_code]: https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/keyvault/azure-keyvault-secrets/src -[api_documentation]: not-valid-link +[api_documentation]: https://azure.github.io/azure-sdk-for-java/track2reports/index.html [azure_identity]: https://github.com/Azure/azure-sdk-for-java/tree/master/identity/client [azkeyvault_docs]: https://docs.microsoft.com/en-us/azure/key-vault/ [maven]: https://maven.apache.org/ From ad59dd9e626203bbf2d6720b11f0fdec29bf1821 Mon Sep 17 00:00:00 2001 From: Shawn Fang <45607042+mssfang@users.noreply.github.com> Date: Thu, 11 Jul 2019 13:03:21 -0700 Subject: [PATCH 68/85] [Fix] Custom-CheckStyle: No-External-Dependency in Public API (#4389) * remove java code isImple check but move to suppression and add only check for public class for external Dependency check * use AccessModifier --- .../ExternalDependencyExposedCheck.java | 22 +++++++++---------- .../checkstyle/checkstyle-suppressions.xml | 6 ++++- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/ExternalDependencyExposedCheck.java b/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/ExternalDependencyExposedCheck.java index 6c4a730d5a99c..b36f28e10be83 100644 --- a/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/ExternalDependencyExposedCheck.java +++ b/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/ExternalDependencyExposedCheck.java @@ -29,12 +29,12 @@ public class ExternalDependencyExposedCheck extends AbstractCheck { ))); private final Map simpleClassNameToQualifiedNameMap = new HashMap<>(); - private static boolean isImplPackage; + + private boolean isPublicClass; @Override public void beginTree(DetailAST rootAST) { simpleClassNameToQualifiedNameMap.clear(); - isImplPackage = false; } @Override @@ -50,7 +50,6 @@ public int[] getAcceptableTokens() { @Override public int[] getRequiredTokens() { return new int[] { - TokenTypes.PACKAGE_DEF, TokenTypes.IMPORT, TokenTypes.METHOD_DEF }; @@ -58,22 +57,23 @@ public int[] getRequiredTokens() { @Override public void visitToken(DetailAST token) { - if (isImplPackage) { - return; - } - switch (token.getType()) { - case TokenTypes.PACKAGE_DEF: - String packageName = FullIdent.createFullIdent(token.findFirstToken(TokenTypes.DOT)).getText(); - isImplPackage = packageName.contains(".implementation"); - break; case TokenTypes.IMPORT: // Add all imported classes into a map, key is the name of class and value is the full package path of class. final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; + case TokenTypes.CLASS_DEF: + // CLASS_DEF always has MODIFIERS + final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken( + token.findFirstToken(TokenTypes.MODIFIERS)); + isPublicClass = accessModifier.equals(AccessModifier.PUBLIC); + break; case TokenTypes.METHOD_DEF: + if (!isPublicClass) { + return; + } checkNoExternalDependencyExposed(token); break; default: diff --git a/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml b/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml index 1f9752c52de54..ac7af8e887727 100755 --- a/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml +++ b/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml @@ -86,7 +86,11 @@ - + + + + + From 3d7e7bae58af98611afed4d56d79c6dc333ffd1a Mon Sep 17 00:00:00 2001 From: Jonathan Giles Date: Fri, 12 Jul 2019 10:30:47 +1200 Subject: [PATCH 69/85] Fixing a few reporting issues (#4392) Fixing a few reporting issues where directories have changed and not been updated in the reporting config. --- eng/code-quality-reports/pom.xml | 14 ---- eng/jacoco-test-coverage/pom.xml | 9 +++ eng/spotbugs-aggregate-report/pom.xml | 78 ++++++++++++++----- pom.client.xml | 11 ++- .../SecretClientJavaDocCodeSnippets.java | 2 +- 5 files changed, 72 insertions(+), 42 deletions(-) diff --git a/eng/code-quality-reports/pom.xml b/eng/code-quality-reports/pom.xml index 78fe8ebfdc4b6..d3f7756700b82 100755 --- a/eng/code-quality-reports/pom.xml +++ b/eng/code-quality-reports/pom.xml @@ -12,7 +12,6 @@ UTF-8 - 9.2.22.v20170606 https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java @@ -61,19 +60,6 @@ - - - org.eclipse.jetty - jetty-maven-plugin - ${jetty-maven-plugin.version} - - 0 - 11079 - STOP - false - ./jetty.xml - - org.apache.maven.plugins maven-site-plugin diff --git a/eng/jacoco-test-coverage/pom.xml b/eng/jacoco-test-coverage/pom.xml index b6567bd45d9e5..ea21a08695cb7 100644 --- a/eng/jacoco-test-coverage/pom.xml +++ b/eng/jacoco-test-coverage/pom.xml @@ -24,10 +24,14 @@ 1.0.0-preview.3 + 1.0.0-preview.3 + 1.0.0-preview.3 + 1.0.0-preview.3 1.0.0-preview.1 1.0.0-preview.1 4.0.0-preview.1 5.0.0-preview.2 + 12.0.0-preview.1 @@ -84,6 +88,11 @@ azure-messaging-eventhubs ${azure-messaging-eventhubs.version} + + + + + diff --git a/eng/spotbugs-aggregate-report/pom.xml b/eng/spotbugs-aggregate-report/pom.xml index df95e28e5936a..a8f5addab7e12 100644 --- a/eng/spotbugs-aggregate-report/pom.xml +++ b/eng/spotbugs-aggregate-report/pom.xml @@ -17,7 +17,7 @@ 5.0.1 2.3.1 2.5.1 - 1.2.0 + 1.2.0 2.0.0 10.5.0 @@ -26,7 +26,10 @@ 1.0.0-preview.1 1.0.0-preview.1 4.0.0-preview.1 + 1.0.0-preview.1 + 4.0.0-preview.1 5.0.0-preview.2 + 12.0.0-preview.1 @@ -49,15 +52,27 @@ - ..\..\appconfiguration\client\src\main\java - ..\..\appconfiguration\client\src\samples\java + ..\..\sdk\appconfiguration\azure-data-appconfiguration\src\main\java + ..\..\sdk\appconfiguration\azure-data-appconfiguration\src\samples\java ..\..\core\azure-core\src\main\java ..\..\core\azure-core\src\samples\java ..\..\core\azure-core-amqp\src\main\java ..\..\core\azure-core-management\src\main\java ..\..\core\azure-core-test\src\main\java - ..\..\eventhubs\client\azure-eventhubs\src\main\java - ..\..\eventhubs\client\azure-eventhubs\src\samples\java + ..\..\sdk\eventhubs\azure-eventhubs\src\main\java + ..\..\sdk\eventhubs\azure-eventhubs\src\samples\java + ..\..\sdk\identity\azure-identity\src\main\java + + + + + + + + + + + @@ -76,19 +91,19 @@ - ..\..\batch\data-plane\src\main\java + ..\..\sdk\batch\microsoft-azure-batch\src\main\java ..\..\eventhubs\data-plane\azure-eventhubs\src\main\java ..\..\eventhubs\data-plane\azure-eventhubs-eph\src\main\java ..\..\eventhubs\data-plane\azure-eventhubs-extensions\src\main\java - ..\..\keyvault\data-plane\azure-keyvault\src\main\java - ..\..\keyvault\data-plane\azure-keyvault-cryptography\src\main\java - ..\..\keyvault\data-plane\azure-keyvault-core\src\main\java - ..\..\keyvault\data-plane\azure-keyvault-extensions\src\main\java - ..\..\keyvault\data-plane\azure-keyvault-webkey\src\main\java - ..\..\servicebus\data-plane\azure-servicebus\src\main\java + ..\..\sdk\keyvault\microsoft-azure-keyvault\src\main\java + ..\..\sdk\keyvault\microsoft-azure-keyvault-cryptography\src\main\java + ..\..\sdk\keyvault\microsoft-azure-keyvault-core\src\main\java + ..\..\sdk\keyvault\microsoft-azure-keyvault-extensions\src\main\java + ..\..\sdk\keyvault\microsoft-azure-keyvault-webkey\src\main\java + ..\..\sdk\servicebus\microsoft-azure-servicebus\src\main\java @@ -117,6 +132,11 @@ true + + com.azure + azure-data-appconfiguration + ${azure-data-appconfiguration.version} + com.azure azure-core @@ -139,14 +159,30 @@ com.azure - azure-data-appconfiguration - ${azure-data-appconfiguration.version} + azure-messaging-eventhubs + ${azure-messaging-eventhubs.version} com.azure - azure-messaging-eventhubs - ${azure-messaging-eventhubs.version} + azure-identity + ${azure-identity.version} + + com.azure + azure-keyvault-keys + ${azure-keyvault.version} + + + com.azure + azure-keyvault-secrets + ${azure-keyvault.version} + + + + + + + @@ -175,27 +211,27 @@ com.microsoft.azure azure-keyvault - ${azure-keyvault.version} + ${azure-keyvault.track-one.version} com.microsoft.azure azure-keyvault-cryptography - ${azure-keyvault.version} + ${azure-keyvault.track-one.version} com.microsoft.azure azure-keyvault-core - ${azure-keyvault.version} + ${azure-keyvault.track-one.version} com.microsoft.azure azure-keyvault-extensions - ${azure-keyvault.version} + ${azure-keyvault.track-one.version} com.microsoft.azure azure-keyvault-webkey - ${azure-keyvault.version} + ${azure-keyvault.track-one.version} com.microsoft.azure diff --git a/pom.client.xml b/pom.client.xml index b09118509b848..a59b045a1effa 100644 --- a/pom.client.xml +++ b/pom.client.xml @@ -537,11 +537,12 @@ -maxLineLength 120 - -snippetpath ${project.basedir}/applicationconfig/client/src/samples/java + -snippetpath ${project.basedir}/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java -snippetpath ${project.basedir}/core/azure-core/src/samples/java - -snippetpath ${project.basedir}/eventhubs/client/azure-eventhubs/src/samples/java - -snippetpath ${project.basedir}/keyvault/client/keys/src/samples/java - -snippetpath ${project.basedir}/keyvault/client/secrets/src/samples/java + -snippetpath ${project.basedir}/sdk/eventhubs/azure-eventhubs/src/samples/java + -snippetpath ${project.basedir}/sdk/keyvault/azure-keyvault-keys/src/samples/java + -snippetpath ${project.basedir}/sdk/keyvault/azure-keyvault-secrets/src/samples/java + @@ -569,10 +570,8 @@ dependencies issue-management licenses - scm plugins plugin-management - team diff --git a/sdk/keyvault/azure-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java b/sdk/keyvault/azure-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java index 16875208d6e89..3b71f4e882ccc 100644 --- a/sdk/keyvault/azure-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java +++ b/sdk/keyvault/azure-keyvault-secrets/src/samples/java/com/azure/security/keyvault/secrets/SecretClientJavaDocCodeSnippets.java @@ -13,7 +13,7 @@ import com.azure.security.keyvault.secrets.models.SecretBase; /** - * This class contains code samples for generating javadocs through doclets for {@link SecretClient] + * This class contains code samples for generating javadocs through doclets for {@link SecretClient} */ public final class SecretClientJavaDocCodeSnippets { From e667416234525bad35e05ef6bf0ee7fe29acd464 Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Thu, 11 Jul 2019 16:29:54 -0700 Subject: [PATCH 70/85] Fix package groups and package info javadoc (#4391) * Fix package groups and package info javadoc * Move common group to top --- .../src/main/java/com/azure/core/test/http/package-info.java | 2 +- .../main/java/com/azure/core/test/models/package-info.java | 2 +- .../src/main/java/com/azure/core/test/package-info.java | 2 +- .../main/java/com/azure/core/test/policy/package-info.java | 2 +- .../src/main/java/com/azure/core/test/utils/package-info.java | 2 +- pom.client.xml | 4 ++++ .../main/java/com/azure/storage/blob/models/package-info.java | 2 +- .../src/main/java/com/azure/storage/blob/package-info.java | 3 +-- .../com/azure/storage/common/credentials/package-info.java | 2 +- .../java/com/azure/storage/common/policy/package-info.java | 2 +- 10 files changed, 13 insertions(+), 10 deletions(-) diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/http/package-info.java b/core/azure-core-test/src/main/java/com/azure/core/test/http/package-info.java index eb3778c87cbc5..f98e81b7f4faa 100644 --- a/core/azure-core-test/src/main/java/com/azure/core/test/http/package-info.java +++ b/core/azure-core-test/src/main/java/com/azure/core/test/http/package-info.java @@ -2,6 +2,6 @@ // Licensed under the MIT License. /** - * Package contains classes to test HTTP communications in Azure client libraries. + * Package containing classes to test HTTP communications in Azure client libraries. */ package com.azure.core.test.http; diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/models/package-info.java b/core/azure-core-test/src/main/java/com/azure/core/test/models/package-info.java index b22156f6f6c01..060fb7b50dca9 100644 --- a/core/azure-core-test/src/main/java/com/azure/core/test/models/package-info.java +++ b/core/azure-core-test/src/main/java/com/azure/core/test/models/package-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** - * Package contains models used to test Azure client libraries. + * Package containing models used to test Azure client libraries. */ package com.azure.core.test.models; diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/package-info.java b/core/azure-core-test/src/main/java/com/azure/core/test/package-info.java index 82c5f9e75223e..1dd6f464254ff 100644 --- a/core/azure-core-test/src/main/java/com/azure/core/test/package-info.java +++ b/core/azure-core-test/src/main/java/com/azure/core/test/package-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** - * Package contains common test classes for Azure client libraries. + * Package containing common test classes for Azure client libraries. */ package com.azure.core.test; diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/policy/package-info.java b/core/azure-core-test/src/main/java/com/azure/core/test/policy/package-info.java index 804d94478d955..28a5327ecbb69 100644 --- a/core/azure-core-test/src/main/java/com/azure/core/test/policy/package-info.java +++ b/core/azure-core-test/src/main/java/com/azure/core/test/policy/package-info.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** - * Package contains {@link com.azure.core.http.policy.HttpPipelinePolicy HttpPipelinePolicies} used to test Azure + * Package containing {@link com.azure.core.http.policy.HttpPipelinePolicy HttpPipelinePolicies} used to test Azure * client libraries. */ package com.azure.core.test.policy; diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/utils/package-info.java b/core/azure-core-test/src/main/java/com/azure/core/test/utils/package-info.java index 8b13830f047fd..f6b311ed0d560 100644 --- a/core/azure-core-test/src/main/java/com/azure/core/test/utils/package-info.java +++ b/core/azure-core-test/src/main/java/com/azure/core/test/utils/package-info.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** - * Package contains utility classes used for testing Azure client libraries. + * Package containing utility classes used for testing Azure client libraries. */ package com.azure.core.test.utils; diff --git a/pom.client.xml b/pom.client.xml index a59b045a1effa..6d5510e1db74a 100644 --- a/pom.client.xml +++ b/pom.client.xml @@ -385,6 +385,10 @@ Azure Key Vault com.azure.security.keyvault* + + Azure Storage - Common + com.azure.storage.common* + Azure Storage - Blobs com.azure.storage.blob* diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/models/package-info.java b/storage/client/blob/src/main/java/com/azure/storage/blob/models/package-info.java index 653e8a46d1d67..a078397789b87 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/models/package-info.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/models/package-info.java @@ -3,6 +3,6 @@ // Code generated by Microsoft (R) AutoRest Code Generator. /** - * This package contains the data models for AzureBlobStorage. + * Package containing the data models for AzureBlobStorage. */ package com.azure.storage.blob.models; diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/package-info.java b/storage/client/blob/src/main/java/com/azure/storage/blob/package-info.java index 77e28d3d565ae..6048911e2d091 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/package-info.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/package-info.java @@ -3,7 +3,6 @@ // Code generated by Microsoft (R) AutoRest Code Generator /** - * This package contains the classes for StorageClient. - * Storage Client. + * Package containing the classes for StorageClient. */ package com.azure.storage.blob; diff --git a/storage/client/blob/src/main/java/com/azure/storage/common/credentials/package-info.java b/storage/client/blob/src/main/java/com/azure/storage/common/credentials/package-info.java index b03314b4cc0b0..b7e3c73a85a80 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/common/credentials/package-info.java +++ b/storage/client/blob/src/main/java/com/azure/storage/common/credentials/package-info.java @@ -2,6 +2,6 @@ // Licensed under the MIT License. /** - * This package contains credentials used by Azure Storage services. + * Package containing credentials used by Azure Storage services. */ package com.azure.storage.common.credentials; diff --git a/storage/client/blob/src/main/java/com/azure/storage/common/policy/package-info.java b/storage/client/blob/src/main/java/com/azure/storage/common/policy/package-info.java index 6f36065ea580b..35661c94f0454 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/common/policy/package-info.java +++ b/storage/client/blob/src/main/java/com/azure/storage/common/policy/package-info.java @@ -2,6 +2,6 @@ // Licensed under the MIT License. /** - * This package contains policies used by Azure Storage services. + * Package containing policies used by Azure Storage services. */ package com.azure.storage.common.policy; From 62e4462bbb9f7a858cf784cb1db1fb3a7d49b1ad Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Thu, 11 Jul 2019 22:25:52 -0700 Subject: [PATCH 71/85] Issue #3734: Support Reactor subscriberContext for async clients (#4379) * prototypes for reactor context * Clean up * Service call with reactor context * update name in snippets * unit tests * Address CR comments * Fix annotation for Range * Fix testcase * Remove unused private methods * Update context util method names * Fix spotbugs for snippet code * Fix spotbugs --- .../core/implementation/util/FluxUtil.java | 76 +++++++++++++++++-- .../java/com/azure/core/util/Context.java | 26 +++++++ .../util/FluxUtilJavaDocCodeSnippets.java | 57 ++++++++++++++ .../implementation/util/FluxUtilTests.java | 71 ++++++++++++++--- .../ServiceClientInstantiationCheck.java | 2 +- .../ConfigurationAsyncClient.java | 19 ++--- .../data/appconfiguration/models/Range.java | 4 +- ...urationAsyncClientJavaDocCodeSnippets.java | 54 +++++++++++++ .../ConfigurationAsyncClientTest.java | 2 +- .../blob/implementation/AppendBlobsImpl.java | 5 +- .../blob/implementation/BlobsImpl.java | 3 +- 11 files changed, 281 insertions(+), 38 deletions(-) create mode 100644 core/azure-core/src/samples/java/com/azure/core/implementation/util/FluxUtilJavaDocCodeSnippets.java create mode 100644 sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ConfigurationAsyncClientJavaDocCodeSnippets.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/util/FluxUtil.java b/core/azure-core/src/main/java/com/azure/core/implementation/util/FluxUtil.java index 1ec6329fdf95d..f8541f0983931 100644 --- a/core/azure-core/src/main/java/com/azure/core/implementation/util/FluxUtil.java +++ b/core/azure-core/src/main/java/com/azure/core/implementation/util/FluxUtil.java @@ -3,11 +3,22 @@ package com.azure.core.implementation.util; +import com.azure.core.util.Context; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.CompositeByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.ReferenceCountUtil; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.channels.AsynchronousFileChannel; +import java.nio.channels.CompletionHandler; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; +import java.util.function.Function; +import java.util.stream.Collectors; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import reactor.core.CoreSubscriber; @@ -16,13 +27,6 @@ import reactor.core.publisher.MonoSink; import reactor.core.publisher.Operators; -import java.io.IOException; -import java.lang.reflect.Type; -import java.nio.channels.AsynchronousFileChannel; -import java.nio.channels.CompletionHandler; -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; -import java.util.concurrent.atomic.AtomicLongFieldUpdater; - /** * Utility type exposing methods to deal with {@link Flux}. */ @@ -174,6 +178,64 @@ public static Mono bytebufStreamToFile(Flux content, Asynchronous return Mono.create(emitter -> content.subscribe(new ByteBufToFileSubscriber(outFile, position, emitter))); } + /** + * This method converts the incoming {@code subscriberContext} from {@link reactor.util.context.Context Reactor + * Context} to {@link Context Azure Context} and calls the given lambda function with this context and returns a + * single entity of type {@code T} + *

+ * If the reactor context is empty, {@link Context#NONE} will be used to call the lambda function + *

+ * + *

Code samples

+ * {@codesnippet com.azure.core.implementation.util.fluxutil.monocontext} + * + * @param serviceCall The lambda function that makes the service call into which azure context will be passed + * @param The type of response returned from the service call + * @return The response from service call + */ + public static Mono monoContext(Function> serviceCall) { + return Mono.subscriberContext() + .map(FluxUtil::toAzureContext) + .flatMap(serviceCall); + } + + /** + * This method converts the incoming {@code subscriberContext} from {@link reactor.util.context.Context Reactor + * Context} to {@link Context Azure Context} and calls the given lambda function with this context and returns a + * collection of type {@code T} + *

+ * If the reactor context is empty, {@link Context#NONE} will be used to call the lambda function + *

+ * + *

Code samples

+ * {@codesnippet com.azure.core.implementation.util.fluxutil.fluxcontext} + * + * @param serviceCall The lambda function that makes the service call into which the context will be passed + * @param The type of response returned from the service call + * @return The response from service call + */ + public static Flux fluxContext(Function> serviceCall) { + return Mono.subscriberContext() + .map(FluxUtil::toAzureContext) + .flatMapMany(serviceCall); + } + + /** + * Converts a reactor context to azure context. If the reactor context is {@code null} or empty, + * {@link Context#NONE} will be returned. + * + * @param context The reactor context + * @return The azure context + */ + private static Context toAzureContext(reactor.util.context.Context context) { + Map keyValues = context.stream() + .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); + if (ImplUtils.isNullOrEmpty(keyValues)) { + return Context.NONE; + } + return Context.of(keyValues); + } + private static class ByteBufToFileSubscriber implements Subscriber { private ByteBufToFileSubscriber(AsynchronousFileChannel outFile, long position, MonoSink emitter) { this.outFile = outFile; diff --git a/core/azure-core/src/main/java/com/azure/core/util/Context.java b/core/azure-core/src/main/java/com/azure/core/util/Context.java index 9d3b1d83477d0..bb58ed2987377 100644 --- a/core/azure-core/src/main/java/com/azure/core/util/Context.java +++ b/core/azure-core/src/main/java/com/azure/core/util/Context.java @@ -4,6 +4,8 @@ package com.azure.core.util; import com.azure.core.implementation.annotation.Immutable; +import com.azure.core.implementation.util.ImplUtils; +import java.util.Map; import java.util.Optional; /** @@ -63,6 +65,30 @@ public Context addData(Object key, Object value) { return new Context(this, key, value); } + /** + * Creates a new immutable {@link Context} object with all the keys and values provided by + * the input {@link Map} + * + * @param keyValues The input key value pairs that will be added to this context + * @return Context object containing all the key-value pairs in the input map + * @throws IllegalArgumentException If {@code keyValues} is {@code null} or empty + */ + public static Context of(Map keyValues) { + if (ImplUtils.isNullOrEmpty(keyValues)) { + throw new IllegalArgumentException("Key value map cannot be null or empty"); + } + + Context context = null; + for (Map.Entry entry : keyValues.entrySet()) { + if (context == null) { + context = new Context(entry.getKey(), entry.getValue()); + } else { + context = context.addData(entry.getKey(), entry.getValue()); + } + } + return context; + } + /** * Scans the linked-list of {@link Context} objects looking for one with the specified key. * Note that the first key found, i.e. the most recently added, will be returned. diff --git a/core/azure-core/src/samples/java/com/azure/core/implementation/util/FluxUtilJavaDocCodeSnippets.java b/core/azure-core/src/samples/java/com/azure/core/implementation/util/FluxUtilJavaDocCodeSnippets.java new file mode 100644 index 0000000000000..341adf9e27f7d --- /dev/null +++ b/core/azure-core/src/samples/java/com/azure/core/implementation/util/FluxUtilJavaDocCodeSnippets.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.core.implementation.util; + +import com.azure.core.util.Context; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Code snippets for {@link FluxUtil} + */ +public class FluxUtilJavaDocCodeSnippets { + + /** + * Code snippet for using {@link FluxUtil} with single item response + */ + public void codeSnippetForCallWithSingleResponse() { + // BEGIN: com.azure.core.implementation.util.fluxutil.monocontext + String prefix = "Hello, "; + Mono response = FluxUtil + .monoContext(context -> serviceCallReturnsSingle(prefix, context)); + // END: com.azure.core.implementation.util.fluxutil.monocontext + } + + /** + * Code snippet for using {@link FluxUtil} with collection response + */ + public void codeSnippetForCallWithCollectionResponse() { + // BEGIN: com.azure.core.implementation.util.fluxutil.fluxcontext + String prefix = "Hello, "; + Flux response = FluxUtil + .fluxContext(context -> serviceCallReturnsCollection(prefix, context)); + // END: com.azure.core.implementation.util.fluxutil.fluxcontext + } + + /** + * Implementation not provided + * @param prefix The prefix + * @param context Azure context + * @return {@link Flux#empty() empty} response + */ + private Flux serviceCallReturnsCollection(String prefix, Context context) { + return Flux.empty(); + } + + /** + * Implementation not provided + * @param prefix The prefix + * @param context Azure context + * @return {@link Mono#empty() empty} response + */ + private Mono serviceCallReturnsSingle(String prefix, Context context) { + return Mono.empty(); + } + +} diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java b/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java index d357bd83c494c..7cda0889394d6 100644 --- a/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java +++ b/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java @@ -3,17 +3,15 @@ package com.azure.core.implementation.util; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.azure.core.util.Context; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.util.ReferenceCountUtil; -import org.junit.Ignore; -import org.junit.Test; -import reactor.core.Exceptions; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -24,10 +22,16 @@ import java.nio.file.StandardOpenOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import reactor.core.Exceptions; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; public class FluxUtilTests { @@ -262,6 +266,51 @@ public void testCollectByteBufStream() { 0, 0, 0, (byte) 255, 0, 0, 1, 0}, bytes); } + + @Test + public void testCallWithContextGetSingle() { + String response = getSingle("Hello, ") + .subscriberContext(reactor.util.context.Context.of("FirstName", "Foo", "LastName", "Bar")) + .block(); + Assert.assertEquals("Hello, Foo Bar", response); + } + + @Test + public void testCallWithContextGetCollection() { + List expectedLines = Arrays.asList("Hello,", "Foo", "Bar"); + List actualLines = new ArrayList<>(); + getCollection("Hello, ") + .subscriberContext(reactor.util.context.Context.of("FirstName", "Foo", "LastName", "Bar")) + .doOnNext(line -> actualLines.add(line)) + .subscribe(); + Assert.assertEquals(expectedLines, actualLines); + } + + private Mono getSingle(String prefix) { + return FluxUtil.monoContext(context -> serviceCallSingle(prefix, context)); + } + + private Flux getCollection(String prefix) { + return FluxUtil + .fluxContext(context -> serviceCallCollection(prefix, context)); + } + + private Mono serviceCallSingle(String prefix, Context context) { + String msg = prefix + + context.getData("FirstName").orElse("Stranger") + + " " + + context.getData("LastName").orElse(""); + return Mono.just(msg); + } + + private Flux serviceCallCollection(String prefix, Context context) { + String msg = prefix + + context.getData("FirstName").orElse("Stranger") + + " " + + context.getData("LastName").orElse(""); + + return Flux.just(msg.split(" ")); + } // private static byte[] toBytes(ByteBuf bb) { byte[] bytes = new byte[bb.readableBytes()]; diff --git a/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/ServiceClientInstantiationCheck.java b/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/ServiceClientInstantiationCheck.java index 38adfaabbade6..02669178d0ca1 100644 --- a/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/ServiceClientInstantiationCheck.java +++ b/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/ServiceClientInstantiationCheck.java @@ -21,7 +21,7 @@ public class ServiceClientInstantiationCheck extends AbstractCheck { private static final String SERVICE_CLIENT = "ServiceClient"; private static final String BUILDER = "builder"; - private static final String ASYNC_CLIENT ="AsyncClient"; + private static final String ASYNC_CLIENT = "AsyncClient"; private static final String CLIENT = "Client"; private static final String IS_ASYNC = "isAsync"; diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java index 267df4df2f213..23f233305f699 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java @@ -28,6 +28,9 @@ import java.net.URL; import java.util.Objects; +import static com.azure.core.implementation.util.FluxUtil.fluxContext; +import static com.azure.core.implementation.util.FluxUtil.monoContext; + /** * This class provides a client that contains all the operations for {@link ConfigurationSetting ConfigurationSettings} * in Azure App Configuration Store. Operations allowed by the client are adding, retrieving, updating, and deleting @@ -71,12 +74,7 @@ public final class ConfigurationAsyncClient { * *

Add a setting with the key "prodDBConnection" and value "db_connection".

* - *
-     * client.addSetting("prodDBConnection", "db_connection")
-     *     .subscribe(response -> {
-     *         ConfigurationSetting result = response.value();
-     *         System.out.printf("Key: %s, Value: %s", result.key(), result.value());
-     *     });
+ * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addsetting#String-String} * * @param key The key of the configuration setting to add. * @param value The value associated with this configuration setting key. @@ -88,7 +86,8 @@ public final class ConfigurationAsyncClient { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> addSetting(String key, String value) { - return addSetting(new ConfigurationSetting().key(key).value(value), Context.NONE); + return monoContext( + context -> addSetting(new ConfigurationSetting().key(key).value(value), context)); } /** @@ -663,16 +662,14 @@ private Mono> listFirstPageSettings(SettingS * *

Retrieve all revisions of the setting that has the key "prodDBConnection".

* - *
-     * client.listSettingRevisions(new SettingSelector().key("prodDBConnection"))
-     *     .subscribe(setting -> System.out.printf("Key: %s, Value: %s", setting.key(), setting.value()));
+ * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions} * * @param selector Optional. Used to filter configuration setting revisions from the service. * @return Revisions of the ConfigurationSetting */ @ServiceMethod(returns = ReturnType.COLLECTION) public Flux listSettingRevisions(SettingSelector selector) { - return listSettingRevisions(selector, Context.NONE); + return fluxContext(context -> listSettingRevisions(selector, context)); } /** diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/models/Range.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/models/Range.java index 93a166235d416..07a7214acb944 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/models/Range.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/models/Range.java @@ -2,7 +2,7 @@ // Licensed under the MIT License. package com.azure.data.appconfiguration.models; -import com.azure.core.implementation.annotation.Fluent; +import com.azure.core.implementation.annotation.Immutable; import com.azure.data.appconfiguration.ConfigurationAsyncClient; import com.azure.data.appconfiguration.ConfigurationClient; @@ -14,7 +14,7 @@ * @see ConfigurationClient#listSettingRevisions(SettingSelector) * @see SettingSelector#range(Range) */ -@Fluent +@Immutable public class Range { private final int start; private final int end; diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ConfigurationAsyncClientJavaDocCodeSnippets.java b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ConfigurationAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 0000000000000..ae1a97cfcb827 --- /dev/null +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ConfigurationAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.appconfiguration; + +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import reactor.util.context.Context; + +/** + * Code snippets for {@link ConfigurationAsyncClient} + */ +public class ConfigurationAsyncClientJavaDocCodeSnippets { + + private String key1 = "key1"; + private String key2 = "key2"; + private String value1 = "val1"; + private String value2 = "val2"; + /** + * Code snippets for {@link ConfigurationAsyncClient#addSetting(String, String)} + */ + public void addSettingsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.addsetting#String-String + client.addSetting("prodDBConnection", "db_connection") + .subscriberContext(Context.of(key1, value1, key2, value2)) + .subscribe(response -> { + ConfigurationSetting result = response.value(); + System.out.printf("Key: %s, Value: %s", result.key(), result.value()); + }); + // END: com.azure.data.appconfiguration.configurationasyncclient.addsetting#String-String + } + + /** + * Code snippets for {@link ConfigurationAsyncClient#listSettingRevisions(SettingSelector)} + */ + public void listSettingRevisionsCodeSnippet() { + ConfigurationAsyncClient client = getAsyncClient(); + // BEGIN: com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions + client.listSettingRevisions(new SettingSelector().keys("prodDBConnection")) + .subscriberContext(Context.of(key1, value1, key2, value2)) + .subscribe(setting -> + System.out.printf("Key: %s, Value: %s", setting.key(), setting.value())); + // END: com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions + } + + /** + * Implementation not provided + * @return {@code null} + */ + private ConfigurationAsyncClient getAsyncClient() { + return new ConfigurationClientBuilder().buildAsyncClient(); + } +} diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java index 32f2e059d4c9c..4903c61f4720e 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java @@ -101,7 +101,7 @@ public void addSettingEmptyValue() { * Verifies that an exception is thrown when null key is passed. */ public void addSettingNullKey() { - assertRunnableThrowsException(() -> client.addSetting(null, "A Value"), IllegalArgumentException.class); + assertRunnableThrowsException(() -> client.addSetting(null, "A Value").block(), IllegalArgumentException.class); assertRunnableThrowsException(() -> client.addSetting(null), NullPointerException.class); } diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/implementation/AppendBlobsImpl.java b/storage/client/blob/src/main/java/com/azure/storage/blob/implementation/AppendBlobsImpl.java index 77a1c79599e38..a6f486ff075f7 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/implementation/AppendBlobsImpl.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/implementation/AppendBlobsImpl.java @@ -29,12 +29,11 @@ import com.azure.storage.blob.models.SourceModifiedAccessConditions; import com.azure.storage.blob.models.StorageErrorException; import io.netty.buffer.ByteBuf; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - import java.net.URL; import java.time.OffsetDateTime; import java.util.Map; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; /** * An instance of this class provides access to all the operations defined in diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/implementation/BlobsImpl.java b/storage/client/blob/src/main/java/com/azure/storage/blob/implementation/BlobsImpl.java index bcdb0de6a2d7f..e89e8972aed35 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/implementation/BlobsImpl.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/implementation/BlobsImpl.java @@ -45,11 +45,10 @@ import com.azure.storage.blob.models.ModifiedAccessConditions; import com.azure.storage.blob.models.SourceModifiedAccessConditions; import com.azure.storage.blob.models.StorageErrorException; -import reactor.core.publisher.Mono; - import java.net.URL; import java.time.OffsetDateTime; import java.util.Map; +import reactor.core.publisher.Mono; /** * An instance of this class provides access to all the operations defined in From d4a09b531207d6e6baabfedfc081ee929e429d21 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Fri, 12 Jul 2019 09:17:12 -0700 Subject: [PATCH 72/85] Setting up CI for Core in Java. (#4412) --- sdk/core/ci.yml | 23 +++++++++++++++++++++++ sdk/core/pom.service.xml | 14 ++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 sdk/core/ci.yml create mode 100644 sdk/core/pom.service.xml diff --git a/sdk/core/ci.yml b/sdk/core/ci.yml new file mode 100644 index 0000000000000..a4eb3bc813cf7 --- /dev/null +++ b/sdk/core/ci.yml @@ -0,0 +1,23 @@ +# DO NOT EDIT THIS FILE +# This file is generated automatically and any changes will be lost. + +trigger: + branches: + include: + - master + paths: + include: + - sdk/core/ + +pr: + branches: + include: + - master + paths: + include: + - sdk/core/ + +jobs: + - template: ../../eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: core \ No newline at end of file diff --git a/sdk/core/pom.service.xml b/sdk/core/pom.service.xml new file mode 100644 index 0000000000000..7c475cc3a4808 --- /dev/null +++ b/sdk/core/pom.service.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + com.azure + azure-core-service + pom + 1.0.0 + + + + From 881b683bb2de4a962e6b395175b4a471533d75b1 Mon Sep 17 00:00:00 2001 From: Alan Zimmer <48699787+alzimmermsft@users.noreply.github.com> Date: Fri, 12 Jul 2019 09:36:49 -0700 Subject: [PATCH 73/85] Azure AppConfig Client Builder Cleanup (#4407) * credentials -> credential, serviceEndpoint -> endpoint, endpoint no longer throws MalformedUrlException * Changed throws to use ClientLogger.logAndThrow --- .../azure-data-appconfiguration/README.md | 16 ++-- .../ConfigurationClientBuilder.java | 88 ++++++++++--------- .../src/samples/java/ConfigurationSets.java | 2 +- .../src/samples/java/HelloWorld.java | 2 +- .../src/samples/java/PipelineSample.java | 2 +- ...onfigurationClientJavaDocCodeSnippets.java | 8 +- .../ConfigurationAsyncClientTest.java | 4 +- .../ConfigurationClientTest.java | 4 +- 8 files changed, 66 insertions(+), 60 deletions(-) diff --git a/sdk/appconfiguration/azure-data-appconfiguration/README.md b/sdk/appconfiguration/azure-data-appconfiguration/README.md index 9f9d8d835e29c..8740e54e76211 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/README.md +++ b/sdk/appconfiguration/azure-data-appconfiguration/README.md @@ -59,7 +59,7 @@ Once you have the value of the connection string you can create the configuratio ```Java ConfigurationClient client = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); ``` @@ -67,7 +67,7 @@ or ```Java ConfigurationAsyncClient client = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .buildAsyncClient(); ``` @@ -87,7 +87,7 @@ An application that needs to retrieve startup configurations is better suited us ```Java ConfigurationClient client = new ConfigurationClient() - .credentials(new ConfigurationClientCredentials(appConfigConnectionString)) + .credential(new ConfigurationClientCredentials(appConfigConnectionString)) .buildClient(); String url = client.getSetting(urlKey).value(); @@ -104,7 +104,7 @@ An application that has a large set of configurations that it needs to periodica ```Java ConfigurationAsyncClient client = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(appConfigConnectionString)) + .credential(new ConfigurationClientCredentials(appConfigConnectionString)) .buildAsyncClient(); client.listSettings(new SettingSelection().label(periodicUpdateLabel)) @@ -126,7 +126,7 @@ Create a Configuration Setting to be stored in the Configuration Store. There ar - setSetting creates a setting if it doesn't exist or overrides an existing setting. ```Java ConfigurationClient client = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); ConfigurationSetting setting = client.setSetting("some_key", "some_value"); ``` @@ -136,7 +136,7 @@ ConfigurationSetting setting = client.setSetting("some_key", "some_value"); Retrieve a previously stored Configuration Setting by calling getSetting. ```Java ConfigurationClient client = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); client.setSetting("some_key", "some_value"); ConfigurationSetting setting = client.getSetting("some_key"); @@ -147,7 +147,7 @@ ConfigurationSetting setting = client.getSetting("some_key"); Update an existing Configuration Setting by calling updateSetting. ```Java ConfigurationClient client = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); client.setSetting("some_key", "some_value"); ConfigurationSetting setting = client.updateSetting("some_key", "new_value"); @@ -158,7 +158,7 @@ ConfigurationSetting setting = client.updateSetting("some_key", "new_value"); Delete an existing Configuration Setting by calling deleteSetting. ```Java ConfigurationClient client = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); client.setSetting("some_key", "some_value"); ConfigurationSetting setting = client.deleteSetting("some_key"); diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java index 8d4bd79e5d1ef..26840826d978c 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationClientBuilder.java @@ -4,6 +4,7 @@ package com.azure.data.appconfiguration; import com.azure.core.implementation.annotation.ServiceClientBuilder; +import com.azure.core.util.logging.ClientLogger; import com.azure.data.appconfiguration.credentials.ConfigurationClientCredentials; import com.azure.data.appconfiguration.models.ConfigurationSetting; import com.azure.data.appconfiguration.policy.ConfigurationCredentialsPolicy; @@ -36,9 +37,9 @@ * by calling {@link ConfigurationClientBuilder#buildAsyncClient() buildAsyncClient} and {@link ConfigurationClientBuilder#buildClient() buildClient} respectively * to construct an instance of the desired client. * - *

The client needs the service endpoint of the Azure App Configuration store and access credentials. - * {@link ConfigurationClientCredentials} gives the builder the service endpoint and access credentials it requires to - * construct a client, set the ConfigurationClientCredentials with {@link ConfigurationClientBuilder#credentials(ConfigurationClientCredentials) this}.

+ *

The client needs the service endpoint of the Azure App Configuration store and access credential. + * {@link ConfigurationClientCredentials} gives the builder the service endpoint and access credential it requires to + * construct a client, set the ConfigurationClientCredentials with {@link ConfigurationClientBuilder#credential(ConfigurationClientCredentials) this}.

* *

Instantiating an asynchronous Configuration Client

* @@ -51,7 +52,7 @@ *

Another way to construct the client is using a {@link HttpPipeline}. The pipeline gives the client an authenticated * way to communicate with the service but it doesn't contain the service endpoint. Set the pipeline with * {@link ConfigurationClientBuilder#pipeline(HttpPipeline) this}, additionally set the service endpoint with - * {@link ConfigurationClientBuilder#serviceEndpoint(String) this}. Using a pipeline requires additional setup but + * {@link ConfigurationClientBuilder#endpoint(String) this}. Using a pipeline requires additional setup but * allows for finer control on how the {@link ConfigurationAsyncClient} and {@link ConfigurationClient} it built.

* * {@codesnippet com.azure.data.applicationconfig.configurationclient.pipeline.instantiation} @@ -70,11 +71,12 @@ public final class ConfigurationClientBuilder { private static final String ACCEPT_HEADER = "Accept"; private static final String ACCEPT_HEADER_VALUE = "application/vnd.microsoft.azconfig.kv+json"; + private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List policies; private final HttpHeaders headers; - private ConfigurationClientCredentials credentials; - private URL serviceEndpoint; + private ConfigurationClientCredentials credential; + private URL endpoint; private HttpClient httpClient; private HttpLogDetailLevel httpLogDetailLevel; private HttpPipeline pipeline; @@ -100,14 +102,14 @@ public ConfigurationClientBuilder() { * *

* If {@link ConfigurationClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and - * {@link ConfigurationClientBuilder#serviceEndpoint(String) serviceEndpoint} are used to create the + * {@link ConfigurationClientBuilder#endpoint(String) endpoint} are used to create the * {@link ConfigurationClient client}. All other builder settings are ignored.

* * @return A ConfigurationClient with the options set from the builder. - * @throws NullPointerException If {@code serviceEndpoint} has not been set. This setting is automatically set when - * {@link ConfigurationClientBuilder#credentials(ConfigurationClientCredentials) credentials} are set through - * the builder. Or can be set explicitly by calling {@link ConfigurationClientBuilder#serviceEndpoint(String)}. - * @throws IllegalStateException If {@link ConfigurationClientBuilder#credentials(ConfigurationClientCredentials)} + * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when + * {@link ConfigurationClientBuilder#credential(ConfigurationClientCredentials) credential} are set through + * the builder. Or can be set explicitly by calling {@link ConfigurationClientBuilder#endpoint(String)}. + * @throws IllegalStateException If {@link ConfigurationClientBuilder#credential(ConfigurationClientCredentials)} * has not been set. */ public ConfigurationClient buildClient() { @@ -120,31 +122,31 @@ public ConfigurationClient buildClient() { * *

* If {@link ConfigurationClientBuilder#pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and - * {@link ConfigurationClientBuilder#serviceEndpoint(String) serviceEndpoint} are used to create the + * {@link ConfigurationClientBuilder#endpoint(String) endpoint} are used to create the * {@link ConfigurationAsyncClient client}. All other builder settings are ignored. *

* * @return A ConfigurationAsyncClient with the options set from the builder. - * @throws NullPointerException If {@code serviceEndpoint} has not been set. This setting is automatically set when - * {@link ConfigurationClientBuilder#credentials(ConfigurationClientCredentials) credentials} are set through - * the builder. Or can be set explicitly by calling {@link ConfigurationClientBuilder#serviceEndpoint(String)}. - * @throws IllegalStateException If {@link ConfigurationClientBuilder#credentials(ConfigurationClientCredentials)} + * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when + * {@link ConfigurationClientBuilder#credential(ConfigurationClientCredentials) credential} are set through + * the builder. Or can be set explicitly by calling {@link ConfigurationClientBuilder#endpoint(String)}. + * @throws IllegalStateException If {@link ConfigurationClientBuilder#credential(ConfigurationClientCredentials)} * has not been set. */ public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? ConfigurationManager.getConfiguration().clone() : configuration; ConfigurationClientCredentials configurationCredentials = getConfigurationCredentials(buildConfiguration); - URL buildServiceEndpoint = getBuildServiceEndpoint(configurationCredentials); + URL buildEndpoint = getBuildEndpoint(configurationCredentials); - Objects.requireNonNull(buildServiceEndpoint); + Objects.requireNonNull(buildEndpoint); if (pipeline != null) { - return new ConfigurationAsyncClient(buildServiceEndpoint, pipeline); + return new ConfigurationAsyncClient(buildEndpoint, pipeline); } - ConfigurationClientCredentials buildCredentials = (credentials == null) ? configurationCredentials : credentials; - if (buildCredentials == null) { - throw new IllegalStateException("'credentials' is required."); + ConfigurationClientCredentials buildCredential = (credential == null) ? configurationCredentials : credential; + if (buildCredential == null) { + logger.logAndThrow(new IllegalStateException("'credential' is required.")); } // Closest to API goes first, closest to wire goes last. @@ -154,7 +156,7 @@ public ConfigurationAsyncClient buildAsyncClient() { policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); policies.add(new AddDatePolicy()); - policies.add(new ConfigurationCredentialsPolicy(buildCredentials)); + policies.add(new ConfigurationCredentialsPolicy(buildCredential)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy); @@ -168,34 +170,38 @@ public ConfigurationAsyncClient buildAsyncClient() { .httpClient(httpClient) .build(); - return new ConfigurationAsyncClient(buildServiceEndpoint, pipeline); + return new ConfigurationAsyncClient(buildEndpoint, pipeline); } /** * Sets the service endpoint for the Azure App Configuration instance. * - * @param serviceEndpoint The URL of the Azure App Configuration instance to send {@link ConfigurationSetting} + * @param endpoint The URL of the Azure App Configuration instance to send {@link ConfigurationSetting} * service requests to and receive responses from. * @return The updated ConfigurationClientBuilder object. - * @throws MalformedURLException if {@code serviceEndpoint} is null or it cannot be parsed into a valid URL. + * @throws IllegalArgumentException if {@code endpoint} is null or it cannot be parsed into a valid URL. */ - public ConfigurationClientBuilder serviceEndpoint(String serviceEndpoint) throws MalformedURLException { - this.serviceEndpoint = new URL(serviceEndpoint); + public ConfigurationClientBuilder endpoint(String endpoint) { + try { + this.endpoint = new URL(endpoint); + } catch (MalformedURLException ex) { + logger.logAndThrow(new IllegalArgumentException("'endpoint' must be a valid URL")); + } + return this; } /** - * Sets the credentials to use when authenticating HTTP requests. Also, sets the - * {@link ConfigurationClientBuilder#serviceEndpoint(String) serviceEndpoint} for this ConfigurationClientBuilder. + * Sets the credential to use when authenticating HTTP requests. Also, sets the + * {@link ConfigurationClientBuilder#endpoint(String) endpoint} for this ConfigurationClientBuilder. * - * @param credentials The credentials to use for authenticating HTTP requests. + * @param credential The credential to use for authenticating HTTP requests. * @return The updated ConfigurationClientBuilder object. - * @throws NullPointerException If {@code credentials} is {@code null}. + * @throws NullPointerException If {@code credential} is {@code null}. */ - public ConfigurationClientBuilder credentials(ConfigurationClientCredentials credentials) { - Objects.requireNonNull(credentials); - this.credentials = credentials; - this.serviceEndpoint = credentials.baseUri(); + public ConfigurationClientBuilder credential(ConfigurationClientCredentials credential) { + this.credential = Objects.requireNonNull(credential); + this.endpoint = credential.baseUri(); return this; } @@ -240,7 +246,7 @@ public ConfigurationClientBuilder httpClient(HttpClient client) { * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from - * {@link ConfigurationClientBuilder#serviceEndpoint(String) serviceEndpoint} to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. + * {@link ConfigurationClientBuilder#endpoint(String) endpoint} to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. @@ -268,7 +274,7 @@ public ConfigurationClientBuilder configuration(Configuration configuration) { private ConfigurationClientCredentials getConfigurationCredentials(Configuration configuration) { String connectionString = configuration.get("AZURE_APPCONFIG_CONNECTION_STRING"); if (ImplUtils.isNullOrEmpty(connectionString)) { - return credentials; + return credential; } try { @@ -278,9 +284,9 @@ private ConfigurationClientCredentials getConfigurationCredentials(Configuration } } - private URL getBuildServiceEndpoint(ConfigurationClientCredentials buildCredentials) { - if (serviceEndpoint != null) { - return serviceEndpoint; + private URL getBuildEndpoint(ConfigurationClientCredentials buildCredentials) { + if (endpoint != null) { + return endpoint; } else if (buildCredentials != null) { return buildCredentials.baseUri(); } else { diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/ConfigurationSets.java b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/ConfigurationSets.java index a818c8da36ebc..d4e5cc18ce6f6 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/ConfigurationSets.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/ConfigurationSets.java @@ -52,7 +52,7 @@ public static void main(String[] args) throws NoSuchAlgorithmException, InvalidK // Instantiate a configuration client that will be used to call the configuration service. ConfigurationAsyncClient client = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .buildAsyncClient(); // Demonstrates two different complex objects being stored in Azure App Configuration; one used for beta and the diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/HelloWorld.java b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/HelloWorld.java index 15bc35ba8531b..8aaa0039a4b1c 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/HelloWorld.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/HelloWorld.java @@ -28,7 +28,7 @@ public static void main(String[] args) throws NoSuchAlgorithmException, InvalidK // Instantiate a client that will be used to call the service. ConfigurationAsyncClient client = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .buildAsyncClient(); // Name of the key to add to the configuration service. diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/PipelineSample.java b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/PipelineSample.java index dc876f7f4c42b..64ca0d7b61ef7 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/PipelineSample.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/PipelineSample.java @@ -44,7 +44,7 @@ public static void main(String[] args) throws NoSuchAlgorithmException, Invalid // We add in a policy to track the type of HTTP method calls we make. // We also want to see the Header information of our HTTP requests, so we specify the detail level. final ConfigurationAsyncClient client = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .addPolicy(new HttpMethodRequestTrackingPolicy(tracker)) .httpLogDetailLevel(HttpLogDetailLevel.HEADERS) .buildAsyncClient(); diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ConfigurationClientJavaDocCodeSnippets.java b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ConfigurationClientJavaDocCodeSnippets.java index 72bd7346b3e1c..209554c5d4be7 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ConfigurationClientJavaDocCodeSnippets.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ConfigurationClientJavaDocCodeSnippets.java @@ -32,8 +32,8 @@ public ConfigurationClient createAsyncConfigurationClientWithPipeline() throws M ConfigurationClient configurationClient = new ConfigurationClientBuilder() .pipeline(pipeline) - .serviceEndpoint("https://myconfig.azure.net/") - .credentials(new ConfigurationClientCredentials(connectionString)) + .endpoint("https://myconfig.azure.net/") + .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); // END: com.azure.data.applicationconfig.configurationclient.pipeline.instantiation return configurationClient; @@ -52,7 +52,7 @@ public ConfigurationAsyncClient createAsyncConfigurationClient() { String connectionString = getConnectionString(); // BEGIN: com.azure.data.applicationconfig.async.configurationclient.instantiation ConfigurationAsyncClient configurationAsyncClient = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .buildAsyncClient(); // END: com.azure.data.applicationconfig.async.configurationclient.instantiation return configurationAsyncClient; @@ -71,7 +71,7 @@ public ConfigurationClient createSyncConfigurationClient() { String connectionString = getConnectionString(); // BEGIN: com.azure.data.applicationconfig.configurationclient.instantiation ConfigurationClient configurationClient = new ConfigurationClientBuilder() - .credentials(new ConfigurationClientCredentials(connectionString)) + .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); // END: com.azure.data.applicationconfig.configurationclient.instantiation return configurationClient; diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java index 4903c61f4720e..067e149c4f292 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java @@ -36,13 +36,13 @@ protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { client = clientSetup(credentials -> new ConfigurationClientBuilder() - .credentials(credentials) + .credential(credentials) .httpClient(interceptorManager.getPlaybackClient()) .httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS) .buildAsyncClient()); } else { client = clientSetup(credentials -> new ConfigurationClientBuilder() - .credentials(credentials) + .credential(credentials) .httpClient(HttpClient.createDefault().wiretap(true)) .httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS) .addPolicy(interceptorManager.getRecordPolicy()) diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientTest.java b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientTest.java index 49c08b0ba9869..32da0d6c5babc 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientTest.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationClientTest.java @@ -31,13 +31,13 @@ protected void beforeTest() { if (interceptorManager.isPlaybackMode()) { client = clientSetup(credentials -> new ConfigurationClientBuilder() - .credentials(credentials) + .credential(credentials) .httpClient(interceptorManager.getPlaybackClient()) .httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS) .buildClient()); } else { client = clientSetup(credentials -> new ConfigurationClientBuilder() - .credentials(credentials) + .credential(credentials) .httpClient(HttpClient.createDefault().wiretap(true)) .httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS) .addPolicy(interceptorManager.getRecordPolicy()) From 5be8d7fb0d3b84edf72a85ecda24a1538bd55e5b Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Fri, 12 Jul 2019 10:34:27 -0700 Subject: [PATCH 74/85] Move cognitive services to sdk (#4107) * Moved cog services folders. * Flattened folder structure. * Renamed to shorten paths. --- eng/.docsettings.yml | 37 ++++++++++--------- .../ms-azure-cs-autosuggest}/pom.xml | 2 +- .../autosuggest/BingAutoSuggestSearch.java | 0 .../autosuggest/BingAutoSuggestSearchAPI.java | 0 .../BingAutoSuggestSearchManager.java | 0 .../BingAutoSuggestSearchAPIImpl.java | 0 .../BingAutoSuggestSearchImpl.java | 0 .../implementation/package-info.java | 0 .../search/autosuggest/models/Action.java | 0 .../search/autosuggest/models/Answer.java | 0 .../models/AutoSuggestOptionalParameter.java | 0 .../autosuggest/models/CreativeWork.java | 0 .../search/autosuggest/models/Error.java | 0 .../search/autosuggest/models/ErrorCode.java | 0 .../autosuggest/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../autosuggest/models/Identifiable.java | 0 .../autosuggest/models/QueryContext.java | 0 .../search/autosuggest/models/Response.java | 0 .../autosuggest/models/ResponseBase.java | 0 .../autosuggest/models/ResponseFormat.java | 0 .../search/autosuggest/models/SafeSearch.java | 0 .../autosuggest/models/ScenarioType.java | 0 .../autosuggest/models/SearchAction.java | 0 .../search/autosuggest/models/SearchKind.java | 0 .../models/SearchResultsAnswer.java | 0 .../autosuggest/models/Suggestions.java | 0 .../models/SuggestionsSuggestionGroup.java | 0 .../search/autosuggest/models/Thing.java | 0 .../autosuggest/models/package-info.java | 0 .../search/autosuggest/package-info.java | 0 .../ms-azure-cs-computervision}/pom.xml | 2 +- .../vision/computervision/ComputerVision.java | 0 .../computervision/ComputerVisionClient.java | 0 .../computervision/ComputerVisionManager.java | 0 .../ComputerVisionClientImpl.java | 0 .../implementation/ComputerVisionImpl.java | 0 .../implementation/package-info.java | 0 .../computervision/models/AdultInfo.java | 0 ...mageByDomainInStreamOptionalParameter.java | 0 ...AnalyzeImageByDomainOptionalParameter.java | 0 ...AnalyzeImageInStreamOptionalParameter.java | 0 .../models/AnalyzeImageOptionalParameter.java | 0 .../computervision/models/Category.java | 0 .../computervision/models/CategoryDetail.java | 0 .../models/CelebritiesModel.java | 0 .../models/CelebrityResults.java | 0 .../computervision/models/ColorInfo.java | 0 .../models/ComputerVisionError.java | 0 .../models/ComputerVisionErrorCodes.java | 0 .../models/ComputerVisionErrorException.java | 0 ...escribeImageInStreamOptionalParameter.java | 0 .../DescribeImageOptionalParameter.java | 0 .../vision/computervision/models/Details.java | 0 .../models/DomainModelResults.java | 0 .../models/FaceDescription.java | 0 .../computervision/models/FaceRectangle.java | 0 .../vision/computervision/models/Gender.java | 0 ...ateThumbnailInStreamOptionalParameter.java | 0 .../GenerateThumbnailOptionalParameter.java | 0 .../computervision/models/ImageAnalysis.java | 0 .../computervision/models/ImageCaption.java | 0 .../models/ImageDescription.java | 0 .../models/ImageDescriptionDetails.java | 0 .../computervision/models/ImageMetadata.java | 0 .../computervision/models/ImageTag.java | 0 .../computervision/models/ImageType.java | 0 .../computervision/models/ImageUrl.java | 0 .../models/LandmarkResults.java | 0 .../computervision/models/LandmarksModel.java | 0 .../vision/computervision/models/Line.java | 0 .../models/ListModelsResult.java | 0 .../models/ModelDescription.java | 0 .../computervision/models/OcrLanguages.java | 0 .../vision/computervision/models/OcrLine.java | 0 .../computervision/models/OcrRegion.java | 0 .../computervision/models/OcrResult.java | 0 .../vision/computervision/models/OcrWord.java | 0 .../models/RecognitionResult.java | 0 ...ePrintedTextInStreamOptionalParameter.java | 0 ...RecognizePrintedTextOptionalParameter.java | 0 .../models/RecognizeTextHeaders.java | 0 .../models/RecognizeTextInStreamHeaders.java | 0 .../TagImageInStreamOptionalParameter.java | 0 .../models/TagImageOptionalParameter.java | 0 .../computervision/models/TagResult.java | 0 .../models/TextOperationResult.java | 0 .../models/TextOperationStatusCodes.java | 0 .../models/TextRecognitionMode.java | 0 .../models/VisualFeatureTypes.java | 0 .../vision/computervision/models/Word.java | 0 .../computervision/models/package-info.java | 0 .../vision/computervision/package-info.java | 0 .../ms-azure-cs-contentmoderator}/pom.xml | 2 +- .../ContentModeratorClient.java | 0 .../ContentModeratorManager.java | 0 .../contentmoderator/ImageModerations.java | 0 .../ListManagementImageLists.java | 0 .../ListManagementImages.java | 0 .../ListManagementTermLists.java | 0 .../contentmoderator/ListManagementTerms.java | 0 .../vision/contentmoderator/Reviews.java | 0 .../contentmoderator/TextModerations.java | 0 .../ContentModeratorClientImpl.java | 0 .../implementation/ImageModerationsImpl.java | 0 .../ListManagementImageListsImpl.java | 0 .../ListManagementImagesImpl.java | 0 .../ListManagementTermListsImpl.java | 0 .../ListManagementTermsImpl.java | 0 .../implementation/ReviewsImpl.java | 0 .../implementation/TextModerationsImpl.java | 0 .../implementation/package-info.java | 0 .../contentmoderator/models/APIError.java | 0 .../models/APIErrorException.java | 0 .../AddImageFileInputOptionalParameter.java | 0 .../models/AddImageOptionalParameter.java | 0 .../AddImageUrlInputOptionalParameter.java | 0 .../AddVideoFrameOptionalParameter.java | 0 .../AddVideoFrameStreamOptionalParameter.java | 0 .../AddVideoFrameUrlOptionalParameter.java | 0 .../contentmoderator/models/Address.java | 0 .../models/AzureRegionBaseUrl.java | 0 .../contentmoderator/models/BodyMetadata.java | 0 .../contentmoderator/models/BodyModel.java | 0 .../models/BodyModelModel.java | 0 .../contentmoderator/models/Candidate.java | 0 .../models/Classification.java | 0 .../models/ClassificationCategory1.java | 0 .../models/ClassificationCategory2.java | 0 .../models/ClassificationCategory3.java | 0 .../contentmoderator/models/Content.java | 0 .../models/CreateJobOptionalParameter.java | 0 .../models/CreateReviewBodyItem.java | 0 .../CreateReviewBodyItemMetadataItem.java | 0 .../CreateReviewsOptionalParameter.java | 0 .../models/CreateVideoReviewsBodyItem.java | 0 ...reateVideoReviewsBodyItemMetadataItem.java | 0 ...teVideoReviewsBodyItemVideoFramesItem.java | 0 ...wsBodyItemVideoFramesItemMetadataItem.java | 0 ...VideoFramesItemReviewerResultTagsItem.java | 0 .../CreateVideoReviewsOptionalParameter.java | 0 .../models/DetectedLanguage.java | 0 .../models/DetectedTerms.java | 0 .../vision/contentmoderator/models/Email.java | 0 .../vision/contentmoderator/models/Error.java | 0 .../contentmoderator/models/Evaluate.java | 0 .../EvaluateFileInputOptionalParameter.java | 0 .../EvaluateMethodOptionalParameter.java | 0 .../EvaluateUrlInputOptionalParameter.java | 0 .../vision/contentmoderator/models/Face.java | 0 .../FindFacesFileInputOptionalParameter.java | 0 .../models/FindFacesOptionalParameter.java | 0 .../FindFacesUrlInputOptionalParameter.java | 0 .../contentmoderator/models/FoundFaces.java | 0 .../vision/contentmoderator/models/Frame.java | 0 .../contentmoderator/models/Frames.java | 0 .../models/GetAllTermsOptionalParameter.java | 0 .../GetVideoFramesOptionalParameter.java | 0 .../vision/contentmoderator/models/IPA.java | 0 .../vision/contentmoderator/models/Image.java | 0 .../models/ImageAdditionalInfoItem.java | 0 .../contentmoderator/models/ImageIds.java | 0 .../contentmoderator/models/ImageList.java | 0 .../models/ImageListMetadata.java | 0 .../vision/contentmoderator/models/Job.java | 0 .../models/JobExecutionReportDetails.java | 0 .../vision/contentmoderator/models/JobId.java | 0 .../models/JobListResult.java | 0 .../contentmoderator/models/KeyValuePair.java | 0 .../vision/contentmoderator/models/Match.java | 0 .../MatchFileInputOptionalParameter.java | 0 .../models/MatchMethodOptionalParameter.java | 0 .../models/MatchResponse.java | 0 .../MatchUrlInputOptionalParameter.java | 0 .../vision/contentmoderator/models/OCR.java | 0 .../models/OCRFileInputOptionalParameter.java | 0 .../models/OCRMethodOptionalParameter.java | 0 .../models/OCRUrlInputOptionalParameter.java | 0 .../vision/contentmoderator/models/PII.java | 0 .../vision/contentmoderator/models/Phone.java | 0 .../contentmoderator/models/RefreshIndex.java | 0 .../models/RefreshIndexAdvancedInfoItem.java | 0 .../contentmoderator/models/Review.java | 0 .../vision/contentmoderator/models/SSN.java | 0 .../contentmoderator/models/Screen.java | 0 .../models/ScreenTextOptionalParameter.java | 0 .../contentmoderator/models/Status.java | 0 .../vision/contentmoderator/models/Tag.java | 0 .../contentmoderator/models/TermList.java | 0 .../models/TermListMetadata.java | 0 .../vision/contentmoderator/models/Terms.java | 0 .../contentmoderator/models/TermsData.java | 0 .../contentmoderator/models/TermsInList.java | 0 .../contentmoderator/models/TermsPaging.java | 0 .../models/TranscriptModerationBodyItem.java | 0 ...TranscriptModerationBodyItemTermsItem.java | 0 .../models/VideoFrameBodyItem.java | 0 .../VideoFrameBodyItemMetadataItem.java | 0 ...eoFrameBodyItemReviewerResultTagsItem.java | 0 .../contentmoderator/models/package-info.java | 0 .../vision/contentmoderator/package-info.java | 0 .../ms-azure-cs-customimagesearch}/pom.xml | 2 +- .../BingCustomImageSearchAPI.java | 0 .../BingCustomImageSearchManager.java | 0 .../BingCustomInstances.java | 0 .../BingCustomImageSearchAPIImpl.java | 0 .../BingCustomInstancesImpl.java | 0 .../implementation/package-info.java | 0 .../customimagesearch/models/Answer.java | 0 .../models/CreativeWork.java | 0 .../customimagesearch/models/Error.java | 0 .../customimagesearch/models/ErrorCode.java | 0 .../models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../models/ErrorSubCode.java | 0 .../customimagesearch/models/Freshness.java | 0 .../models/Identifiable.java | 0 .../customimagesearch/models/ImageAspect.java | 0 .../customimagesearch/models/ImageColor.java | 0 .../models/ImageContent.java | 0 .../models/ImageLicense.java | 0 .../customimagesearch/models/ImageObject.java | 0 .../models/ImageSearchOptionalParameter.java | 0 .../customimagesearch/models/ImageSize.java | 0 .../customimagesearch/models/ImageType.java | 0 .../customimagesearch/models/Images.java | 0 .../customimagesearch/models/MediaObject.java | 0 .../customimagesearch/models/Query.java | 0 .../customimagesearch/models/Response.java | 0 .../models/ResponseBase.java | 0 .../customimagesearch/models/SafeSearch.java | 0 .../models/SearchResultsAnswer.java | 0 .../customimagesearch/models/Thing.java | 0 .../customimagesearch/models/WebPage.java | 0 .../models/package-info.java | 0 .../customimagesearch/package-info.java | 0 .../ms-azure-cs-customsearch}/pom.xml | 2 +- .../customsearch/BingCustomInstances.java | 0 .../customsearch/BingCustomSearchAPI.java | 0 .../customsearch/BingCustomSearchManager.java | 0 .../BingCustomInstancesImpl.java | 0 .../BingCustomSearchAPIImpl.java | 0 .../implementation/package-info.java | 0 .../search/customsearch/models/Answer.java | 0 .../customsearch/models/CreativeWork.java | 0 .../search/customsearch/models/Error.java | 0 .../search/customsearch/models/ErrorCode.java | 0 .../customsearch/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../customsearch/models/ErrorSubCode.java | 0 .../customsearch/models/Identifiable.java | 0 .../search/customsearch/models/Query.java | 0 .../customsearch/models/QueryContext.java | 0 .../search/customsearch/models/Response.java | 0 .../customsearch/models/ResponseBase.java | 0 .../customsearch/models/SafeSearch.java | 0 .../models/SearchOptionalParameter.java | 0 .../customsearch/models/SearchResponse.java | 0 .../models/SearchResultsAnswer.java | 0 .../customsearch/models/TextFormat.java | 0 .../search/customsearch/models/Thing.java | 0 .../customsearch/models/WebMetaTag.java | 0 .../search/customsearch/models/WebPage.java | 0 .../customsearch/models/WebWebAnswer.java | 0 .../customsearch/models/package-info.java | 0 .../search/customsearch/package-info.java | 0 .../pom.xml | 2 +- .../CustomVisionPredictionManager.java | 0 .../prediction/PredictionEndpoint.java | 0 .../customvision/prediction/Predictions.java | 0 .../PredictionEndpointImpl.java | 0 .../implementation/PredictionsImpl.java | 0 .../implementation/package-info.java | 0 .../prediction/models/BoundingBox.java | 0 .../prediction/models/ImagePrediction.java | 0 .../prediction/models/ImageUrl.java | 0 .../models/PredictImageOptionalParameter.java | 0 .../PredictImageUrlOptionalParameter.java | 0 ...tImageUrlWithNoStoreOptionalParameter.java | 0 ...dictImageWithNoStoreOptionalParameter.java | 0 .../prediction/models/Prediction.java | 0 .../prediction/models/package-info.java | 0 .../customvision/prediction/package-info.java | 0 .../pom.xml | 2 +- .../training/CustomVisionTrainingManager.java | 0 .../customvision/training/TrainingApi.java | 0 .../customvision/training/Trainings.java | 0 .../implementation/TrainingApiImpl.java | 0 .../implementation/TrainingsImpl.java | 0 .../training/implementation/package-info.java | 0 .../training/models/BoundingBox.java | 0 .../training/models/Classifier.java | 0 .../CreateImageRegionsOptionalParameter.java | 0 .../CreateImageTagsOptionalParameter.java | 0 ...CreateImagesFromDataOptionalParameter.java | 0 .../CreateProjectOptionalParameter.java | 0 .../models/CreateTagOptionalParameter.java | 0 .../customvision/training/models/Domain.java | 0 .../training/models/DomainType.java | 0 .../customvision/training/models/Export.java | 0 .../training/models/ExportFlavor.java | 0 .../ExportIterationOptionalParameter.java | 0 .../training/models/ExportPlatform.java | 0 .../training/models/ExportStatusModel.java | 0 ...magePerformanceCountOptionalParameter.java | 0 ...GetImagePerformancesOptionalParameter.java | 0 .../GetImagesByIdsOptionalParameter.java | 0 ...IterationPerformanceOptionalParameter.java | 0 .../models/GetTagOptionalParameter.java | 0 .../GetTaggedImageCountOptionalParameter.java | 0 .../GetTaggedImagesOptionalParameter.java | 0 .../models/GetTagsOptionalParameter.java | 0 ...etUntaggedImageCountOptionalParameter.java | 0 .../GetUntaggedImagesOptionalParameter.java | 0 .../customvision/training/models/Image.java | 0 .../training/models/ImageCreateResult.java | 0 .../training/models/ImageCreateSummary.java | 0 .../training/models/ImageFileCreateBatch.java | 0 .../training/models/ImageFileCreateEntry.java | 0 .../training/models/ImageIdCreateBatch.java | 0 .../training/models/ImageIdCreateEntry.java | 0 .../training/models/ImagePerformance.java | 0 .../training/models/ImagePrediction.java | 0 .../training/models/ImageRegion.java | 0 .../models/ImageRegionCreateBatch.java | 0 .../models/ImageRegionCreateEntry.java | 0 .../models/ImageRegionCreateResult.java | 0 .../models/ImageRegionCreateSummary.java | 0 .../training/models/ImageRegionProposal.java | 0 .../training/models/ImageTag.java | 0 .../training/models/ImageTagCreateBatch.java | 0 .../training/models/ImageTagCreateEntry.java | 0 .../models/ImageTagCreateSummary.java | 0 .../training/models/ImageUploadStatus.java | 0 .../training/models/ImageUrl.java | 0 .../training/models/ImageUrlCreateBatch.java | 0 .../training/models/ImageUrlCreateEntry.java | 0 .../training/models/Iteration.java | 0 .../training/models/IterationPerformance.java | 0 .../customvision/training/models/OrderBy.java | 0 .../training/models/Prediction.java | 0 .../models/PredictionQueryResult.java | 0 .../training/models/PredictionQueryTag.java | 0 .../training/models/PredictionQueryToken.java | 0 .../customvision/training/models/Project.java | 0 .../training/models/ProjectSettings.java | 0 .../QuickTestImageOptionalParameter.java | 0 .../QuickTestImageUrlOptionalParameter.java | 0 .../customvision/training/models/Region.java | 0 .../training/models/RegionProposal.java | 0 .../models/StoredImagePrediction.java | 0 .../customvision/training/models/Tag.java | 0 .../training/models/TagPerformance.java | 0 .../training/models/package-info.java | 0 .../customvision/training/package-info.java | 0 .../ms-azure-cs-entitysearch}/pom.xml | 2 +- .../search/entitysearch/BingEntities.java | 0 .../entitysearch/BingEntitySearchAPI.java | 0 .../entitysearch/BingEntitySearchManager.java | 0 .../implementation/BingEntitiesImpl.java | 0 .../BingEntitySearchAPIImpl.java | 0 .../implementation/package-info.java | 0 .../search/entitysearch/models/Airport.java | 0 .../search/entitysearch/models/Answer.java | 0 .../entitysearch/models/AnswerType.java | 0 .../entitysearch/models/CivicStructure.java | 0 .../models/ContractualRulesAttribution.java | 0 .../ContractualRulesContractualRule.java | 0 .../ContractualRulesLicenseAttribution.java | 0 .../ContractualRulesLinkAttribution.java | 0 .../ContractualRulesMediaAttribution.java | 0 .../ContractualRulesTextAttribution.java | 0 .../entitysearch/models/CreativeWork.java | 0 .../models/EntertainmentBusiness.java | 0 .../EntitiesEntityPresentationInfo.java | 0 .../entitysearch/models/EntitiesModel.java | 0 .../models/EntityQueryScenario.java | 0 .../entitysearch/models/EntityScenario.java | 0 .../entitysearch/models/EntityType.java | 0 .../search/entitysearch/models/Error.java | 0 .../search/entitysearch/models/ErrorCode.java | 0 .../entitysearch/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../entitysearch/models/ErrorSubCode.java | 0 .../models/FoodEstablishment.java | 0 .../search/entitysearch/models/Hotel.java | 0 .../entitysearch/models/Identifiable.java | 0 .../entitysearch/models/ImageObject.java | 0 .../entitysearch/models/Intangible.java | 0 .../search/entitysearch/models/License.java | 0 .../entitysearch/models/LocalBusiness.java | 0 .../entitysearch/models/LodgingBusiness.java | 0 .../entitysearch/models/MediaObject.java | 0 .../entitysearch/models/MovieTheater.java | 0 .../entitysearch/models/Organization.java | 0 .../search/entitysearch/models/Place.java | 0 .../search/entitysearch/models/Places.java | 0 .../entitysearch/models/PostalAddress.java | 0 .../entitysearch/models/QueryContext.java | 0 .../search/entitysearch/models/Response.java | 0 .../entitysearch/models/ResponseBase.java | 0 .../entitysearch/models/ResponseFormat.java | 0 .../entitysearch/models/Restaurant.java | 0 .../entitysearch/models/SafeSearch.java | 0 .../models/SearchOptionalParameter.java | 0 .../entitysearch/models/SearchResponse.java | 0 .../models/SearchResultsAnswer.java | 0 .../entitysearch/models/StructuredValue.java | 0 .../search/entitysearch/models/Thing.java | 0 .../models/TouristAttraction.java | 0 .../entitysearch/models/package-info.java | 0 .../search/entitysearch/package-info.java | 0 .../ms-azure-cs-faceapi}/pom.xml | 2 +- .../vision/faceapi/FaceAPI.java | 0 .../vision/faceapi/FaceAPIManager.java | 0 .../vision/faceapi/FaceLists.java | 0 .../vision/faceapi/Faces.java | 0 .../vision/faceapi/PersonGroupPersons.java | 0 .../vision/faceapi/PersonGroups.java | 0 .../faceapi/implementation/FaceAPIImpl.java | 0 .../faceapi/implementation/FaceListsImpl.java | 0 .../faceapi/implementation/FacesImpl.java | 0 .../PersonGroupPersonsImpl.java | 0 .../implementation/PersonGroupsImpl.java | 0 .../faceapi/implementation/package-info.java | 0 .../vision/faceapi/models/APIError.java | 0 .../faceapi/models/APIErrorException.java | 0 .../vision/faceapi/models/Accessory.java | 0 .../vision/faceapi/models/AccessoryType.java | 0 .../AddFaceFromStreamOptionalParameter.java | 0 .../AddFaceFromUrlOptionalParameter.java | 0 ...PersonFaceFromStreamOptionalParameter.java | 0 ...AddPersonFaceFromUrlOptionalParameter.java | 0 .../vision/faceapi/models/AzureRegions.java | 0 .../vision/faceapi/models/Blur.java | 0 .../vision/faceapi/models/BlurLevel.java | 0 .../vision/faceapi/models/Coordinate.java | 0 .../CreateFaceListsOptionalParameter.java | 0 ...tePersonGroupPersonsOptionalParameter.java | 0 .../CreatePersonGroupsOptionalParameter.java | 0 .../DetectWithStreamOptionalParameter.java | 0 .../DetectWithUrlOptionalParameter.java | 0 .../vision/faceapi/models/DetectedFace.java | 0 .../vision/faceapi/models/Emotion.java | 0 .../vision/faceapi/models/Error.java | 0 .../vision/faceapi/models/Exposure.java | 0 .../vision/faceapi/models/ExposureLevel.java | 0 .../faceapi/models/FaceAttributeType.java | 0 .../vision/faceapi/models/FaceAttributes.java | 0 .../vision/faceapi/models/FaceLandmarks.java | 0 .../vision/faceapi/models/FaceList.java | 0 .../vision/faceapi/models/FaceRectangle.java | 0 .../vision/faceapi/models/FacialHair.java | 0 .../faceapi/models/FindSimilarMatchMode.java | 0 .../models/FindSimilarOptionalParameter.java | 0 .../faceapi/models/FindSimilarRequest.java | 0 .../vision/faceapi/models/Gender.java | 0 .../vision/faceapi/models/GlassesType.java | 0 .../vision/faceapi/models/GroupRequest.java | 0 .../vision/faceapi/models/GroupResult.java | 0 .../vision/faceapi/models/Hair.java | 0 .../vision/faceapi/models/HairColor.java | 0 .../vision/faceapi/models/HairColorType.java | 0 .../vision/faceapi/models/HeadPose.java | 0 .../faceapi/models/IdentifyCandidate.java | 0 .../models/IdentifyOptionalParameter.java | 0 .../faceapi/models/IdentifyRequest.java | 0 .../vision/faceapi/models/IdentifyResult.java | 0 .../vision/faceapi/models/ImageUrl.java | 0 ...stPersonGroupPersonsOptionalParameter.java | 0 .../ListPersonGroupsOptionalParameter.java | 0 .../vision/faceapi/models/Makeup.java | 0 .../models/NameAndUserDataContract.java | 0 .../vision/faceapi/models/Noise.java | 0 .../vision/faceapi/models/NoiseLevel.java | 0 .../vision/faceapi/models/Occlusion.java | 0 .../vision/faceapi/models/PersistedFace.java | 0 .../vision/faceapi/models/Person.java | 0 .../vision/faceapi/models/PersonGroup.java | 0 .../vision/faceapi/models/SimilarFace.java | 0 .../vision/faceapi/models/TrainingStatus.java | 0 .../faceapi/models/TrainingStatusType.java | 0 .../UpdateFaceListsOptionalParameter.java | 0 .../models/UpdateFaceOptionalParameter.java | 0 .../models/UpdatePersonFaceRequest.java | 0 ...tePersonGroupPersonsOptionalParameter.java | 0 .../UpdatePersonGroupsOptionalParameter.java | 0 .../models/VerifyFaceToFaceRequest.java | 0 .../models/VerifyFaceToPersonRequest.java | 0 .../vision/faceapi/models/VerifyResult.java | 0 .../vision/faceapi/models/package-info.java | 0 .../vision/faceapi/package-info.java | 0 .../ms-azure-cs-imagesearch}/pom.xml | 2 +- .../imagesearch/BingImageSearchAPI.java | 0 .../imagesearch/BingImageSearchManager.java | 0 .../search/imagesearch/BingImages.java | 0 .../BingImageSearchAPIImpl.java | 0 .../implementation/BingImagesImpl.java | 0 .../implementation/package-info.java | 0 .../imagesearch/models/AggregateOffer.java | 0 .../imagesearch/models/AggregateRating.java | 0 .../search/imagesearch/models/Answer.java | 0 .../imagesearch/models/CollectionPage.java | 0 .../imagesearch/models/CreativeWork.java | 0 .../search/imagesearch/models/Currency.java | 0 .../models/DetailsOptionalParameter.java | 0 .../search/imagesearch/models/Error.java | 0 .../search/imagesearch/models/ErrorCode.java | 0 .../imagesearch/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../imagesearch/models/ErrorSubCode.java | 0 .../search/imagesearch/models/Freshness.java | 0 .../imagesearch/models/Identifiable.java | 0 .../imagesearch/models/ImageAspect.java | 0 .../search/imagesearch/models/ImageColor.java | 0 .../imagesearch/models/ImageContent.java | 0 .../imagesearch/models/ImageCropType.java | 0 .../imagesearch/models/ImageGallery.java | 0 .../models/ImageInsightModule.java | 0 .../imagesearch/models/ImageInsights.java | 0 .../models/ImageInsightsImageCaption.java | 0 .../imagesearch/models/ImageLicense.java | 0 .../imagesearch/models/ImageObject.java | 0 .../search/imagesearch/models/ImageSize.java | 0 .../imagesearch/models/ImageTagsModule.java | 0 .../search/imagesearch/models/ImageType.java | 0 .../models/ImagesImageMetadata.java | 0 .../imagesearch/models/ImagesModel.java | 0 .../imagesearch/models/ImagesModule.java | 0 .../imagesearch/models/InsightsTag.java | 0 .../search/imagesearch/models/Intangible.java | 0 .../imagesearch/models/ItemAvailability.java | 0 .../imagesearch/models/MediaObject.java | 0 .../models/NormalizedRectangle.java | 0 .../search/imagesearch/models/Offer.java | 0 .../imagesearch/models/Organization.java | 0 .../search/imagesearch/models/Person.java | 0 .../imagesearch/models/PivotSuggestions.java | 0 .../imagesearch/models/PropertiesItem.java | 0 .../search/imagesearch/models/Query.java | 0 .../search/imagesearch/models/Rating.java | 0 .../search/imagesearch/models/Recipe.java | 0 .../imagesearch/models/RecipesModule.java | 0 .../models/RecognizedEntitiesModule.java | 0 .../imagesearch/models/RecognizedEntity.java | 0 .../models/RecognizedEntityGroup.java | 0 .../models/RecognizedEntityRegion.java | 0 .../models/RelatedCollectionsModule.java | 0 .../models/RelatedSearchesModule.java | 0 .../search/imagesearch/models/Response.java | 0 .../imagesearch/models/ResponseBase.java | 0 .../search/imagesearch/models/SafeSearch.java | 0 .../models/SearchOptionalParameter.java | 0 .../models/SearchResultsAnswer.java | 0 .../imagesearch/models/StructuredValue.java | 0 .../search/imagesearch/models/Thing.java | 0 .../imagesearch/models/TrendingImages.java | 0 .../models/TrendingImagesCategory.java | 0 .../models/TrendingImagesTile.java | 0 .../models/TrendingOptionalParameter.java | 0 .../search/imagesearch/models/WebPage.java | 0 .../imagesearch/models/package-info.java | 0 .../search/imagesearch/package-info.java | 0 .../ms-azure-cs-luis-authoring}/pom.xml | 2 +- .../language/luis/authoring/Apps.java | 0 .../language/luis/authoring/EndpointAPI.java | 0 .../language/luis/authoring/Examples.java | 0 .../language/luis/authoring/Features.java | 0 .../luis/authoring/LUISAuthoringClient.java | 0 .../luis/authoring/LUISAuthoringManager.java | 0 .../language/luis/authoring/Models.java | 0 .../language/luis/authoring/Patterns.java | 0 .../language/luis/authoring/Permissions.java | 0 .../language/luis/authoring/Trains.java | 0 .../language/luis/authoring/Versions.java | 0 .../authoring/implementation/AppsImpl.java | 0 .../implementation/ExamplesImpl.java | 0 .../implementation/FeaturesImpl.java | 0 .../LUISAuthoringClientImpl.java | 0 .../authoring/implementation/ModelsImpl.java | 0 .../implementation/PatternsImpl.java | 0 .../implementation/PermissionsImpl.java | 0 .../authoring/implementation/TrainsImpl.java | 0 .../implementation/VersionsImpl.java | 0 .../implementation/package-info.java | 0 ...CompositeEntityChildOptionalParameter.java | 0 ...PrebuiltDomainModelsOptionalParameter.java | 0 .../models/AddEntityOptionalParameter.java | 0 .../AddExplicitListItemOptionalParameter.java | 0 ...rarchicalEntityChildOptionalParameter.java | 0 .../models/AddIntentOptionalParameter.java | 0 .../AddPermissionsOptionalParameter.java | 0 .../models/ApplicationCreateObject.java | 0 .../models/ApplicationInfoResponse.java | 0 .../models/ApplicationPublishObject.java | 0 .../ApplicationSettingUpdateObject.java | 0 .../authoring/models/ApplicationSettings.java | 0 .../models/ApplicationUpdateObject.java | 0 .../authoring/models/AvailableCulture.java | 0 .../models/AvailablePrebuiltEntityModel.java | 0 .../authoring/models/BatchLabelExample.java | 0 .../luis/authoring/models/ChildEntity.java | 0 .../models/CloneOptionalParameter.java | 0 .../luis/authoring/models/ClosedList.java | 0 .../models/ClosedListEntityExtractor.java | 0 .../models/ClosedListModelCreateObject.java | 0 .../models/ClosedListModelPatchObject.java | 0 .../models/ClosedListModelUpdateObject.java | 0 .../authoring/models/CollaboratorsArray.java | 0 .../CompositeChildModelCreateObject.java | 0 .../models/CompositeEntityExtractor.java | 0 .../models/CompositeEntityModel.java | 0 ...ClosedListEntityRoleOptionalParameter.java | 0 ...eCompositeEntityRoleOptionalParameter.java | 0 ...omPrebuiltEntityRoleOptionalParameter.java | 0 .../CreateEntityRoleOptionalParameter.java | 0 ...erarchicalEntityRoleOptionalParameter.java | 0 ...PatternAnyEntityRoleOptionalParameter.java | 0 ...tePrebuiltEntityRoleOptionalParameter.java | 0 ...reateRegexEntityRoleOptionalParameter.java | 0 .../authoring/models/CustomPrebuiltModel.java | 0 .../models/DeleteIntentOptionalParameter.java | 0 .../DeletePermissionsOptionalParameter.java | 0 .../luis/authoring/models/EndpointInfo.java | 0 .../models/EnqueueTrainingResponse.java | 0 .../models/EntitiesSuggestionExample.java | 0 .../authoring/models/EntityExtractor.java | 0 .../luis/authoring/models/EntityLabel.java | 0 .../authoring/models/EntityLabelObject.java | 0 .../authoring/models/EntityModelInfo.java | 0 .../authoring/models/EntityPrediction.java | 0 .../luis/authoring/models/EntityRole.java | 0 .../models/EntityRoleCreateObject.java | 0 .../models/EntityRoleUpdateObject.java | 0 .../luis/authoring/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../authoring/models/ExampleLabelObject.java | 0 .../ExamplesMethodOptionalParameter.java | 0 .../authoring/models/ExplicitListItem.java | 0 .../models/ExplicitListItemCreateObject.java | 0 .../models/ExplicitListItemUpdateObject.java | 0 .../authoring/models/FeatureInfoObject.java | 0 .../models/FeaturesResponseObject.java | 0 ...GetEntitySuggestionsOptionalParameter.java | 0 .../GetIntentPatternsOptionalParameter.java | 0 ...GetIntentSuggestionsOptionalParameter.java | 0 ...atternAnyEntityInfosOptionalParameter.java | 0 .../models/GetPatternsOptionalParameter.java | 0 .../GetRegexEntityInfosOptionalParameter.java | 0 .../models/HierarchicalChildEntity.java | 0 .../HierarchicalChildModelCreateObject.java | 0 .../HierarchicalChildModelUpdateObject.java | 0 .../models/HierarchicalEntityExtractor.java | 0 .../models/HierarchicalEntityModel.java | 0 .../authoring/models/HierarchicalModel.java | 0 .../ImportMethodAppsOptionalParameter.java | 0 ...ImportMethodVersionsOptionalParameter.java | 0 .../authoring/models/IntentClassifier.java | 0 .../authoring/models/IntentPrediction.java | 0 .../models/IntentsSuggestionExample.java | 0 .../luis/authoring/models/JSONEntity.java | 0 .../authoring/models/JSONModelFeature.java | 0 .../authoring/models/JSONRegexFeature.java | 0 .../luis/authoring/models/JSONUtterance.java | 0 .../models/LabelExampleResponse.java | 0 .../authoring/models/LabelTextObject.java | 0 .../authoring/models/LabeledUtterance.java | 0 .../models/ListAppsOptionalParameter.java | 0 .../ListClosedListsOptionalParameter.java | 0 ...istCompositeEntitiesOptionalParameter.java | 0 .../models/ListEntitiesOptionalParameter.java | 0 .../models/ListExamplesOptionalParameter.java | 0 .../models/ListFeaturesOptionalParameter.java | 0 ...HierarchicalEntitiesOptionalParameter.java | 0 .../models/ListIntentsOptionalParameter.java | 0 .../models/ListModelsOptionalParameter.java | 0 .../ListPhraseListsOptionalParameter.java | 0 .../ListPrebuiltsOptionalParameter.java | 0 .../models/ListVersionsOptionalParameter.java | 0 .../luis/authoring/models/LuisApp.java | 0 .../authoring/models/ModelCreateObject.java | 0 .../luis/authoring/models/ModelInfo.java | 0 .../authoring/models/ModelInfoResponse.java | 0 .../models/ModelTrainingDetails.java | 0 .../authoring/models/ModelTrainingInfo.java | 0 .../authoring/models/ModelUpdateObject.java | 0 .../luis/authoring/models/OperationError.java | 0 .../authoring/models/OperationStatus.java | 0 .../authoring/models/OperationStatusType.java | 0 .../PatchClosedListOptionalParameter.java | 0 .../luis/authoring/models/PatternAny.java | 0 .../models/PatternAnyEntityExtractor.java | 0 .../models/PatternAnyModelCreateObject.java | 0 .../models/PatternAnyModelUpdateObject.java | 0 .../authoring/models/PatternCreateObject.java | 0 .../authoring/models/PatternFeatureInfo.java | 0 .../luis/authoring/models/PatternRule.java | 0 .../models/PatternRuleCreateObject.java | 0 .../authoring/models/PatternRuleInfo.java | 0 .../models/PatternRuleUpdateObject.java | 0 .../authoring/models/PatternUpdateObject.java | 0 .../models/PersonalAssistantsResponse.java | 0 .../models/PhraseListFeatureInfo.java | 0 .../models/PhraselistCreateObject.java | 0 .../models/PhraselistUpdateObject.java | 0 .../luis/authoring/models/PrebuiltDomain.java | 0 .../PrebuiltDomainCreateBaseObject.java | 0 .../models/PrebuiltDomainCreateObject.java | 0 .../authoring/models/PrebuiltDomainItem.java | 0 .../PrebuiltDomainModelCreateObject.java | 0 .../models/PrebuiltDomainObject.java | 0 .../luis/authoring/models/PrebuiltEntity.java | 0 .../models/PrebuiltEntityExtractor.java | 0 .../ProductionOrStagingEndpointInfo.java | 0 .../models/PublishSettingUpdateObject.java | 0 .../authoring/models/PublishSettings.java | 0 .../luis/authoring/models/RegexEntity.java | 0 .../models/RegexEntityExtractor.java | 0 .../models/RegexModelCreateObject.java | 0 .../models/RegexModelUpdateObject.java | 0 .../luis/authoring/models/SubClosedList.java | 0 .../models/SubClosedListResponse.java | 0 .../authoring/models/TaskUpdateObject.java | 0 .../luis/authoring/models/TrainingStatus.java | 0 ...ClosedListEntityRoleOptionalParameter.java | 0 ...eCompositeEntityRoleOptionalParameter.java | 0 ...omPrebuiltEntityRoleOptionalParameter.java | 0 .../models/UpdateEntityOptionalParameter.java | 0 .../UpdateEntityRoleOptionalParameter.java | 0 ...dateExplicitListItemOptionalParameter.java | 0 ...rarchicalEntityChildOptionalParameter.java | 0 ...erarchicalEntityRoleOptionalParameter.java | 0 .../models/UpdateIntentOptionalParameter.java | 0 ...PatternAnyEntityRoleOptionalParameter.java | 0 .../UpdatePermissionsOptionalParameter.java | 0 .../UpdatePhraseListOptionalParameter.java | 0 ...tePrebuiltEntityRoleOptionalParameter.java | 0 ...pdateRegexEntityRoleOptionalParameter.java | 0 .../UpdateSettingsOptionalParameter.java | 0 .../UpdateVersionsOptionalParameter.java | 0 .../luis/authoring/models/UserAccessList.java | 0 .../authoring/models/UserCollaborator.java | 0 .../luis/authoring/models/VersionInfo.java | 0 .../models/WordListBaseUpdateObject.java | 0 .../luis/authoring/models/WordListObject.java | 0 .../luis/authoring/models/package-info.java | 0 .../language/luis/authoring/package-info.java | 0 .../ms-azure-cs-luis-runtime}/pom.xml | 2 +- .../language/luis/runtime/EndpointAPI.java | 0 .../language/luis/runtime/LuisRuntimeAPI.java | 0 .../luis/runtime/LuisRuntimeManager.java | 0 .../language/luis/runtime/Predictions.java | 0 .../implementation/LuisRuntimeAPIImpl.java | 0 .../implementation/PredictionsImpl.java | 0 .../runtime/implementation/package-info.java | 0 .../luis/runtime/models/APIError.java | 0 .../runtime/models/APIErrorException.java | 0 .../luis/runtime/models/AzureRegions.java | 0 .../runtime/models/CompositeChildModel.java | 0 .../runtime/models/CompositeEntityModel.java | 0 .../luis/runtime/models/EntityModel.java | 0 .../runtime/models/EntityWithResolution.java | 0 .../luis/runtime/models/EntityWithScore.java | 0 .../luis/runtime/models/IntentModel.java | 0 .../luis/runtime/models/LuisResult.java | 0 .../models/ResolveOptionalParameter.java | 0 .../luis/runtime/models/Sentiment.java | 0 .../luis/runtime/models/package-info.java | 0 .../language/luis/runtime/package-info.java | 0 .../ms-azure-cs-newssearch}/pom.xml | 2 +- .../search/newssearch/BingNews.java | 0 .../search/newssearch/BingNewsSearchAPI.java | 0 .../newssearch/BingNewsSearchManager.java | 0 .../implementation/BingNewsImpl.java | 0 .../implementation/BingNewsSearchAPIImpl.java | 0 .../implementation/package-info.java | 0 .../search/newssearch/models/Answer.java | 0 .../search/newssearch/models/Article.java | 0 .../models/CategoryOptionalParameter.java | 0 .../newssearch/models/CreativeWork.java | 0 .../search/newssearch/models/Error.java | 0 .../search/newssearch/models/ErrorCode.java | 0 .../newssearch/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../newssearch/models/ErrorSubCode.java | 0 .../search/newssearch/models/Freshness.java | 0 .../newssearch/models/Identifiable.java | 0 .../search/newssearch/models/ImageObject.java | 0 .../search/newssearch/models/MediaObject.java | 0 .../search/newssearch/models/NewsArticle.java | 0 .../search/newssearch/models/NewsModel.java | 0 .../search/newssearch/models/NewsTopic.java | 0 .../newssearch/models/Organization.java | 0 .../search/newssearch/models/Query.java | 0 .../search/newssearch/models/Response.java | 0 .../newssearch/models/ResponseBase.java | 0 .../search/newssearch/models/SafeSearch.java | 0 .../models/SearchOptionalParameter.java | 0 .../models/SearchResultsAnswer.java | 0 .../search/newssearch/models/TextFormat.java | 0 .../search/newssearch/models/Thing.java | 0 .../models/TrendingOptionalParameter.java | 0 .../newssearch/models/TrendingTopics.java | 0 .../search/newssearch/models/VideoObject.java | 0 .../newssearch/models/package-info.java | 0 .../search/newssearch/package-info.java | 0 .../ms-azure-cs-spellcheck}/pom.xml | 2 +- .../spellcheck/BingSpellCheckAPI.java | 0 .../spellcheck/BingSpellCheckManager.java | 0 .../spellcheck/BingSpellCheckOperations.java | 0 .../implementation/BingSpellCheckAPIImpl.java | 0 .../BingSpellCheckOperationsImpl.java | 0 .../implementation/package-info.java | 0 .../spellcheck/models/ActionType.java | 0 .../language/spellcheck/models/Answer.java | 0 .../language/spellcheck/models/Error.java | 0 .../language/spellcheck/models/ErrorCode.java | 0 .../spellcheck/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../spellcheck/models/ErrorSubCode.java | 0 .../language/spellcheck/models/ErrorType.java | 0 .../spellcheck/models/Identifiable.java | 0 .../language/spellcheck/models/Response.java | 0 .../spellcheck/models/ResponseBase.java | 0 .../spellcheck/models/SpellCheck.java | 0 .../models/SpellCheckerOptionalParameter.java | 0 .../models/SpellingFlaggedToken.java | 0 .../models/SpellingTokenSuggestion.java | 0 .../spellcheck/models/package-info.java | 0 .../language/spellcheck/package-info.java | 0 .../ms-azure-cs-textanalytics}/pom.xml | 2 +- .../language/textanalytics/TextAnalytics.java | 0 .../textanalytics/TextAnalyticsAPI.java | 0 .../textanalytics/TextAnalyticsManager.java | 0 .../implementation/TextAnalyticsAPIImpl.java | 0 .../implementation/TextAnalyticsImpl.java | 0 .../implementation/package-info.java | 0 .../textanalytics/models/AzureRegions.java | 0 .../textanalytics/models/BatchInput.java | 0 .../DetectLanguageOptionalParameter.java | 0 .../models/DetectedLanguage.java | 0 .../models/EntitiesBatchResult.java | 0 .../models/EntitiesBatchResultItem.java | 0 .../models/EntitiesOptionalParameter.java | 0 .../textanalytics/models/EntityRecord.java | 0 .../textanalytics/models/ErrorRecord.java | 0 .../textanalytics/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../language/textanalytics/models/Input.java | 0 .../textanalytics/models/InternalError.java | 0 .../models/KeyPhraseBatchResult.java | 0 .../models/KeyPhraseBatchResultItem.java | 0 .../models/KeyPhrasesOptionalParameter.java | 0 .../models/LanguageBatchResult.java | 0 .../models/LanguageBatchResultItem.java | 0 .../textanalytics/models/MatchRecord.java | 0 .../models/MultiLanguageBatchInput.java | 0 .../models/MultiLanguageInput.java | 0 .../models/SentimentBatchResult.java | 0 .../models/SentimentBatchResultItem.java | 0 .../models/SentimentOptionalParameter.java | 0 .../textanalytics/models/package-info.java | 0 .../language/textanalytics/package-info.java | 0 .../ms-azure-cs-videosearch}/pom.xml | 2 +- .../videosearch/BingVideoSearchAPI.java | 0 .../videosearch/BingVideoSearchManager.java | 0 .../search/videosearch/BingVideos.java | 0 .../BingVideoSearchAPIImpl.java | 0 .../implementation/BingVideosImpl.java | 0 .../implementation/package-info.java | 0 .../search/videosearch/models/Answer.java | 0 .../videosearch/models/CreativeWork.java | 0 .../models/DetailsOptionalParameter.java | 0 .../search/videosearch/models/Error.java | 0 .../search/videosearch/models/ErrorCode.java | 0 .../videosearch/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../videosearch/models/ErrorSubCode.java | 0 .../search/videosearch/models/Freshness.java | 0 .../videosearch/models/Identifiable.java | 0 .../videosearch/models/ImageObject.java | 0 .../videosearch/models/MediaObject.java | 0 .../videosearch/models/PivotSuggestions.java | 0 .../search/videosearch/models/Query.java | 0 .../videosearch/models/QueryContext.java | 0 .../search/videosearch/models/Response.java | 0 .../videosearch/models/ResponseBase.java | 0 .../search/videosearch/models/SafeSearch.java | 0 .../models/SearchOptionalParameter.java | 0 .../models/SearchResultsAnswer.java | 0 .../search/videosearch/models/TextFormat.java | 0 .../search/videosearch/models/Thing.java | 0 .../models/TrendingOptionalParameter.java | 0 .../videosearch/models/TrendingVideos.java | 0 .../models/TrendingVideosCategory.java | 0 .../models/TrendingVideosSubcategory.java | 0 .../models/TrendingVideosTile.java | 0 .../videosearch/models/VideoDetails.java | 0 .../models/VideoInsightModule.java | 0 .../videosearch/models/VideoLength.java | 0 .../videosearch/models/VideoObject.java | 0 .../videosearch/models/VideoPricing.java | 0 .../models/VideoQueryScenario.java | 0 .../videosearch/models/VideoResolution.java | 0 .../videosearch/models/VideosModel.java | 0 .../videosearch/models/VideosModule.java | 0 .../videosearch/models/package-info.java | 0 .../search/videosearch/package-info.java | 0 .../ms-azure-cs-visualsearch}/pom.xml | 2 +- .../search/visualsearch/BingImages.java | 0 .../visualsearch/BingVisualSearchAPI.java | 0 .../visualsearch/BingVisualSearchManager.java | 0 .../implementation/BingImagesImpl.java | 0 .../BingVisualSearchAPIImpl.java | 0 .../implementation/package-info.java | 0 .../search/visualsearch/models/Action.java | 0 .../visualsearch/models/AggregateOffer.java | 0 .../visualsearch/models/AggregateRating.java | 0 .../visualsearch/models/CreativeWork.java | 0 .../search/visualsearch/models/CropArea.java | 0 .../search/visualsearch/models/Currency.java | 0 .../search/visualsearch/models/Error.java | 0 .../search/visualsearch/models/ErrorCode.java | 0 .../visualsearch/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../visualsearch/models/ErrorSubCode.java | 0 .../search/visualsearch/models/Filters.java | 0 .../visualsearch/models/Identifiable.java | 0 .../visualsearch/models/ImageAction.java | 0 .../models/ImageEntityAction.java | 0 .../search/visualsearch/models/ImageInfo.java | 0 .../visualsearch/models/ImageKnowledge.java | 0 .../models/ImageModuleAction.java | 0 .../visualsearch/models/ImageObject.java | 0 .../models/ImageRecipesAction.java | 0 .../models/ImageRelatedSearchesAction.java | 0 .../models/ImageShoppingSourcesAction.java | 0 .../search/visualsearch/models/ImageTag.java | 0 .../visualsearch/models/ImageTagRegion.java | 0 .../models/ImagesImageMetadata.java | 0 .../visualsearch/models/ImagesModule.java | 0 .../visualsearch/models/Intangible.java | 0 .../visualsearch/models/ItemAvailability.java | 0 .../visualsearch/models/KnowledgeRequest.java | 0 .../visualsearch/models/MediaObject.java | 0 .../models/NormalizedQuadrilateral.java | 0 .../search/visualsearch/models/Offer.java | 0 .../visualsearch/models/Organization.java | 0 .../search/visualsearch/models/Person.java | 0 .../search/visualsearch/models/Point2D.java | 0 .../visualsearch/models/PropertiesItem.java | 0 .../search/visualsearch/models/Query.java | 0 .../search/visualsearch/models/Rating.java | 0 .../search/visualsearch/models/Recipe.java | 0 .../visualsearch/models/RecipesModule.java | 0 .../models/RelatedSearchesModule.java | 0 .../search/visualsearch/models/Response.java | 0 .../visualsearch/models/ResponseBase.java | 0 .../visualsearch/models/StructuredValue.java | 0 .../search/visualsearch/models/Thing.java | 0 .../models/VisualSearchOptionalParameter.java | 0 .../models/VisualSearchRequest.java | 0 .../visualsearch/models/package-info.java | 0 .../search/visualsearch/package-info.java | 0 .../ms-azure-cs-websearch}/pom.xml | 2 +- .../search/websearch/BingWebSearch.java | 0 .../search/websearch/BingWebSearchAPI.java | 0 .../websearch/BingWebSearchManager.java | 0 .../implementation/BingWebSearchAPIImpl.java | 0 .../implementation/BingWebSearchImpl.java | 0 .../implementation/package-info.java | 0 .../search/websearch/models/Answer.java | 0 .../search/websearch/models/AnswerType.java | 0 .../search/websearch/models/Article.java | 0 .../search/websearch/models/Computation.java | 0 .../search/websearch/models/CreativeWork.java | 0 .../search/websearch/models/Error.java | 0 .../search/websearch/models/ErrorCode.java | 0 .../websearch/models/ErrorResponse.java | 0 .../models/ErrorResponseException.java | 0 .../search/websearch/models/ErrorSubCode.java | 0 .../search/websearch/models/Freshness.java | 0 .../search/websearch/models/Identifiable.java | 0 .../search/websearch/models/ImageObject.java | 0 .../search/websearch/models/Images.java | 0 .../search/websearch/models/Intangible.java | 0 .../search/websearch/models/MediaObject.java | 0 .../search/websearch/models/News.java | 0 .../search/websearch/models/NewsArticle.java | 0 .../search/websearch/models/Places.java | 0 .../search/websearch/models/Query.java | 0 .../search/websearch/models/QueryContext.java | 0 .../websearch/models/RankingRankingGroup.java | 0 .../websearch/models/RankingRankingItem.java | 0 .../models/RankingRankingResponse.java | 0 .../RelatedSearchesRelatedSearchAnswer.java | 0 .../search/websearch/models/Response.java | 0 .../search/websearch/models/ResponseBase.java | 0 .../search/websearch/models/SafeSearch.java | 0 .../models/SearchOptionalParameter.java | 0 .../websearch/models/SearchResponse.java | 0 .../websearch/models/SearchResultsAnswer.java | 0 .../websearch/models/SpellSuggestions.java | 0 .../websearch/models/StructuredValue.java | 0 .../search/websearch/models/TextFormat.java | 0 .../search/websearch/models/Thing.java | 0 .../search/websearch/models/TimeZone.java | 0 .../models/TimeZoneTimeZoneInformation.java | 0 .../search/websearch/models/VideoObject.java | 0 .../search/websearch/models/Videos.java | 0 .../search/websearch/models/WebMetaTag.java | 0 .../search/websearch/models/WebPage.java | 0 .../search/websearch/models/WebWebAnswer.java | 0 .../websearch/models/WebWebGrouping.java | 0 .../search/websearch/models/package-info.java | 0 .../search/websearch/package-info.java | 0 sdk/cognitiveservices/pom.service.xml | 19 +++++++++- .../cognitiveservices}/pom.xml | 36 +++++++++--------- 1018 files changed, 73 insertions(+), 55 deletions(-) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/pom.xml (98%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearch.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearchAPI.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearchManager.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/BingAutoSuggestSearchAPIImpl.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/BingAutoSuggestSearchImpl.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Action.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Answer.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/AutoSuggestOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/CreativeWork.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Error.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorCode.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorResponse.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorResponseException.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Identifiable.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/QueryContext.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Response.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ResponseBase.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ResponseFormat.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SafeSearch.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ScenarioType.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchAction.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchKind.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchResultsAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Suggestions.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SuggestionsSuggestionGroup.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Thing.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingautosuggest => sdk/cognitiveservices/ms-azure-cs-autosuggest}/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/package-info.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/pom.xml (98%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVision.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionClient.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionManager.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionClientImpl.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AdultInfo.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageByDomainInStreamOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageByDomainOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageInStreamOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Category.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CategoryDetail.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CelebritiesModel.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CelebrityResults.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ColorInfo.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionError.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionErrorCodes.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionErrorException.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DescribeImageInStreamOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DescribeImageOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Details.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DomainModelResults.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/FaceDescription.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/FaceRectangle.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Gender.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailInStreamOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageAnalysis.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageCaption.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageDescription.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageDescriptionDetails.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageMetadata.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageTag.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageType.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageUrl.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/LandmarkResults.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/LandmarksModel.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Line.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ListModelsResult.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ModelDescription.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrLanguages.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrLine.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrRegion.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrResult.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrWord.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognitionResult.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextInStreamOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizeTextHeaders.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizeTextInStreamHeaders.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagImageInStreamOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagImageOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagResult.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextOperationResult.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextOperationStatusCodes.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextRecognitionMode.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/VisualFeatureTypes.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Word.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/package-info.java (100%) rename {cognitiveservices/data-plane/vision/computervision => sdk/cognitiveservices/ms-azure-cs-computervision}/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/package-info.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/pom.xml (98%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ContentModeratorClient.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ContentModeratorManager.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ImageModerations.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementImageLists.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementImages.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementTermLists.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementTerms.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/Reviews.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/TextModerations.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ContentModeratorClientImpl.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImageListsImpl.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImagesImpl.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermListsImpl.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermsImpl.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/TextModerationsImpl.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/APIError.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/APIErrorException.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageFileInputOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageUrlInputOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameStreamOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameUrlOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Address.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AzureRegionBaseUrl.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyMetadata.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyModel.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyModelModel.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Candidate.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Classification.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory1.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory2.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory3.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Content.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateJobOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewBodyItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewBodyItemMetadataItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemMetadataItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItemMetadataItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/DetectedLanguage.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/DetectedTerms.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Email.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Error.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Evaluate.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateFileInputOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateMethodOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateUrlInputOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Face.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesFileInputOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesUrlInputOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FoundFaces.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Frame.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Frames.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/GetAllTermsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/GetVideoFramesOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/IPA.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Image.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageAdditionalInfoItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageIds.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageList.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageListMetadata.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Job.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobExecutionReportDetails.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobId.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobListResult.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/KeyValuePair.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Match.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchFileInputOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchMethodOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchResponse.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchUrlInputOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCR.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRFileInputOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRMethodOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRUrlInputOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/PII.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Phone.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/RefreshIndex.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/RefreshIndexAdvancedInfoItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Review.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/SSN.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Screen.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ScreenTextOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Status.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Tag.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermList.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermListMetadata.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Terms.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsData.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsInList.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsPaging.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TranscriptModerationBodyItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TranscriptModerationBodyItemTermsItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItemMetadataItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItemReviewerResultTagsItem.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/package-info.java (100%) rename {cognitiveservices/data-plane/vision/contentmoderator => sdk/cognitiveservices/ms-azure-cs-contentmoderator}/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/pom.xml (98%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomImageSearchAPI.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomImageSearchManager.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomInstances.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomImageSearchAPIImpl.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomInstancesImpl.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Answer.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/CreativeWork.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Error.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorCode.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorResponse.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorResponseException.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorSubCode.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Freshness.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Identifiable.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageAspect.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageColor.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageContent.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageLicense.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageObject.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageSearchOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageSize.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageType.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Images.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/MediaObject.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Query.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Response.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ResponseBase.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/SafeSearch.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/SearchResultsAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Thing.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/WebPage.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingcustomimagesearch => sdk/cognitiveservices/ms-azure-cs-customimagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/pom.xml (98%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomInstances.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomSearchAPI.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomSearchManager.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/BingCustomInstancesImpl.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/BingCustomSearchAPIImpl.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Answer.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/CreativeWork.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Error.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorCode.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorResponse.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorResponseException.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorSubCode.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Identifiable.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Query.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/QueryContext.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Response.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ResponseBase.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SafeSearch.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchResponse.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchResultsAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/TextFormat.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Thing.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebMetaTag.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebPage.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebWebAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingcustomsearch => sdk/cognitiveservices/ms-azure-cs-customsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/package-info.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/pom.xml (98%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/CustomVisionPredictionManager.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/PredictionEndpoint.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/Predictions.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionEndpointImpl.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionsImpl.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/BoundingBox.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/ImagePrediction.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/ImageUrl.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageUrlOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageUrlWithNoStoreOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageWithNoStoreOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/Prediction.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/package-info.java (100%) rename {cognitiveservices/data-plane/vision/customvision/prediction => sdk/cognitiveservices/ms-azure-cs-customvision-prediction}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/package-info.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/pom.xml (98%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/CustomVisionTrainingManager.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/TrainingApi.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/Trainings.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingApiImpl.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/BoundingBox.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Classifier.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImageRegionsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImageTagsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImagesFromDataOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateProjectOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateTagOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Domain.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/DomainType.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Export.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportFlavor.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportIterationOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportPlatform.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportStatusModel.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagePerformanceCountOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagePerformancesOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagesByIdsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetIterationPerformanceOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTagOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTaggedImageCountOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTaggedImagesOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTagsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetUntaggedImageCountOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetUntaggedImagesOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Image.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageCreateResult.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageCreateSummary.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageFileCreateBatch.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageFileCreateEntry.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateBatch.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateEntry.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImagePerformance.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImagePrediction.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegion.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateBatch.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateEntry.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateResult.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateSummary.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionProposal.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTag.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateBatch.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateEntry.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateSummary.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUploadStatus.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrl.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrlCreateBatch.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrlCreateEntry.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Iteration.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/IterationPerformance.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/OrderBy.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Prediction.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryResult.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryTag.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryToken.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Project.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ProjectSettings.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/QuickTestImageOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/QuickTestImageUrlOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Region.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/RegionProposal.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/StoredImagePrediction.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Tag.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/TagPerformance.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/package-info.java (100%) rename {cognitiveservices/data-plane/vision/customvision/training => sdk/cognitiveservices/ms-azure-cs-customvision-training}/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/pom.xml (98%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntities.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntitySearchAPI.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntitySearchManager.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/BingEntitiesImpl.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/BingEntitySearchAPIImpl.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Airport.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Answer.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/AnswerType.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/CivicStructure.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesAttribution.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesContractualRule.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesLicenseAttribution.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesLinkAttribution.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesMediaAttribution.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesTextAttribution.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/CreativeWork.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntertainmentBusiness.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntitiesEntityPresentationInfo.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntitiesModel.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityQueryScenario.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityScenario.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityType.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Error.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorCode.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorResponse.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorResponseException.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorSubCode.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/FoodEstablishment.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Hotel.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Identifiable.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ImageObject.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Intangible.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/License.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/LocalBusiness.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/LodgingBusiness.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/MediaObject.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/MovieTheater.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Organization.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Place.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Places.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/PostalAddress.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/QueryContext.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Response.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ResponseBase.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ResponseFormat.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Restaurant.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SafeSearch.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchResponse.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchResultsAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/StructuredValue.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Thing.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/TouristAttraction.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingentitysearch => sdk/cognitiveservices/ms-azure-cs-entitysearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/package-info.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/pom.xml (98%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceAPI.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceAPIManager.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceLists.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/Faces.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/PersonGroupPersons.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/PersonGroups.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceAPIImpl.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupsImpl.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/APIError.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/APIErrorException.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Accessory.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AccessoryType.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddFaceFromStreamOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddFaceFromUrlOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddPersonFaceFromStreamOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddPersonFaceFromUrlOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AzureRegions.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Blur.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/BlurLevel.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Coordinate.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreateFaceListsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreatePersonGroupPersonsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreatePersonGroupsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectWithStreamOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectWithUrlOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectedFace.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Emotion.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Error.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Exposure.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ExposureLevel.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceAttributeType.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceAttributes.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceLandmarks.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceList.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceRectangle.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FacialHair.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarMatchMode.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarRequest.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Gender.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GlassesType.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GroupRequest.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GroupResult.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Hair.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColor.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColorType.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HeadPose.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyCandidate.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyRequest.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyResult.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ImageUrl.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ListPersonGroupPersonsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ListPersonGroupsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Makeup.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/NameAndUserDataContract.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Noise.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/NoiseLevel.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Occlusion.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/PersistedFace.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Person.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/PersonGroup.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/SimilarFace.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/TrainingStatus.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/TrainingStatusType.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdateFaceListsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdateFaceOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonFaceRequest.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonGroupPersonsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonGroupsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyFaceToFaceRequest.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyFaceToPersonRequest.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyResult.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/package-info.java (100%) rename {cognitiveservices/data-plane/vision/faceapi => sdk/cognitiveservices/ms-azure-cs-faceapi}/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/pom.xml (98%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImageSearchAPI.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImageSearchManager.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImages.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImageSearchAPIImpl.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImagesImpl.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/AggregateOffer.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/AggregateRating.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Answer.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/CollectionPage.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/CreativeWork.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Currency.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/DetailsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Error.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorCode.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorResponse.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorResponseException.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorSubCode.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Freshness.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Identifiable.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageAspect.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageColor.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageContent.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageCropType.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageGallery.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsightModule.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsights.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsightsImageCaption.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageLicense.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageObject.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageSize.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageTagsModule.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageType.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesImageMetadata.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesModel.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesModule.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/InsightsTag.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Intangible.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ItemAvailability.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/MediaObject.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/NormalizedRectangle.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Offer.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Organization.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Person.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/PivotSuggestions.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/PropertiesItem.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Query.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Rating.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Recipe.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecipesModule.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntitiesModule.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntity.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntityGroup.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntityRegion.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RelatedCollectionsModule.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RelatedSearchesModule.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Response.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ResponseBase.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SafeSearch.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SearchOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SearchResultsAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/StructuredValue.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Thing.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImages.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImagesCategory.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImagesTile.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/WebPage.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingimagesearch => sdk/cognitiveservices/ms-azure-cs-imagesearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/package-info.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/pom.xml (98%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Apps.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/EndpointAPI.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Examples.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Features.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/LUISAuthoringClient.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/LUISAuthoringManager.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Models.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Patterns.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Permissions.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Trains.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Versions.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/AppsImpl.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/FeaturesImpl.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/LUISAuthoringClientImpl.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PatternsImpl.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PermissionsImpl.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/TrainsImpl.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/VersionsImpl.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddCompositeEntityChildOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddCustomPrebuiltDomainModelsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddEntityOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddExplicitListItemOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddHierarchicalEntityChildOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddIntentOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddPermissionsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationInfoResponse.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationPublishObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationSettingUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationSettings.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AvailableCulture.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AvailablePrebuiltEntityModel.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/BatchLabelExample.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ChildEntity.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CloneOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedList.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListEntityExtractor.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelPatchObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CollaboratorsArray.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeChildModelCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeEntityExtractor.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeEntityModel.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateClosedListEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateCompositeEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateCustomPrebuiltEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateHierarchicalEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreatePatternAnyEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreatePrebuiltEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateRegexEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CustomPrebuiltModel.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/DeleteIntentOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/DeletePermissionsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EndpointInfo.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EnqueueTrainingResponse.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntitiesSuggestionExample.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityExtractor.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityLabel.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityLabelObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityModelInfo.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityPrediction.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRole.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRoleCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRoleUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ErrorResponse.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ErrorResponseException.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExampleLabelObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExamplesMethodOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItem.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItemCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItemUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/FeatureInfoObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/FeaturesResponseObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetEntitySuggestionsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetIntentPatternsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetIntentSuggestionsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetPatternAnyEntityInfosOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetPatternsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetRegexEntityInfosOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildEntity.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildModelCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildModelUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalEntityExtractor.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalEntityModel.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalModel.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ImportMethodAppsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ImportMethodVersionsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentClassifier.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentPrediction.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentsSuggestionExample.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONEntity.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONModelFeature.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONRegexFeature.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONUtterance.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabelExampleResponse.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabelTextObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabeledUtterance.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListAppsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListClosedListsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListCompositeEntitiesOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListEntitiesOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListExamplesOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListFeaturesOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListHierarchicalEntitiesOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListIntentsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListModelsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListPhraseListsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListPrebuiltsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListVersionsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LuisApp.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelInfo.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelInfoResponse.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelTrainingDetails.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelTrainingInfo.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationError.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationStatus.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationStatusType.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatchClosedListOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAny.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyEntityExtractor.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyModelCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyModelUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternFeatureInfo.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRule.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleInfo.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PersonalAssistantsResponse.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraseListFeatureInfo.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraselistCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraselistUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomain.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainCreateBaseObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainItem.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainModelCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltEntity.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltEntityExtractor.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ProductionOrStagingEndpointInfo.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PublishSettingUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PublishSettings.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexEntity.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexEntityExtractor.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexModelCreateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexModelUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/SubClosedList.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/SubClosedListResponse.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/TaskUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/TrainingStatus.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateClosedListEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateCompositeEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateCustomPrebuiltEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateEntityOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateExplicitListItemOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateHierarchicalEntityChildOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateHierarchicalEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateIntentOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePatternAnyEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePermissionsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePhraseListOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePrebuiltEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateRegexEntityRoleOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateSettingsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateVersionsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UserAccessList.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UserCollaborator.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/VersionInfo.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/WordListBaseUpdateObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/WordListObject.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/package-info.java (100%) rename {cognitiveservices/data-plane/language/luis/authoring => sdk/cognitiveservices/ms-azure-cs-luis-authoring}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/package-info.java (100%) rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/pom.xml (98%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/EndpointAPI.java (100%) rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/LuisRuntimeAPI.java (100%) rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/LuisRuntimeManager.java (100%) rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/Predictions.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/LuisRuntimeAPIImpl.java (100%) rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/PredictionsImpl.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/package-info.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/APIError.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/APIErrorException.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/AzureRegions.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/CompositeChildModel.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/CompositeEntityModel.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityModel.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityWithResolution.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityWithScore.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/IntentModel.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/LuisResult.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/ResolveOptionalParameter.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/Sentiment.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/package-info.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/luis/runtime => sdk/cognitiveservices/ms-azure-cs-luis-runtime}/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/package-info.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/pom.xml (98%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNews.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNewsSearchAPI.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNewsSearchManager.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsImpl.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsSearchAPIImpl.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Answer.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Article.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/CategoryOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/CreativeWork.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Error.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorCode.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorResponse.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorResponseException.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorSubCode.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Freshness.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Identifiable.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ImageObject.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/MediaObject.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsArticle.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsModel.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsTopic.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Organization.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Query.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Response.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ResponseBase.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SafeSearch.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SearchOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SearchResultsAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TextFormat.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Thing.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TrendingOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TrendingTopics.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/VideoObject.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingnewssearch => sdk/cognitiveservices/ms-azure-cs-newssearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/package-info.java (100%) rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/pom.xml (98%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckAPI.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckManager.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckOperations.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckAPIImpl.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckOperationsImpl.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/package-info.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ActionType.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Answer.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Error.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorCode.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorResponse.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorResponseException.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorSubCode.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorType.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Identifiable.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Response.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ResponseBase.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellCheck.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellCheckerOptionalParameter.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellingFlaggedToken.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellingTokenSuggestion.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/package-info.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/bingspellcheck => sdk/cognitiveservices/ms-azure-cs-spellcheck}/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/package-info.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/pom.xml (98%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalytics.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsAPI.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsManager.java (100%) rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsAPIImpl.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsImpl.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/package-info.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/AzureRegions.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/BatchInput.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/DetectLanguageOptionalParameter.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/DetectedLanguage.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesBatchResult.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesBatchResultItem.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesOptionalParameter.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntityRecord.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorRecord.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorResponse.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorResponseException.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/Input.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/InternalError.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhraseBatchResult.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhraseBatchResultItem.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhrasesOptionalParameter.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/LanguageBatchResult.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/LanguageBatchResultItem.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MatchRecord.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MultiLanguageBatchInput.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MultiLanguageInput.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentBatchResult.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentBatchResultItem.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentOptionalParameter.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/package-info.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/language/textanalytics => sdk/cognitiveservices/ms-azure-cs-textanalytics}/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/package-info.java (100%) mode change 100755 => 100644 rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/pom.xml (98%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideoSearchAPI.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideoSearchManager.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideos.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideoSearchAPIImpl.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Answer.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/CreativeWork.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/DetailsOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Error.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorCode.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorResponse.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorResponseException.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorSubCode.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Freshness.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Identifiable.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ImageObject.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/MediaObject.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/PivotSuggestions.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Query.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/QueryContext.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Response.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ResponseBase.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SafeSearch.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SearchOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SearchResultsAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TextFormat.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Thing.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideos.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosCategory.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosSubcategory.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosTile.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoDetails.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoInsightModule.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoLength.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoObject.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoPricing.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoQueryScenario.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoResolution.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideosModel.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideosModule.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingvideosearch => sdk/cognitiveservices/ms-azure-cs-videosearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/pom.xml (98%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingImages.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingVisualSearchAPI.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingVisualSearchManager.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingImagesImpl.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingVisualSearchAPIImpl.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Action.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/AggregateOffer.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/AggregateRating.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/CreativeWork.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/CropArea.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Currency.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Error.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorCode.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorResponse.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorResponseException.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorSubCode.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Filters.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Identifiable.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageAction.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageEntityAction.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageInfo.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageKnowledge.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageModuleAction.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageObject.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageRecipesAction.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageRelatedSearchesAction.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageShoppingSourcesAction.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageTag.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageTagRegion.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImagesImageMetadata.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImagesModule.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Intangible.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ItemAvailability.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/KnowledgeRequest.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/MediaObject.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/NormalizedQuadrilateral.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Offer.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Organization.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Person.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Point2D.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/PropertiesItem.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Query.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Rating.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Recipe.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/RecipesModule.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/RelatedSearchesModule.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Response.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ResponseBase.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/StructuredValue.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Thing.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/VisualSearchOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/VisualSearchRequest.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingvisualsearch => sdk/cognitiveservices/ms-azure-cs-visualsearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/pom.xml (98%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearch.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearchAPI.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearchManager.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchAPIImpl.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchImpl.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Answer.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/AnswerType.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Article.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Computation.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/CreativeWork.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Error.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorCode.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorResponse.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorResponseException.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorSubCode.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Freshness.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Identifiable.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ImageObject.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Images.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Intangible.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/MediaObject.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/News.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/NewsArticle.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Places.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Query.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/QueryContext.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingGroup.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingItem.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingResponse.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RelatedSearchesRelatedSearchAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Response.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ResponseBase.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SafeSearch.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchOptionalParameter.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchResponse.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchResultsAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SpellSuggestions.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/StructuredValue.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TextFormat.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Thing.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TimeZone.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TimeZoneTimeZoneInformation.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/VideoObject.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Videos.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebMetaTag.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebPage.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebWebAnswer.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebWebGrouping.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/package-info.java (100%) rename {cognitiveservices/data-plane/search/bingwebsearch => sdk/cognitiveservices/ms-azure-cs-websearch}/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/package-info.java (100%) rename {cognitiveservices/data-plane => sdk/cognitiveservices}/pom.xml (92%) mode change 100755 => 100644 diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml index d1b091127da59..fde81ca0d4b8f 100644 --- a/eng/.docsettings.yml +++ b/eng/.docsettings.yml @@ -17,30 +17,31 @@ required_readme_sections: - ^Next steps$ - ^Contributing$ known_presence_issues: - - ['cognitiveservices/data-plane/language/bingspellcheck', '#2847'] - - ['cognitiveservices/data-plane/language/luis/authoring', '#2847'] - - ['cognitiveservices/data-plane/language/luis/runtime', '#2847'] - - ['cognitiveservices/data-plane/language/textanalytics', '#2847'] - - ['cognitiveservices/data-plane/search/bingautosuggest', '#2847'] - - ['cognitiveservices/data-plane/search/bingcustomimagesearch', '#2847'] - - ['cognitiveservices/data-plane/search/bingcustomsearch', '#2847'] - - ['cognitiveservices/data-plane/search/bingentitysearch', '#2847'] - - ['cognitiveservices/data-plane/search/bingimagesearch', '#2847'] - - ['cognitiveservices/data-plane/search/bingnewssearch', '#2847'] - - ['cognitiveservices/data-plane/search/bingvideosearch', '#2847'] - - ['cognitiveservices/data-plane/search/bingvisualsearch', '#2847'] - - ['cognitiveservices/data-plane/search/bingwebsearch', '#2847'] - - ['cognitiveservices/data-plane/vision/computervision', '#2847'] - - ['cognitiveservices/data-plane/vision/contentmoderator', '#2847'] - - ['cognitiveservices/data-plane/vision/customvision/prediction', '#2847'] - - ['cognitiveservices/data-plane/vision/customvision/training', '#2847'] - - ['cognitiveservices/data-plane/vision/faceapi', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-spellcheck', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-luis-authoring', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-luis-runtime', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-textanalytics', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-autosuggest', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-customimagesearch', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-customsearch', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-entitysearch', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-imagesearch', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-newssearch', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-videosearch', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-visualsearch', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-websearch', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-computervision', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-contentmoderator', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-customvision-prediction', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-customvision-training', '#2847'] + - ['sdk/cognitiveservices/ms-azure-cs-faceapi', '#2847'] - ['sdk/keyvault/microsoft-azure-keyvault', '#2847'] - ['sdk/keyvault/microsoft-azure-keyvault-core', '#2847'] - ['sdk/keyvault/microsoft-azure-keyvault-cryptography', '#2847'] - ['sdk/keyvault/microsoft-azure-keyvault-extensions', '#2847'] - ['sdk/keyvault/microsoft-azure-keyvault-webkey', '#2847'] - ['sdk/mediaservices/microsoft-azure-media', '#2847'] + - ['mediaservices/data-plane', '#2847'] - ['core/build-tools', '#2847'] - ['core/azure-core', '#2847'] - ['core/azure-core-auth', '#2847'] diff --git a/cognitiveservices/data-plane/search/bingautosuggest/pom.xml b/sdk/cognitiveservices/ms-azure-cs-autosuggest/pom.xml similarity index 98% rename from cognitiveservices/data-plane/search/bingautosuggest/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/pom.xml index 115e1708562a9..5b91d450eed0d 100644 --- a/cognitiveservices/data-plane/search/bingautosuggest/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-autosuggest/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-autosuggest 1.0.2-beta diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearch.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearch.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearch.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearch.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearchAPI.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearchAPI.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearchAPI.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearchAPI.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearchManager.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearchManager.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearchManager.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/BingAutoSuggestSearchManager.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/BingAutoSuggestSearchAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/BingAutoSuggestSearchAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/BingAutoSuggestSearchAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/BingAutoSuggestSearchAPIImpl.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/BingAutoSuggestSearchImpl.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/BingAutoSuggestSearchImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/BingAutoSuggestSearchImpl.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/BingAutoSuggestSearchImpl.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/implementation/package-info.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Action.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Action.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Action.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Action.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Answer.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Answer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Answer.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Answer.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/AutoSuggestOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/AutoSuggestOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/AutoSuggestOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/AutoSuggestOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/CreativeWork.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/CreativeWork.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/CreativeWork.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/CreativeWork.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Error.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorCode.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorCode.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorCode.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorResponseException.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Identifiable.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Identifiable.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Identifiable.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Identifiable.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/QueryContext.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/QueryContext.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/QueryContext.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/QueryContext.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Response.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Response.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Response.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Response.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ResponseBase.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ResponseBase.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ResponseBase.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ResponseBase.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ResponseFormat.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ResponseFormat.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ResponseFormat.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ResponseFormat.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SafeSearch.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SafeSearch.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SafeSearch.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SafeSearch.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ScenarioType.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ScenarioType.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ScenarioType.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/ScenarioType.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchAction.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchAction.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchAction.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchAction.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchKind.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchKind.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchKind.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchKind.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchResultsAnswer.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchResultsAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchResultsAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SearchResultsAnswer.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Suggestions.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Suggestions.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Suggestions.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Suggestions.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SuggestionsSuggestionGroup.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SuggestionsSuggestionGroup.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SuggestionsSuggestionGroup.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/SuggestionsSuggestionGroup.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Thing.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Thing.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Thing.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/Thing.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/models/package-info.java diff --git a/cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/package-info.java b/sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingautosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-autosuggest/src/main/java/com/microsoft/azure/cognitiveservices/search/autosuggest/package-info.java diff --git a/cognitiveservices/data-plane/vision/computervision/pom.xml b/sdk/cognitiveservices/ms-azure-cs-computervision/pom.xml old mode 100755 new mode 100644 similarity index 98% rename from cognitiveservices/data-plane/vision/computervision/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-computervision/pom.xml index f585c51f98577..67d7daafb80bc --- a/cognitiveservices/data-plane/vision/computervision/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-computervision/pom.xml @@ -11,7 +11,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-computervision 1.0.2-beta diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVision.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVision.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVision.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVision.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionClient.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionClient.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionClient.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionClient.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionManager.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionManager.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionManager.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVisionManager.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionClientImpl.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionClientImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionClientImpl.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionClientImpl.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/package-info.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AdultInfo.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AdultInfo.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AdultInfo.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AdultInfo.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageByDomainInStreamOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageByDomainInStreamOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageByDomainInStreamOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageByDomainInStreamOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageByDomainOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageByDomainOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageByDomainOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageByDomainOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageInStreamOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageInStreamOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageInStreamOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageInStreamOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/AnalyzeImageOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Category.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Category.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Category.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Category.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CategoryDetail.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CategoryDetail.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CategoryDetail.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CategoryDetail.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CelebritiesModel.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CelebritiesModel.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CelebritiesModel.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CelebritiesModel.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CelebrityResults.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CelebrityResults.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CelebrityResults.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/CelebrityResults.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ColorInfo.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ColorInfo.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ColorInfo.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ColorInfo.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionError.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionError.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionError.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionError.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionErrorCodes.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionErrorCodes.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionErrorCodes.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionErrorCodes.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionErrorException.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionErrorException.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionErrorException.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ComputerVisionErrorException.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DescribeImageInStreamOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DescribeImageInStreamOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DescribeImageInStreamOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DescribeImageInStreamOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DescribeImageOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DescribeImageOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DescribeImageOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DescribeImageOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Details.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Details.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Details.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Details.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DomainModelResults.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DomainModelResults.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DomainModelResults.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/DomainModelResults.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/FaceDescription.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/FaceDescription.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/FaceDescription.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/FaceDescription.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/FaceRectangle.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/FaceRectangle.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/FaceRectangle.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/FaceRectangle.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Gender.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Gender.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Gender.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Gender.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailInStreamOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailInStreamOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailInStreamOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailInStreamOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/GenerateThumbnailOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageAnalysis.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageAnalysis.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageAnalysis.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageAnalysis.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageCaption.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageCaption.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageCaption.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageCaption.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageDescription.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageDescription.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageDescription.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageDescription.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageDescriptionDetails.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageDescriptionDetails.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageDescriptionDetails.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageDescriptionDetails.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageMetadata.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageMetadata.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageMetadata.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageMetadata.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageTag.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageTag.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageTag.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageTag.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageType.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageType.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageType.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageType.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageUrl.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageUrl.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageUrl.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ImageUrl.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/LandmarkResults.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/LandmarkResults.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/LandmarkResults.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/LandmarkResults.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/LandmarksModel.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/LandmarksModel.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/LandmarksModel.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/LandmarksModel.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Line.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Line.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Line.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Line.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ListModelsResult.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ListModelsResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ListModelsResult.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ListModelsResult.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ModelDescription.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ModelDescription.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ModelDescription.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/ModelDescription.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrLanguages.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrLanguages.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrLanguages.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrLanguages.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrLine.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrLine.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrLine.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrLine.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrRegion.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrRegion.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrRegion.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrRegion.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrResult.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrResult.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrResult.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrWord.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrWord.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrWord.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/OcrWord.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognitionResult.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognitionResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognitionResult.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognitionResult.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextInStreamOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextInStreamOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextInStreamOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextInStreamOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizePrintedTextOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizeTextHeaders.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizeTextHeaders.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizeTextHeaders.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizeTextHeaders.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizeTextInStreamHeaders.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizeTextInStreamHeaders.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizeTextInStreamHeaders.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/RecognizeTextInStreamHeaders.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagImageInStreamOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagImageInStreamOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagImageInStreamOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagImageInStreamOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagImageOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagImageOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagImageOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagImageOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagResult.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagResult.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TagResult.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextOperationResult.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextOperationResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextOperationResult.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextOperationResult.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextOperationStatusCodes.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextOperationStatusCodes.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextOperationStatusCodes.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextOperationStatusCodes.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextRecognitionMode.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextRecognitionMode.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextRecognitionMode.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/TextRecognitionMode.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/VisualFeatureTypes.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/VisualFeatureTypes.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/VisualFeatureTypes.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/VisualFeatureTypes.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Word.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Word.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Word.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/Word.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/models/package-info.java diff --git a/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/package-info.java b/sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/package-info.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/pom.xml b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/pom.xml old mode 100755 new mode 100644 similarity index 98% rename from cognitiveservices/data-plane/vision/contentmoderator/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/pom.xml index 4d970865955fc..0678ef83bea88 --- a/cognitiveservices/data-plane/vision/contentmoderator/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/pom.xml @@ -11,7 +11,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-contentmoderator 1.0.2-beta diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ContentModeratorClient.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ContentModeratorClient.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ContentModeratorClient.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ContentModeratorClient.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ContentModeratorManager.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ContentModeratorManager.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ContentModeratorManager.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ContentModeratorManager.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ImageModerations.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ImageModerations.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ImageModerations.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ImageModerations.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementImageLists.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementImageLists.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementImageLists.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementImageLists.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementImages.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementImages.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementImages.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementImages.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementTermLists.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementTermLists.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementTermLists.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementTermLists.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementTerms.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementTerms.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementTerms.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/ListManagementTerms.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/Reviews.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/Reviews.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/Reviews.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/Reviews.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/TextModerations.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/TextModerations.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/TextModerations.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/TextModerations.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ContentModeratorClientImpl.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ContentModeratorClientImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ContentModeratorClientImpl.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ContentModeratorClientImpl.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ImageModerationsImpl.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImageListsImpl.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImageListsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImageListsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImageListsImpl.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImagesImpl.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImagesImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImagesImpl.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementImagesImpl.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermListsImpl.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermListsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermListsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermListsImpl.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermsImpl.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ListManagementTermsImpl.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/TextModerationsImpl.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/TextModerationsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/TextModerationsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/TextModerationsImpl.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/package-info.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/APIError.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/APIError.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/APIError.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/APIError.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/APIErrorException.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/APIErrorException.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/APIErrorException.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/APIErrorException.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageFileInputOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageFileInputOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageFileInputOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageFileInputOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageUrlInputOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageUrlInputOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageUrlInputOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddImageUrlInputOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameStreamOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameStreamOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameStreamOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameStreamOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameUrlOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameUrlOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameUrlOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AddVideoFrameUrlOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Address.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Address.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Address.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Address.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AzureRegionBaseUrl.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AzureRegionBaseUrl.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AzureRegionBaseUrl.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/AzureRegionBaseUrl.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyMetadata.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyMetadata.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyMetadata.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyMetadata.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyModel.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyModel.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyModel.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyModel.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyModelModel.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyModelModel.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyModelModel.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/BodyModelModel.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Candidate.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Candidate.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Candidate.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Candidate.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Classification.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Classification.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Classification.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Classification.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory1.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory1.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory1.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory1.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory2.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory2.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory2.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory2.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory3.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory3.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory3.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ClassificationCategory3.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Content.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Content.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Content.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Content.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateJobOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateJobOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateJobOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateJobOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewBodyItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewBodyItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewBodyItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewBodyItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewBodyItemMetadataItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewBodyItemMetadataItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewBodyItemMetadataItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewBodyItemMetadataItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateReviewsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemMetadataItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemMetadataItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemMetadataItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemMetadataItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItemMetadataItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItemMetadataItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItemMetadataItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItemMetadataItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsBodyItemVideoFramesItemReviewerResultTagsItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/CreateVideoReviewsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/DetectedLanguage.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/DetectedLanguage.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/DetectedLanguage.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/DetectedLanguage.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/DetectedTerms.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/DetectedTerms.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/DetectedTerms.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/DetectedTerms.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Email.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Email.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Email.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Email.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Error.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Evaluate.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Evaluate.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Evaluate.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Evaluate.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateFileInputOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateFileInputOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateFileInputOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateFileInputOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateMethodOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateMethodOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateMethodOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateMethodOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateUrlInputOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateUrlInputOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateUrlInputOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/EvaluateUrlInputOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Face.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Face.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Face.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Face.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesFileInputOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesFileInputOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesFileInputOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesFileInputOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesUrlInputOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesUrlInputOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesUrlInputOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FindFacesUrlInputOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FoundFaces.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FoundFaces.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FoundFaces.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/FoundFaces.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Frame.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Frame.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Frame.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Frame.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Frames.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Frames.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Frames.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Frames.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/GetAllTermsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/GetAllTermsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/GetAllTermsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/GetAllTermsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/GetVideoFramesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/GetVideoFramesOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/GetVideoFramesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/GetVideoFramesOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/IPA.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/IPA.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/IPA.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/IPA.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Image.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Image.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Image.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Image.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageAdditionalInfoItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageAdditionalInfoItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageAdditionalInfoItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageAdditionalInfoItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageIds.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageIds.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageIds.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageIds.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageList.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageList.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageList.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageList.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageListMetadata.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageListMetadata.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageListMetadata.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ImageListMetadata.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Job.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Job.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Job.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Job.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobExecutionReportDetails.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobExecutionReportDetails.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobExecutionReportDetails.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobExecutionReportDetails.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobId.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobId.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobId.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobId.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobListResult.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobListResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobListResult.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/JobListResult.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/KeyValuePair.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/KeyValuePair.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/KeyValuePair.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/KeyValuePair.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Match.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Match.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Match.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Match.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchFileInputOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchFileInputOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchFileInputOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchFileInputOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchMethodOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchMethodOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchMethodOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchMethodOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchResponse.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchResponse.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchResponse.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchResponse.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchUrlInputOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchUrlInputOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchUrlInputOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/MatchUrlInputOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCR.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCR.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCR.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCR.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRFileInputOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRFileInputOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRFileInputOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRFileInputOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRMethodOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRMethodOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRMethodOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRMethodOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRUrlInputOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRUrlInputOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRUrlInputOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/OCRUrlInputOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/PII.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/PII.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/PII.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/PII.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Phone.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Phone.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Phone.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Phone.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/RefreshIndex.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/RefreshIndex.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/RefreshIndex.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/RefreshIndex.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/RefreshIndexAdvancedInfoItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/RefreshIndexAdvancedInfoItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/RefreshIndexAdvancedInfoItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/RefreshIndexAdvancedInfoItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Review.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Review.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Review.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Review.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/SSN.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/SSN.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/SSN.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/SSN.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Screen.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Screen.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Screen.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Screen.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ScreenTextOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ScreenTextOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ScreenTextOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/ScreenTextOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Status.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Status.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Status.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Status.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Tag.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Tag.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Tag.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Tag.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermList.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermList.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermList.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermList.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermListMetadata.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermListMetadata.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermListMetadata.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermListMetadata.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Terms.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Terms.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Terms.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/Terms.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsData.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsData.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsData.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsData.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsInList.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsInList.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsInList.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsInList.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsPaging.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsPaging.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsPaging.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TermsPaging.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TranscriptModerationBodyItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TranscriptModerationBodyItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TranscriptModerationBodyItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TranscriptModerationBodyItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TranscriptModerationBodyItemTermsItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TranscriptModerationBodyItemTermsItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TranscriptModerationBodyItemTermsItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/TranscriptModerationBodyItemTermsItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItemMetadataItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItemMetadataItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItemMetadataItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItemMetadataItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItemReviewerResultTagsItem.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItemReviewerResultTagsItem.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItemReviewerResultTagsItem.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/VideoFrameBodyItemReviewerResultTagsItem.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/models/package-info.java diff --git a/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/package-info.java b/sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/package-info.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/pom.xml b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/pom.xml similarity index 98% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/pom.xml index 4362d9179db56..2d99abaad5d71 100644 --- a/cognitiveservices/data-plane/search/bingcustomimagesearch/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-customimagesearch 1.0.2-beta diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomImageSearchAPI.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomImageSearchAPI.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomImageSearchAPI.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomImageSearchAPI.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomImageSearchManager.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomImageSearchManager.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomImageSearchManager.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomImageSearchManager.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomInstances.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomInstances.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomInstances.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/BingCustomInstances.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomImageSearchAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomImageSearchAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomImageSearchAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomImageSearchAPIImpl.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomInstancesImpl.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomInstancesImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomInstancesImpl.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/BingCustomInstancesImpl.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/implementation/package-info.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Answer.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Answer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Answer.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Answer.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/CreativeWork.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/CreativeWork.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/CreativeWork.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/CreativeWork.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Error.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorCode.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorCode.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorCode.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorResponseException.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorSubCode.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorSubCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorSubCode.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ErrorSubCode.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Freshness.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Freshness.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Freshness.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Freshness.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Identifiable.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Identifiable.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Identifiable.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Identifiable.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageAspect.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageAspect.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageAspect.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageAspect.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageColor.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageColor.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageColor.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageColor.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageContent.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageContent.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageContent.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageContent.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageLicense.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageLicense.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageLicense.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageLicense.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageObject.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageObject.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageObject.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageSearchOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageSearchOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageSearchOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageSearchOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageSize.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageSize.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageSize.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageSize.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageType.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageType.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageType.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ImageType.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Images.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Images.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Images.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Images.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/MediaObject.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/MediaObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/MediaObject.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/MediaObject.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Query.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Query.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Query.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Query.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Response.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Response.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Response.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Response.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ResponseBase.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ResponseBase.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ResponseBase.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/ResponseBase.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/SafeSearch.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/SafeSearch.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/SafeSearch.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/SafeSearch.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/SearchResultsAnswer.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/SearchResultsAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/SearchResultsAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/SearchResultsAnswer.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Thing.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Thing.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Thing.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/Thing.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/WebPage.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/WebPage.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/WebPage.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/WebPage.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/models/package-info.java diff --git a/cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customimagesearch/package-info.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/pom.xml b/sdk/cognitiveservices/ms-azure-cs-customsearch/pom.xml similarity index 98% rename from cognitiveservices/data-plane/search/bingcustomsearch/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-customsearch/pom.xml index 14c184488025a..5b6ac07a479a8 100644 --- a/cognitiveservices/data-plane/search/bingcustomsearch/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-customsearch/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-customsearch 1.0.2 diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomInstances.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomInstances.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomInstances.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomInstances.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomSearchAPI.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomSearchAPI.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomSearchAPI.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomSearchAPI.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomSearchManager.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomSearchManager.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomSearchManager.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/BingCustomSearchManager.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/BingCustomInstancesImpl.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/BingCustomInstancesImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/BingCustomInstancesImpl.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/BingCustomInstancesImpl.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/BingCustomSearchAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/BingCustomSearchAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/BingCustomSearchAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/BingCustomSearchAPIImpl.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/implementation/package-info.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Answer.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Answer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Answer.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Answer.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/CreativeWork.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/CreativeWork.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/CreativeWork.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/CreativeWork.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Error.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorCode.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorCode.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorCode.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorResponseException.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorSubCode.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorSubCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorSubCode.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ErrorSubCode.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Identifiable.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Identifiable.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Identifiable.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Identifiable.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Query.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Query.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Query.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Query.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/QueryContext.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/QueryContext.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/QueryContext.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/QueryContext.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Response.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Response.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Response.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Response.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ResponseBase.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ResponseBase.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ResponseBase.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/ResponseBase.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SafeSearch.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SafeSearch.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SafeSearch.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SafeSearch.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchResponse.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchResponse.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchResponse.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchResultsAnswer.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchResultsAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchResultsAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/SearchResultsAnswer.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/TextFormat.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/TextFormat.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/TextFormat.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/TextFormat.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Thing.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Thing.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Thing.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/Thing.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebMetaTag.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebMetaTag.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebMetaTag.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebMetaTag.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebPage.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebPage.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebPage.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebPage.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebWebAnswer.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebWebAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebWebAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/WebWebAnswer.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/models/package-info.java diff --git a/cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingcustomsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/customsearch/package-info.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/pom.xml b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/pom.xml similarity index 98% rename from cognitiveservices/data-plane/vision/customvision/prediction/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/pom.xml index e208aaa0b909d..f4ee4cec9cb4f 100644 --- a/cognitiveservices/data-plane/vision/customvision/prediction/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/pom.xml @@ -11,7 +11,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../../pom.xml + ../pom.xml azure-cognitiveservices-customvision-prediction 1.0.2-beta diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/CustomVisionPredictionManager.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/CustomVisionPredictionManager.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/CustomVisionPredictionManager.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/CustomVisionPredictionManager.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/PredictionEndpoint.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/PredictionEndpoint.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/PredictionEndpoint.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/PredictionEndpoint.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/Predictions.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/Predictions.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/Predictions.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/Predictions.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionEndpointImpl.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionEndpointImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionEndpointImpl.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionEndpointImpl.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionsImpl.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/PredictionsImpl.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/implementation/package-info.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/BoundingBox.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/BoundingBox.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/BoundingBox.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/BoundingBox.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/ImagePrediction.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/ImagePrediction.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/ImagePrediction.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/ImagePrediction.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/ImageUrl.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/ImageUrl.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/ImageUrl.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/ImageUrl.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageUrlOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageUrlOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageUrlOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageUrlOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageUrlWithNoStoreOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageUrlWithNoStoreOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageUrlWithNoStoreOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageUrlWithNoStoreOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageWithNoStoreOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageWithNoStoreOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageWithNoStoreOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/PredictImageWithNoStoreOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/Prediction.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/Prediction.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/Prediction.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/Prediction.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/models/package-info.java diff --git a/cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-prediction/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/prediction/package-info.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/pom.xml b/sdk/cognitiveservices/ms-azure-cs-customvision-training/pom.xml similarity index 98% rename from cognitiveservices/data-plane/vision/customvision/training/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/pom.xml index 9330c16a23f79..491e94891644b 100644 --- a/cognitiveservices/data-plane/vision/customvision/training/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-customvision-training/pom.xml @@ -11,7 +11,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../../pom.xml + ../pom.xml azure-cognitiveservices-customvision-training 1.0.2-beta diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/CustomVisionTrainingManager.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/CustomVisionTrainingManager.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/CustomVisionTrainingManager.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/CustomVisionTrainingManager.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/TrainingApi.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/TrainingApi.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/TrainingApi.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/TrainingApi.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/Trainings.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/Trainings.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/Trainings.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/Trainings.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingApiImpl.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingApiImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingApiImpl.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingApiImpl.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/TrainingsImpl.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/implementation/package-info.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/BoundingBox.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/BoundingBox.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/BoundingBox.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/BoundingBox.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Classifier.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Classifier.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Classifier.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Classifier.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImageRegionsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImageRegionsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImageRegionsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImageRegionsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImageTagsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImageTagsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImageTagsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImageTagsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImagesFromDataOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImagesFromDataOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImagesFromDataOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateImagesFromDataOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateProjectOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateProjectOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateProjectOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateProjectOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateTagOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateTagOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateTagOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/CreateTagOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Domain.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Domain.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Domain.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Domain.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/DomainType.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/DomainType.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/DomainType.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/DomainType.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Export.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Export.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Export.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Export.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportFlavor.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportFlavor.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportFlavor.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportFlavor.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportIterationOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportIterationOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportIterationOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportIterationOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportPlatform.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportPlatform.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportPlatform.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportPlatform.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportStatusModel.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportStatusModel.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportStatusModel.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ExportStatusModel.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagePerformanceCountOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagePerformanceCountOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagePerformanceCountOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagePerformanceCountOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagePerformancesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagePerformancesOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagePerformancesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagePerformancesOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagesByIdsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagesByIdsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagesByIdsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetImagesByIdsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetIterationPerformanceOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetIterationPerformanceOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetIterationPerformanceOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetIterationPerformanceOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTagOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTagOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTagOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTagOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTaggedImageCountOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTaggedImageCountOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTaggedImageCountOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTaggedImageCountOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTaggedImagesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTaggedImagesOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTaggedImagesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTaggedImagesOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTagsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTagsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTagsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetTagsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetUntaggedImageCountOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetUntaggedImageCountOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetUntaggedImageCountOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetUntaggedImageCountOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetUntaggedImagesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetUntaggedImagesOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetUntaggedImagesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/GetUntaggedImagesOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Image.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Image.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Image.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Image.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageCreateResult.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageCreateResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageCreateResult.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageCreateResult.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageCreateSummary.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageCreateSummary.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageCreateSummary.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageCreateSummary.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageFileCreateBatch.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageFileCreateBatch.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageFileCreateBatch.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageFileCreateBatch.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageFileCreateEntry.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageFileCreateEntry.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageFileCreateEntry.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageFileCreateEntry.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateBatch.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateBatch.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateBatch.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateBatch.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateEntry.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateEntry.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateEntry.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageIdCreateEntry.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImagePerformance.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImagePerformance.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImagePerformance.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImagePerformance.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImagePrediction.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImagePrediction.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImagePrediction.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImagePrediction.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegion.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegion.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegion.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegion.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateBatch.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateBatch.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateBatch.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateBatch.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateEntry.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateEntry.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateEntry.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateEntry.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateResult.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateResult.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateResult.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateSummary.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateSummary.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateSummary.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionCreateSummary.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionProposal.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionProposal.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionProposal.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageRegionProposal.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTag.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTag.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTag.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTag.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateBatch.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateBatch.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateBatch.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateBatch.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateEntry.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateEntry.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateEntry.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateEntry.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateSummary.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateSummary.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateSummary.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageTagCreateSummary.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUploadStatus.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUploadStatus.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUploadStatus.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUploadStatus.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrl.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrl.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrl.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrl.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrlCreateBatch.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrlCreateBatch.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrlCreateBatch.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrlCreateBatch.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrlCreateEntry.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrlCreateEntry.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrlCreateEntry.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ImageUrlCreateEntry.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Iteration.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Iteration.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Iteration.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Iteration.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/IterationPerformance.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/IterationPerformance.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/IterationPerformance.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/IterationPerformance.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/OrderBy.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/OrderBy.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/OrderBy.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/OrderBy.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Prediction.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Prediction.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Prediction.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Prediction.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryResult.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryResult.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryResult.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryTag.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryTag.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryTag.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryTag.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryToken.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryToken.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryToken.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/PredictionQueryToken.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Project.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Project.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Project.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Project.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ProjectSettings.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ProjectSettings.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ProjectSettings.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/ProjectSettings.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/QuickTestImageOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/QuickTestImageOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/QuickTestImageOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/QuickTestImageOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/QuickTestImageUrlOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/QuickTestImageUrlOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/QuickTestImageUrlOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/QuickTestImageUrlOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Region.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Region.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Region.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Region.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/RegionProposal.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/RegionProposal.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/RegionProposal.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/RegionProposal.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/StoredImagePrediction.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/StoredImagePrediction.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/StoredImagePrediction.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/StoredImagePrediction.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Tag.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Tag.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Tag.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/Tag.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/TagPerformance.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/TagPerformance.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/TagPerformance.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/TagPerformance.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/models/package-info.java diff --git a/cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/package-info.java b/sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/customvision/training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-customvision-training/src/main/java/com/microsoft/azure/cognitiveservices/vision/customvision/training/package-info.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/pom.xml b/sdk/cognitiveservices/ms-azure-cs-entitysearch/pom.xml similarity index 98% rename from cognitiveservices/data-plane/search/bingentitysearch/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/pom.xml index 58421872540f0..e43ccb17c512e 100644 --- a/cognitiveservices/data-plane/search/bingentitysearch/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-entitysearch/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-entitysearch 1.0.2 diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntities.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntities.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntities.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntities.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntitySearchAPI.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntitySearchAPI.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntitySearchAPI.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntitySearchAPI.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntitySearchManager.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntitySearchManager.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntitySearchManager.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/BingEntitySearchManager.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/BingEntitiesImpl.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/BingEntitiesImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/BingEntitiesImpl.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/BingEntitiesImpl.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/BingEntitySearchAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/BingEntitySearchAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/BingEntitySearchAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/BingEntitySearchAPIImpl.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/implementation/package-info.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Airport.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Airport.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Airport.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Airport.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Answer.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Answer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Answer.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Answer.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/AnswerType.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/AnswerType.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/AnswerType.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/AnswerType.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/CivicStructure.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/CivicStructure.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/CivicStructure.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/CivicStructure.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesAttribution.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesAttribution.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesAttribution.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesAttribution.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesContractualRule.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesContractualRule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesContractualRule.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesContractualRule.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesLicenseAttribution.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesLicenseAttribution.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesLicenseAttribution.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesLicenseAttribution.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesLinkAttribution.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesLinkAttribution.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesLinkAttribution.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesLinkAttribution.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesMediaAttribution.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesMediaAttribution.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesMediaAttribution.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesMediaAttribution.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesTextAttribution.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesTextAttribution.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesTextAttribution.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ContractualRulesTextAttribution.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/CreativeWork.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/CreativeWork.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/CreativeWork.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/CreativeWork.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntertainmentBusiness.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntertainmentBusiness.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntertainmentBusiness.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntertainmentBusiness.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntitiesEntityPresentationInfo.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntitiesEntityPresentationInfo.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntitiesEntityPresentationInfo.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntitiesEntityPresentationInfo.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntitiesModel.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntitiesModel.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntitiesModel.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntitiesModel.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityQueryScenario.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityQueryScenario.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityQueryScenario.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityQueryScenario.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityScenario.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityScenario.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityScenario.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityScenario.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityType.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityType.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityType.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/EntityType.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Error.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorCode.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorCode.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorCode.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorResponseException.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorSubCode.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorSubCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorSubCode.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ErrorSubCode.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/FoodEstablishment.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/FoodEstablishment.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/FoodEstablishment.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/FoodEstablishment.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Hotel.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Hotel.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Hotel.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Hotel.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Identifiable.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Identifiable.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Identifiable.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Identifiable.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ImageObject.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ImageObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ImageObject.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ImageObject.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Intangible.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Intangible.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Intangible.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Intangible.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/License.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/License.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/License.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/License.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/LocalBusiness.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/LocalBusiness.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/LocalBusiness.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/LocalBusiness.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/LodgingBusiness.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/LodgingBusiness.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/LodgingBusiness.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/LodgingBusiness.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/MediaObject.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/MediaObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/MediaObject.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/MediaObject.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/MovieTheater.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/MovieTheater.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/MovieTheater.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/MovieTheater.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Organization.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Organization.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Organization.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Organization.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Place.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Place.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Place.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Place.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Places.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Places.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Places.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Places.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/PostalAddress.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/PostalAddress.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/PostalAddress.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/PostalAddress.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/QueryContext.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/QueryContext.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/QueryContext.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/QueryContext.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Response.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Response.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Response.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Response.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ResponseBase.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ResponseBase.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ResponseBase.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ResponseBase.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ResponseFormat.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ResponseFormat.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ResponseFormat.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/ResponseFormat.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Restaurant.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Restaurant.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Restaurant.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Restaurant.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SafeSearch.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SafeSearch.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SafeSearch.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SafeSearch.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchResponse.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchResponse.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchResponse.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchResultsAnswer.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchResultsAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchResultsAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/SearchResultsAnswer.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/StructuredValue.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/StructuredValue.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/StructuredValue.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/StructuredValue.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Thing.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Thing.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Thing.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/Thing.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/TouristAttraction.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/TouristAttraction.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/TouristAttraction.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/TouristAttraction.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/models/package-info.java diff --git a/cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/package-info.java b/sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingentitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-entitysearch/src/main/java/com/microsoft/azure/cognitiveservices/search/entitysearch/package-info.java diff --git a/cognitiveservices/data-plane/vision/faceapi/pom.xml b/sdk/cognitiveservices/ms-azure-cs-faceapi/pom.xml similarity index 98% rename from cognitiveservices/data-plane/vision/faceapi/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-faceapi/pom.xml index 9da7c43166699..75833fdba5817 100644 --- a/cognitiveservices/data-plane/vision/faceapi/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-faceapi/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-faceapi 1.0.2-beta diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceAPI.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceAPI.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceAPI.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceAPI.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceAPIManager.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceAPIManager.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceAPIManager.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceAPIManager.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceLists.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceLists.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceLists.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/FaceLists.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/Faces.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/Faces.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/Faces.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/Faces.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/PersonGroupPersons.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/PersonGroupPersons.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/PersonGroupPersons.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/PersonGroupPersons.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/PersonGroups.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/PersonGroups.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/PersonGroups.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/PersonGroups.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceAPIImpl.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FaceListsImpl.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/FacesImpl.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupsImpl.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupsImpl.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupsImpl.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/package-info.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/APIError.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/APIError.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/APIError.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/APIError.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/APIErrorException.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/APIErrorException.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/APIErrorException.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/APIErrorException.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Accessory.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Accessory.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Accessory.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Accessory.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AccessoryType.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AccessoryType.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AccessoryType.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AccessoryType.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddFaceFromStreamOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddFaceFromStreamOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddFaceFromStreamOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddFaceFromStreamOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddFaceFromUrlOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddFaceFromUrlOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddFaceFromUrlOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddFaceFromUrlOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddPersonFaceFromStreamOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddPersonFaceFromStreamOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddPersonFaceFromStreamOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddPersonFaceFromStreamOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddPersonFaceFromUrlOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddPersonFaceFromUrlOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddPersonFaceFromUrlOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AddPersonFaceFromUrlOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AzureRegions.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AzureRegions.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AzureRegions.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/AzureRegions.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Blur.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Blur.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Blur.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Blur.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/BlurLevel.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/BlurLevel.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/BlurLevel.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/BlurLevel.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Coordinate.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Coordinate.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Coordinate.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Coordinate.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreateFaceListsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreateFaceListsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreateFaceListsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreateFaceListsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreatePersonGroupPersonsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreatePersonGroupPersonsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreatePersonGroupPersonsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreatePersonGroupPersonsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreatePersonGroupsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreatePersonGroupsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreatePersonGroupsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/CreatePersonGroupsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectWithStreamOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectWithStreamOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectWithStreamOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectWithStreamOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectWithUrlOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectWithUrlOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectWithUrlOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectWithUrlOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectedFace.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectedFace.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectedFace.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/DetectedFace.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Emotion.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Emotion.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Emotion.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Emotion.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Error.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Exposure.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Exposure.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Exposure.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Exposure.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ExposureLevel.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ExposureLevel.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ExposureLevel.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ExposureLevel.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceAttributeType.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceAttributeType.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceAttributeType.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceAttributeType.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceAttributes.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceAttributes.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceAttributes.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceAttributes.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceLandmarks.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceLandmarks.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceLandmarks.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceLandmarks.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceList.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceList.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceList.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceList.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceRectangle.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceRectangle.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceRectangle.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FaceRectangle.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FacialHair.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FacialHair.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FacialHair.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FacialHair.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarMatchMode.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarMatchMode.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarMatchMode.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarMatchMode.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarRequest.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarRequest.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarRequest.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/FindSimilarRequest.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Gender.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Gender.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Gender.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Gender.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GlassesType.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GlassesType.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GlassesType.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GlassesType.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GroupRequest.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GroupRequest.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GroupRequest.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GroupRequest.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GroupResult.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GroupResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GroupResult.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/GroupResult.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Hair.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Hair.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Hair.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Hair.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColor.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColor.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColor.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColor.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColorType.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColorType.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColorType.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HairColorType.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HeadPose.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HeadPose.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HeadPose.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/HeadPose.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyCandidate.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyCandidate.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyCandidate.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyCandidate.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyRequest.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyRequest.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyRequest.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyRequest.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyResult.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyResult.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/IdentifyResult.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ImageUrl.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ImageUrl.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ImageUrl.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ImageUrl.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ListPersonGroupPersonsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ListPersonGroupPersonsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ListPersonGroupPersonsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ListPersonGroupPersonsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ListPersonGroupsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ListPersonGroupsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ListPersonGroupsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/ListPersonGroupsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Makeup.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Makeup.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Makeup.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Makeup.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/NameAndUserDataContract.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/NameAndUserDataContract.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/NameAndUserDataContract.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/NameAndUserDataContract.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Noise.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Noise.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Noise.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Noise.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/NoiseLevel.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/NoiseLevel.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/NoiseLevel.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/NoiseLevel.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Occlusion.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Occlusion.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Occlusion.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Occlusion.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/PersistedFace.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/PersistedFace.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/PersistedFace.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/PersistedFace.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Person.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Person.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Person.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/Person.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/PersonGroup.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/PersonGroup.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/PersonGroup.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/PersonGroup.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/SimilarFace.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/SimilarFace.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/SimilarFace.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/SimilarFace.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/TrainingStatus.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/TrainingStatus.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/TrainingStatus.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/TrainingStatus.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/TrainingStatusType.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/TrainingStatusType.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/TrainingStatusType.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/TrainingStatusType.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdateFaceListsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdateFaceListsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdateFaceListsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdateFaceListsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdateFaceOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdateFaceOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdateFaceOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdateFaceOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonFaceRequest.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonFaceRequest.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonFaceRequest.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonFaceRequest.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonGroupPersonsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonGroupPersonsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonGroupPersonsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonGroupPersonsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonGroupsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonGroupsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonGroupsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/UpdatePersonGroupsOptionalParameter.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyFaceToFaceRequest.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyFaceToFaceRequest.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyFaceToFaceRequest.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyFaceToFaceRequest.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyFaceToPersonRequest.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyFaceToPersonRequest.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyFaceToPersonRequest.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyFaceToPersonRequest.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyResult.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyResult.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyResult.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/VerifyResult.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/models/package-info.java diff --git a/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/package-info.java b/sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/package-info.java similarity index 100% rename from cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/package-info.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/pom.xml b/sdk/cognitiveservices/ms-azure-cs-imagesearch/pom.xml similarity index 98% rename from cognitiveservices/data-plane/search/bingimagesearch/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/pom.xml index 6ec62a353a1e5..629742c83a1d1 100644 --- a/cognitiveservices/data-plane/search/bingimagesearch/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-imagesearch/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-imagesearch 1.0.2 diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImageSearchAPI.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImageSearchAPI.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImageSearchAPI.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImageSearchAPI.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImageSearchManager.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImageSearchManager.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImageSearchManager.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImageSearchManager.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImages.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImages.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImages.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/BingImages.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImageSearchAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImageSearchAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImageSearchAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImageSearchAPIImpl.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImagesImpl.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImagesImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImagesImpl.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/BingImagesImpl.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/implementation/package-info.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/AggregateOffer.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/AggregateOffer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/AggregateOffer.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/AggregateOffer.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/AggregateRating.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/AggregateRating.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/AggregateRating.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/AggregateRating.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Answer.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Answer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Answer.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Answer.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/CollectionPage.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/CollectionPage.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/CollectionPage.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/CollectionPage.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/CreativeWork.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/CreativeWork.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/CreativeWork.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/CreativeWork.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Currency.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Currency.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Currency.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Currency.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/DetailsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/DetailsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/DetailsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/DetailsOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Error.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorCode.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorCode.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorCode.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorResponseException.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorSubCode.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorSubCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorSubCode.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ErrorSubCode.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Freshness.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Freshness.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Freshness.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Freshness.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Identifiable.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Identifiable.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Identifiable.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Identifiable.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageAspect.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageAspect.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageAspect.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageAspect.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageColor.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageColor.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageColor.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageColor.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageContent.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageContent.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageContent.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageContent.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageCropType.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageCropType.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageCropType.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageCropType.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageGallery.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageGallery.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageGallery.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageGallery.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsightModule.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsightModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsightModule.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsightModule.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsights.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsights.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsights.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsights.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsightsImageCaption.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsightsImageCaption.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsightsImageCaption.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageInsightsImageCaption.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageLicense.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageLicense.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageLicense.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageLicense.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageObject.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageObject.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageObject.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageSize.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageSize.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageSize.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageSize.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageTagsModule.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageTagsModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageTagsModule.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageTagsModule.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageType.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageType.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageType.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImageType.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesImageMetadata.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesImageMetadata.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesImageMetadata.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesImageMetadata.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesModel.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesModel.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesModel.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesModel.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesModule.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesModule.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ImagesModule.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/InsightsTag.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/InsightsTag.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/InsightsTag.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/InsightsTag.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Intangible.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Intangible.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Intangible.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Intangible.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ItemAvailability.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ItemAvailability.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ItemAvailability.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ItemAvailability.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/MediaObject.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/MediaObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/MediaObject.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/MediaObject.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/NormalizedRectangle.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/NormalizedRectangle.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/NormalizedRectangle.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/NormalizedRectangle.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Offer.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Offer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Offer.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Offer.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Organization.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Organization.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Organization.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Organization.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Person.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Person.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Person.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Person.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/PivotSuggestions.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/PivotSuggestions.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/PivotSuggestions.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/PivotSuggestions.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/PropertiesItem.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/PropertiesItem.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/PropertiesItem.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/PropertiesItem.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Query.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Query.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Query.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Query.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Rating.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Rating.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Rating.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Rating.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Recipe.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Recipe.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Recipe.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Recipe.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecipesModule.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecipesModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecipesModule.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecipesModule.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntitiesModule.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntitiesModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntitiesModule.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntitiesModule.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntity.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntity.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntity.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntity.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntityGroup.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntityGroup.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntityGroup.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntityGroup.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntityRegion.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntityRegion.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntityRegion.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RecognizedEntityRegion.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RelatedCollectionsModule.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RelatedCollectionsModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RelatedCollectionsModule.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RelatedCollectionsModule.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RelatedSearchesModule.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RelatedSearchesModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RelatedSearchesModule.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/RelatedSearchesModule.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Response.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Response.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Response.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Response.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ResponseBase.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ResponseBase.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ResponseBase.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/ResponseBase.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SafeSearch.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SafeSearch.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SafeSearch.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SafeSearch.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SearchOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SearchOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SearchOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SearchOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SearchResultsAnswer.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SearchResultsAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SearchResultsAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/SearchResultsAnswer.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/StructuredValue.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/StructuredValue.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/StructuredValue.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/StructuredValue.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Thing.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Thing.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Thing.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/Thing.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImages.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImages.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImages.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImages.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImagesCategory.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImagesCategory.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImagesCategory.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImagesCategory.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImagesTile.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImagesTile.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImagesTile.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingImagesTile.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/TrendingOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/WebPage.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/WebPage.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/WebPage.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/WebPage.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/models/package-info.java diff --git a/cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/package-info.java b/sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingimagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-imagesearch/src/main/java/com/microsoft/azure/cognitiveservices/search/imagesearch/package-info.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/pom.xml b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/pom.xml similarity index 98% rename from cognitiveservices/data-plane/language/luis/authoring/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/pom.xml index 878d915c0ed1b..9989b6af3ece1 100644 --- a/cognitiveservices/data-plane/language/luis/authoring/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../../pom.xml + ../pom.xml azure-cognitiveservices-luis-authoring 1.0.2-beta diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Apps.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Apps.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Apps.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Apps.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/EndpointAPI.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/EndpointAPI.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/EndpointAPI.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/EndpointAPI.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Examples.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Examples.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Examples.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Examples.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Features.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Features.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Features.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Features.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/LUISAuthoringClient.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/LUISAuthoringClient.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/LUISAuthoringClient.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/LUISAuthoringClient.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/LUISAuthoringManager.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/LUISAuthoringManager.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/LUISAuthoringManager.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/LUISAuthoringManager.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Models.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Models.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Models.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Models.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Patterns.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Patterns.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Patterns.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Patterns.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Permissions.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Permissions.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Permissions.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Permissions.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Trains.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Trains.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Trains.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Trains.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Versions.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Versions.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Versions.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/Versions.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/AppsImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/AppsImpl.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/AppsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/AppsImpl.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ExamplesImpl.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/FeaturesImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/FeaturesImpl.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/FeaturesImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/FeaturesImpl.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/LUISAuthoringClientImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/LUISAuthoringClientImpl.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/LUISAuthoringClientImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/LUISAuthoringClientImpl.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PatternsImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PatternsImpl.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PatternsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PatternsImpl.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PermissionsImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PermissionsImpl.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PermissionsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/PermissionsImpl.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/TrainsImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/TrainsImpl.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/TrainsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/TrainsImpl.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/VersionsImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/VersionsImpl.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/VersionsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/VersionsImpl.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/package-info.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddCompositeEntityChildOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddCompositeEntityChildOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddCompositeEntityChildOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddCompositeEntityChildOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddCustomPrebuiltDomainModelsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddCustomPrebuiltDomainModelsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddCustomPrebuiltDomainModelsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddCustomPrebuiltDomainModelsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddEntityOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddEntityOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddEntityOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddEntityOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddExplicitListItemOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddExplicitListItemOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddExplicitListItemOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddExplicitListItemOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddHierarchicalEntityChildOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddHierarchicalEntityChildOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddHierarchicalEntityChildOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddHierarchicalEntityChildOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddIntentOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddIntentOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddIntentOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddIntentOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddPermissionsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddPermissionsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddPermissionsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AddPermissionsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationInfoResponse.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationInfoResponse.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationInfoResponse.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationInfoResponse.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationPublishObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationPublishObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationPublishObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationPublishObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationSettingUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationSettingUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationSettingUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationSettingUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationSettings.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationSettings.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationSettings.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationSettings.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ApplicationUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AvailableCulture.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AvailableCulture.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AvailableCulture.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AvailableCulture.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AvailablePrebuiltEntityModel.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AvailablePrebuiltEntityModel.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AvailablePrebuiltEntityModel.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/AvailablePrebuiltEntityModel.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/BatchLabelExample.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/BatchLabelExample.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/BatchLabelExample.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/BatchLabelExample.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ChildEntity.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ChildEntity.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ChildEntity.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ChildEntity.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CloneOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CloneOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CloneOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CloneOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedList.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedList.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedList.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedList.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListEntityExtractor.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListEntityExtractor.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListEntityExtractor.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListEntityExtractor.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelPatchObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelPatchObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelPatchObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelPatchObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ClosedListModelUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CollaboratorsArray.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CollaboratorsArray.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CollaboratorsArray.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CollaboratorsArray.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeChildModelCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeChildModelCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeChildModelCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeChildModelCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeEntityExtractor.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeEntityExtractor.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeEntityExtractor.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeEntityExtractor.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeEntityModel.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeEntityModel.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeEntityModel.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CompositeEntityModel.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateClosedListEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateClosedListEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateClosedListEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateClosedListEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateCompositeEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateCompositeEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateCompositeEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateCompositeEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateCustomPrebuiltEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateCustomPrebuiltEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateCustomPrebuiltEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateCustomPrebuiltEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateHierarchicalEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateHierarchicalEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateHierarchicalEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateHierarchicalEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreatePatternAnyEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreatePatternAnyEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreatePatternAnyEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreatePatternAnyEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreatePrebuiltEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreatePrebuiltEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreatePrebuiltEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreatePrebuiltEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateRegexEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateRegexEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateRegexEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CreateRegexEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CustomPrebuiltModel.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CustomPrebuiltModel.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CustomPrebuiltModel.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/CustomPrebuiltModel.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/DeleteIntentOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/DeleteIntentOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/DeleteIntentOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/DeleteIntentOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/DeletePermissionsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/DeletePermissionsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/DeletePermissionsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/DeletePermissionsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EndpointInfo.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EndpointInfo.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EndpointInfo.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EndpointInfo.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EnqueueTrainingResponse.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EnqueueTrainingResponse.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EnqueueTrainingResponse.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EnqueueTrainingResponse.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntitiesSuggestionExample.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntitiesSuggestionExample.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntitiesSuggestionExample.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntitiesSuggestionExample.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityExtractor.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityExtractor.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityExtractor.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityExtractor.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityLabel.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityLabel.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityLabel.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityLabel.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityLabelObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityLabelObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityLabelObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityLabelObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityModelInfo.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityModelInfo.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityModelInfo.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityModelInfo.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityPrediction.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityPrediction.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityPrediction.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityPrediction.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRole.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRole.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRole.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRole.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRoleCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRoleCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRoleCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRoleCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRoleUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRoleUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRoleUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/EntityRoleUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ErrorResponse.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ErrorResponseException.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExampleLabelObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExampleLabelObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExampleLabelObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExampleLabelObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExamplesMethodOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExamplesMethodOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExamplesMethodOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExamplesMethodOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItem.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItem.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItem.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItem.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItemCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItemCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItemCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItemCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItemUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItemUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItemUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ExplicitListItemUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/FeatureInfoObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/FeatureInfoObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/FeatureInfoObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/FeatureInfoObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/FeaturesResponseObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/FeaturesResponseObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/FeaturesResponseObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/FeaturesResponseObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetEntitySuggestionsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetEntitySuggestionsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetEntitySuggestionsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetEntitySuggestionsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetIntentPatternsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetIntentPatternsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetIntentPatternsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetIntentPatternsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetIntentSuggestionsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetIntentSuggestionsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetIntentSuggestionsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetIntentSuggestionsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetPatternAnyEntityInfosOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetPatternAnyEntityInfosOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetPatternAnyEntityInfosOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetPatternAnyEntityInfosOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetPatternsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetPatternsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetPatternsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetPatternsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetRegexEntityInfosOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetRegexEntityInfosOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetRegexEntityInfosOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/GetRegexEntityInfosOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildEntity.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildEntity.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildEntity.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildEntity.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildModelCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildModelCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildModelCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildModelCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildModelUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildModelUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildModelUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalChildModelUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalEntityExtractor.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalEntityExtractor.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalEntityExtractor.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalEntityExtractor.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalEntityModel.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalEntityModel.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalEntityModel.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalEntityModel.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalModel.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalModel.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalModel.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/HierarchicalModel.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ImportMethodAppsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ImportMethodAppsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ImportMethodAppsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ImportMethodAppsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ImportMethodVersionsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ImportMethodVersionsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ImportMethodVersionsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ImportMethodVersionsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentClassifier.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentClassifier.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentClassifier.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentClassifier.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentPrediction.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentPrediction.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentPrediction.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentPrediction.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentsSuggestionExample.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentsSuggestionExample.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentsSuggestionExample.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/IntentsSuggestionExample.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONEntity.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONEntity.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONEntity.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONEntity.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONModelFeature.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONModelFeature.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONModelFeature.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONModelFeature.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONRegexFeature.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONRegexFeature.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONRegexFeature.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONRegexFeature.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONUtterance.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONUtterance.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONUtterance.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/JSONUtterance.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabelExampleResponse.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabelExampleResponse.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabelExampleResponse.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabelExampleResponse.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabelTextObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabelTextObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabelTextObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabelTextObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabeledUtterance.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabeledUtterance.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabeledUtterance.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LabeledUtterance.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListAppsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListAppsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListAppsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListAppsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListClosedListsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListClosedListsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListClosedListsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListClosedListsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListCompositeEntitiesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListCompositeEntitiesOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListCompositeEntitiesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListCompositeEntitiesOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListEntitiesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListEntitiesOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListEntitiesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListEntitiesOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListExamplesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListExamplesOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListExamplesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListExamplesOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListFeaturesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListFeaturesOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListFeaturesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListFeaturesOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListHierarchicalEntitiesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListHierarchicalEntitiesOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListHierarchicalEntitiesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListHierarchicalEntitiesOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListIntentsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListIntentsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListIntentsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListIntentsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListModelsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListModelsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListModelsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListModelsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListPhraseListsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListPhraseListsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListPhraseListsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListPhraseListsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListPrebuiltsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListPrebuiltsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListPrebuiltsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListPrebuiltsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListVersionsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListVersionsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListVersionsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ListVersionsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LuisApp.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LuisApp.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LuisApp.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/LuisApp.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelInfo.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelInfo.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelInfo.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelInfo.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelInfoResponse.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelInfoResponse.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelInfoResponse.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelInfoResponse.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelTrainingDetails.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelTrainingDetails.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelTrainingDetails.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelTrainingDetails.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelTrainingInfo.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelTrainingInfo.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelTrainingInfo.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelTrainingInfo.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ModelUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationError.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationError.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationError.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationError.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationStatus.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationStatus.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationStatus.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationStatus.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationStatusType.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationStatusType.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationStatusType.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/OperationStatusType.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatchClosedListOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatchClosedListOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatchClosedListOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatchClosedListOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAny.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAny.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAny.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAny.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyEntityExtractor.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyEntityExtractor.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyEntityExtractor.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyEntityExtractor.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyModelCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyModelCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyModelCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyModelCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyModelUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyModelUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyModelUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternAnyModelUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternFeatureInfo.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternFeatureInfo.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternFeatureInfo.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternFeatureInfo.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRule.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRule.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRule.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRule.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleInfo.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleInfo.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleInfo.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleInfo.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternRuleUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PatternUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PersonalAssistantsResponse.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PersonalAssistantsResponse.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PersonalAssistantsResponse.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PersonalAssistantsResponse.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraseListFeatureInfo.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraseListFeatureInfo.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraseListFeatureInfo.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraseListFeatureInfo.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraselistCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraselistCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraselistCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraselistCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraselistUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraselistUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraselistUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PhraselistUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomain.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomain.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomain.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomain.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainCreateBaseObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainCreateBaseObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainCreateBaseObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainCreateBaseObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainItem.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainItem.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainItem.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainItem.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainModelCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainModelCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainModelCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainModelCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltDomainObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltEntity.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltEntity.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltEntity.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltEntity.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltEntityExtractor.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltEntityExtractor.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltEntityExtractor.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PrebuiltEntityExtractor.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ProductionOrStagingEndpointInfo.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ProductionOrStagingEndpointInfo.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ProductionOrStagingEndpointInfo.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/ProductionOrStagingEndpointInfo.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PublishSettingUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PublishSettingUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PublishSettingUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PublishSettingUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PublishSettings.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PublishSettings.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PublishSettings.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/PublishSettings.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexEntity.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexEntity.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexEntity.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexEntity.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexEntityExtractor.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexEntityExtractor.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexEntityExtractor.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexEntityExtractor.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexModelCreateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexModelCreateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexModelCreateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexModelCreateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexModelUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexModelUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexModelUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/RegexModelUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/SubClosedList.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/SubClosedList.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/SubClosedList.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/SubClosedList.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/SubClosedListResponse.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/SubClosedListResponse.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/SubClosedListResponse.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/SubClosedListResponse.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/TaskUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/TaskUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/TaskUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/TaskUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/TrainingStatus.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/TrainingStatus.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/TrainingStatus.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/TrainingStatus.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateClosedListEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateClosedListEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateClosedListEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateClosedListEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateCompositeEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateCompositeEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateCompositeEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateCompositeEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateCustomPrebuiltEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateCustomPrebuiltEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateCustomPrebuiltEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateCustomPrebuiltEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateEntityOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateEntityOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateEntityOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateEntityOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateExplicitListItemOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateExplicitListItemOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateExplicitListItemOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateExplicitListItemOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateHierarchicalEntityChildOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateHierarchicalEntityChildOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateHierarchicalEntityChildOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateHierarchicalEntityChildOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateHierarchicalEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateHierarchicalEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateHierarchicalEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateHierarchicalEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateIntentOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateIntentOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateIntentOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateIntentOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePatternAnyEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePatternAnyEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePatternAnyEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePatternAnyEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePermissionsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePermissionsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePermissionsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePermissionsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePhraseListOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePhraseListOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePhraseListOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePhraseListOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePrebuiltEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePrebuiltEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePrebuiltEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdatePrebuiltEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateRegexEntityRoleOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateRegexEntityRoleOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateRegexEntityRoleOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateRegexEntityRoleOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateSettingsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateSettingsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateSettingsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateSettingsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateVersionsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateVersionsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateVersionsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UpdateVersionsOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UserAccessList.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UserAccessList.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UserAccessList.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UserAccessList.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UserCollaborator.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UserCollaborator.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UserCollaborator.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/UserCollaborator.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/VersionInfo.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/VersionInfo.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/VersionInfo.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/VersionInfo.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/WordListBaseUpdateObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/WordListBaseUpdateObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/WordListBaseUpdateObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/WordListBaseUpdateObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/WordListObject.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/WordListObject.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/WordListObject.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/WordListObject.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/models/package-info.java diff --git a/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/package-info.java b/sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/package-info.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-luis-authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/package-info.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/pom.xml b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/pom.xml old mode 100755 new mode 100644 similarity index 98% rename from cognitiveservices/data-plane/language/luis/runtime/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/pom.xml index e8beb81425867..5975fc3328ad7 --- a/cognitiveservices/data-plane/language/luis/runtime/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../../pom.xml + ../pom.xml azure-cognitiveservices-luis-runtime 1.0.2-beta diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/EndpointAPI.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/EndpointAPI.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/EndpointAPI.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/EndpointAPI.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/LuisRuntimeAPI.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/LuisRuntimeAPI.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/LuisRuntimeAPI.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/LuisRuntimeAPI.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/LuisRuntimeManager.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/LuisRuntimeManager.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/LuisRuntimeManager.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/LuisRuntimeManager.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/Predictions.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/Predictions.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/Predictions.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/Predictions.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/LuisRuntimeAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/LuisRuntimeAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/LuisRuntimeAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/LuisRuntimeAPIImpl.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/PredictionsImpl.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/PredictionsImpl.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/PredictionsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/PredictionsImpl.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/implementation/package-info.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/APIError.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/APIError.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/APIError.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/APIError.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/APIErrorException.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/APIErrorException.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/APIErrorException.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/APIErrorException.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/AzureRegions.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/AzureRegions.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/AzureRegions.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/AzureRegions.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/CompositeChildModel.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/CompositeChildModel.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/CompositeChildModel.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/CompositeChildModel.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/CompositeEntityModel.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/CompositeEntityModel.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/CompositeEntityModel.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/CompositeEntityModel.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityModel.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityModel.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityModel.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityModel.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityWithResolution.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityWithResolution.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityWithResolution.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityWithResolution.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityWithScore.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityWithScore.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityWithScore.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/EntityWithScore.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/IntentModel.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/IntentModel.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/IntentModel.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/IntentModel.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/LuisResult.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/LuisResult.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/LuisResult.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/LuisResult.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/ResolveOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/ResolveOptionalParameter.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/ResolveOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/ResolveOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/Sentiment.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/Sentiment.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/Sentiment.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/Sentiment.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/models/package-info.java diff --git a/cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/package-info.java b/sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/luis/runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-luis-runtime/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/runtime/package-info.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/pom.xml b/sdk/cognitiveservices/ms-azure-cs-newssearch/pom.xml similarity index 98% rename from cognitiveservices/data-plane/search/bingnewssearch/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-newssearch/pom.xml index 97d457b0420a1..e876be271200c 100644 --- a/cognitiveservices/data-plane/search/bingnewssearch/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-newssearch/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-newssearch 1.0.2 diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNews.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNews.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNews.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNews.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNewsSearchAPI.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNewsSearchAPI.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNewsSearchAPI.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNewsSearchAPI.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNewsSearchManager.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNewsSearchManager.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNewsSearchManager.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/BingNewsSearchManager.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsImpl.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsImpl.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsSearchAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsSearchAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsSearchAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/BingNewsSearchAPIImpl.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/implementation/package-info.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Answer.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Answer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Answer.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Answer.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Article.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Article.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Article.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Article.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/CategoryOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/CategoryOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/CategoryOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/CategoryOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/CreativeWork.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/CreativeWork.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/CreativeWork.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/CreativeWork.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Error.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorCode.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorCode.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorCode.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorResponseException.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorSubCode.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorSubCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorSubCode.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ErrorSubCode.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Freshness.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Freshness.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Freshness.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Freshness.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Identifiable.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Identifiable.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Identifiable.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Identifiable.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ImageObject.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ImageObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ImageObject.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ImageObject.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/MediaObject.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/MediaObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/MediaObject.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/MediaObject.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsArticle.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsArticle.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsArticle.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsArticle.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsModel.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsModel.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsModel.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsModel.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsTopic.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsTopic.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsTopic.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/NewsTopic.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Organization.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Organization.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Organization.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Organization.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Query.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Query.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Query.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Query.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Response.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Response.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Response.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Response.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ResponseBase.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ResponseBase.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ResponseBase.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/ResponseBase.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SafeSearch.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SafeSearch.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SafeSearch.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SafeSearch.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SearchOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SearchOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SearchOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SearchOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SearchResultsAnswer.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SearchResultsAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SearchResultsAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/SearchResultsAnswer.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TextFormat.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TextFormat.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TextFormat.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TextFormat.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Thing.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Thing.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Thing.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/Thing.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TrendingOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TrendingOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TrendingOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TrendingOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TrendingTopics.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TrendingTopics.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TrendingTopics.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/TrendingTopics.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/VideoObject.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/VideoObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/VideoObject.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/VideoObject.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/models/package-info.java diff --git a/cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/package-info.java b/sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingnewssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-newssearch/src/main/java/com/microsoft/azure/cognitiveservices/search/newssearch/package-info.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/pom.xml b/sdk/cognitiveservices/ms-azure-cs-spellcheck/pom.xml old mode 100755 new mode 100644 similarity index 98% rename from cognitiveservices/data-plane/language/bingspellcheck/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/pom.xml index a175bc04e384f..3d2478a24caee --- a/cognitiveservices/data-plane/language/bingspellcheck/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-spellcheck/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml 1.0.2 azure-cognitiveservices-spellcheck diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckAPI.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckAPI.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckAPI.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckAPI.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckManager.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckManager.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckManager.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckManager.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckOperations.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckOperations.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckOperations.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/BingSpellCheckOperations.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckAPIImpl.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckAPIImpl.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckOperationsImpl.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckOperationsImpl.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckOperationsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/BingSpellCheckOperationsImpl.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/implementation/package-info.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ActionType.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ActionType.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ActionType.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ActionType.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Answer.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Answer.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Answer.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Answer.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Error.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Error.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorCode.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorCode.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorCode.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorCode.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorResponse.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorResponseException.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorSubCode.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorSubCode.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorSubCode.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorSubCode.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorType.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorType.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorType.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ErrorType.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Identifiable.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Identifiable.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Identifiable.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Identifiable.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Response.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Response.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Response.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/Response.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ResponseBase.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ResponseBase.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ResponseBase.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/ResponseBase.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellCheck.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellCheck.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellCheck.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellCheck.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellCheckerOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellCheckerOptionalParameter.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellCheckerOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellCheckerOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellingFlaggedToken.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellingFlaggedToken.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellingFlaggedToken.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellingFlaggedToken.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellingTokenSuggestion.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellingTokenSuggestion.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellingTokenSuggestion.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/SpellingTokenSuggestion.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/models/package-info.java diff --git a/cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/package-info.java b/sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/bingspellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-spellcheck/src/main/java/com/microsoft/azure/cognitiveservices/language/spellcheck/package-info.java diff --git a/cognitiveservices/data-plane/language/textanalytics/pom.xml b/sdk/cognitiveservices/ms-azure-cs-textanalytics/pom.xml old mode 100755 new mode 100644 similarity index 98% rename from cognitiveservices/data-plane/language/textanalytics/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/pom.xml index 3f19296b15696..ed884313899dc --- a/cognitiveservices/data-plane/language/textanalytics/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-textanalytics/pom.xml @@ -11,7 +11,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-textanalytics 1.0.2-beta diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalytics.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalytics.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalytics.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalytics.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsAPI.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsAPI.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsAPI.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsAPI.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsManager.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsManager.java similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsManager.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/TextAnalyticsManager.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsAPIImpl.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsAPIImpl.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsImpl.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsImpl.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsImpl.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/TextAnalyticsImpl.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/implementation/package-info.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/AzureRegions.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/AzureRegions.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/AzureRegions.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/AzureRegions.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/BatchInput.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/BatchInput.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/BatchInput.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/BatchInput.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/DetectLanguageOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/DetectLanguageOptionalParameter.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/DetectLanguageOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/DetectLanguageOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/DetectedLanguage.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/DetectedLanguage.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/DetectedLanguage.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/DetectedLanguage.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesBatchResult.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesBatchResult.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesBatchResult.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesBatchResult.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesBatchResultItem.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesBatchResultItem.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesBatchResultItem.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesBatchResultItem.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesOptionalParameter.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntitiesOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntityRecord.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntityRecord.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntityRecord.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/EntityRecord.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorRecord.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorRecord.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorRecord.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorRecord.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorResponse.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorResponseException.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/Input.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/Input.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/Input.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/Input.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/InternalError.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/InternalError.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/InternalError.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/InternalError.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhraseBatchResult.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhraseBatchResult.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhraseBatchResult.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhraseBatchResult.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhraseBatchResultItem.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhraseBatchResultItem.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhraseBatchResultItem.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhraseBatchResultItem.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhrasesOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhrasesOptionalParameter.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhrasesOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/KeyPhrasesOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/LanguageBatchResult.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/LanguageBatchResult.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/LanguageBatchResult.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/LanguageBatchResult.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/LanguageBatchResultItem.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/LanguageBatchResultItem.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/LanguageBatchResultItem.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/LanguageBatchResultItem.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MatchRecord.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MatchRecord.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MatchRecord.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MatchRecord.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MultiLanguageBatchInput.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MultiLanguageBatchInput.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MultiLanguageBatchInput.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MultiLanguageBatchInput.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MultiLanguageInput.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MultiLanguageInput.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MultiLanguageInput.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/MultiLanguageInput.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentBatchResult.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentBatchResult.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentBatchResult.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentBatchResult.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentBatchResultItem.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentBatchResultItem.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentBatchResultItem.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentBatchResultItem.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentOptionalParameter.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/SentimentOptionalParameter.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/models/package-info.java diff --git a/cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/package-info.java b/sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from cognitiveservices/data-plane/language/textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-textanalytics/src/main/java/com/microsoft/azure/cognitiveservices/language/textanalytics/package-info.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/pom.xml b/sdk/cognitiveservices/ms-azure-cs-videosearch/pom.xml similarity index 98% rename from cognitiveservices/data-plane/search/bingvideosearch/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-videosearch/pom.xml index 149edcf09ea97..665291eabc7f1 100644 --- a/cognitiveservices/data-plane/search/bingvideosearch/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-videosearch/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-videosearch 1.0.2 diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideoSearchAPI.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideoSearchAPI.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideoSearchAPI.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideoSearchAPI.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideoSearchManager.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideoSearchManager.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideoSearchManager.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideoSearchManager.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideos.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideos.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideos.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/BingVideos.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideoSearchAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideoSearchAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideoSearchAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideoSearchAPIImpl.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/BingVideosImpl.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/implementation/package-info.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Answer.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Answer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Answer.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Answer.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/CreativeWork.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/CreativeWork.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/CreativeWork.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/CreativeWork.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/DetailsOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/DetailsOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/DetailsOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/DetailsOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Error.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorCode.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorCode.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorCode.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorResponseException.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorSubCode.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorSubCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorSubCode.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ErrorSubCode.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Freshness.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Freshness.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Freshness.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Freshness.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Identifiable.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Identifiable.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Identifiable.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Identifiable.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ImageObject.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ImageObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ImageObject.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ImageObject.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/MediaObject.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/MediaObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/MediaObject.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/MediaObject.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/PivotSuggestions.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/PivotSuggestions.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/PivotSuggestions.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/PivotSuggestions.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Query.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Query.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Query.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Query.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/QueryContext.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/QueryContext.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/QueryContext.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/QueryContext.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Response.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Response.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Response.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Response.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ResponseBase.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ResponseBase.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ResponseBase.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/ResponseBase.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SafeSearch.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SafeSearch.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SafeSearch.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SafeSearch.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SearchOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SearchOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SearchOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SearchOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SearchResultsAnswer.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SearchResultsAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SearchResultsAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/SearchResultsAnswer.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TextFormat.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TextFormat.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TextFormat.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TextFormat.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Thing.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Thing.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Thing.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/Thing.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideos.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideos.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideos.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideos.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosCategory.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosCategory.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosCategory.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosCategory.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosSubcategory.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosSubcategory.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosSubcategory.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosSubcategory.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosTile.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosTile.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosTile.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/TrendingVideosTile.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoDetails.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoDetails.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoDetails.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoDetails.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoInsightModule.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoInsightModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoInsightModule.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoInsightModule.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoLength.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoLength.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoLength.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoLength.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoObject.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoObject.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoObject.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoPricing.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoPricing.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoPricing.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoPricing.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoQueryScenario.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoQueryScenario.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoQueryScenario.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoQueryScenario.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoResolution.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoResolution.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoResolution.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideoResolution.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideosModel.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideosModel.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideosModel.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideosModel.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideosModule.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideosModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideosModule.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/VideosModule.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/models/package-info.java diff --git a/cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/package-info.java b/sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvideosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-videosearch/src/main/java/com/microsoft/azure/cognitiveservices/search/videosearch/package-info.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/pom.xml b/sdk/cognitiveservices/ms-azure-cs-visualsearch/pom.xml similarity index 98% rename from cognitiveservices/data-plane/search/bingvisualsearch/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/pom.xml index bf6ba0b59e493..1ba947143e7ab 100644 --- a/cognitiveservices/data-plane/search/bingvisualsearch/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-visualsearch/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-visualsearch 1.0.2-beta diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingImages.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingImages.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingImages.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingImages.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingVisualSearchAPI.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingVisualSearchAPI.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingVisualSearchAPI.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingVisualSearchAPI.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingVisualSearchManager.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingVisualSearchManager.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingVisualSearchManager.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/BingVisualSearchManager.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingImagesImpl.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingImagesImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingImagesImpl.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingImagesImpl.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingVisualSearchAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingVisualSearchAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingVisualSearchAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/BingVisualSearchAPIImpl.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/implementation/package-info.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Action.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Action.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Action.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Action.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/AggregateOffer.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/AggregateOffer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/AggregateOffer.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/AggregateOffer.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/AggregateRating.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/AggregateRating.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/AggregateRating.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/AggregateRating.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/CreativeWork.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/CreativeWork.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/CreativeWork.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/CreativeWork.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/CropArea.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/CropArea.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/CropArea.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/CropArea.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Currency.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Currency.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Currency.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Currency.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Error.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorCode.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorCode.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorCode.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorResponseException.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorSubCode.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorSubCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorSubCode.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ErrorSubCode.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Filters.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Filters.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Filters.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Filters.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Identifiable.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Identifiable.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Identifiable.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Identifiable.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageAction.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageAction.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageAction.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageAction.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageEntityAction.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageEntityAction.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageEntityAction.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageEntityAction.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageInfo.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageInfo.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageInfo.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageInfo.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageKnowledge.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageKnowledge.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageKnowledge.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageKnowledge.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageModuleAction.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageModuleAction.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageModuleAction.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageModuleAction.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageObject.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageObject.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageObject.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageRecipesAction.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageRecipesAction.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageRecipesAction.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageRecipesAction.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageRelatedSearchesAction.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageRelatedSearchesAction.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageRelatedSearchesAction.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageRelatedSearchesAction.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageShoppingSourcesAction.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageShoppingSourcesAction.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageShoppingSourcesAction.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageShoppingSourcesAction.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageTag.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageTag.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageTag.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageTag.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageTagRegion.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageTagRegion.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageTagRegion.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImageTagRegion.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImagesImageMetadata.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImagesImageMetadata.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImagesImageMetadata.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImagesImageMetadata.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImagesModule.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImagesModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImagesModule.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ImagesModule.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Intangible.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Intangible.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Intangible.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Intangible.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ItemAvailability.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ItemAvailability.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ItemAvailability.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ItemAvailability.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/KnowledgeRequest.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/KnowledgeRequest.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/KnowledgeRequest.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/KnowledgeRequest.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/MediaObject.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/MediaObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/MediaObject.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/MediaObject.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/NormalizedQuadrilateral.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/NormalizedQuadrilateral.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/NormalizedQuadrilateral.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/NormalizedQuadrilateral.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Offer.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Offer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Offer.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Offer.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Organization.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Organization.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Organization.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Organization.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Person.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Person.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Person.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Person.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Point2D.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Point2D.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Point2D.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Point2D.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/PropertiesItem.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/PropertiesItem.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/PropertiesItem.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/PropertiesItem.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Query.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Query.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Query.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Query.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Rating.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Rating.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Rating.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Rating.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Recipe.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Recipe.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Recipe.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Recipe.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/RecipesModule.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/RecipesModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/RecipesModule.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/RecipesModule.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/RelatedSearchesModule.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/RelatedSearchesModule.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/RelatedSearchesModule.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/RelatedSearchesModule.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Response.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Response.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Response.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Response.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ResponseBase.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ResponseBase.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ResponseBase.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/ResponseBase.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/StructuredValue.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/StructuredValue.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/StructuredValue.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/StructuredValue.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Thing.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Thing.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Thing.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/Thing.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/VisualSearchOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/VisualSearchOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/VisualSearchOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/VisualSearchOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/VisualSearchRequest.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/VisualSearchRequest.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/VisualSearchRequest.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/VisualSearchRequest.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/models/package-info.java diff --git a/cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/package-info.java b/sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingvisualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-visualsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/visualsearch/package-info.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/pom.xml b/sdk/cognitiveservices/ms-azure-cs-websearch/pom.xml similarity index 98% rename from cognitiveservices/data-plane/search/bingwebsearch/pom.xml rename to sdk/cognitiveservices/ms-azure-cs-websearch/pom.xml index 82b74ceb2e931..1fad4bab508b9 100644 --- a/cognitiveservices/data-plane/search/bingwebsearch/pom.xml +++ b/sdk/cognitiveservices/ms-azure-cs-websearch/pom.xml @@ -9,7 +9,7 @@ com.microsoft.azure.cognitiveservices azure-cognitiveservices-parent 1.0.2 - ../../pom.xml + ../pom.xml azure-cognitiveservices-websearch 1.0.2 diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearch.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearch.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearch.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearch.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearchAPI.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearchAPI.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearchAPI.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearchAPI.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearchManager.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearchManager.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearchManager.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/BingWebSearchManager.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchAPIImpl.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchAPIImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchAPIImpl.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchAPIImpl.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchImpl.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchImpl.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchImpl.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/BingWebSearchImpl.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/package-info.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/implementation/package-info.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Answer.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Answer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Answer.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Answer.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/AnswerType.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/AnswerType.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/AnswerType.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/AnswerType.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Article.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Article.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Article.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Article.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Computation.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Computation.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Computation.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Computation.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/CreativeWork.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/CreativeWork.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/CreativeWork.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/CreativeWork.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Error.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Error.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Error.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Error.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorCode.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorCode.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorCode.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorResponse.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorResponse.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorResponse.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorResponseException.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorResponseException.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorResponseException.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorResponseException.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorSubCode.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorSubCode.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorSubCode.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ErrorSubCode.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Freshness.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Freshness.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Freshness.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Freshness.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Identifiable.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Identifiable.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Identifiable.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Identifiable.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ImageObject.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ImageObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ImageObject.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ImageObject.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Images.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Images.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Images.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Images.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Intangible.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Intangible.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Intangible.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Intangible.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/MediaObject.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/MediaObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/MediaObject.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/MediaObject.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/News.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/News.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/News.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/News.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/NewsArticle.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/NewsArticle.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/NewsArticle.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/NewsArticle.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Places.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Places.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Places.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Places.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Query.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Query.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Query.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Query.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/QueryContext.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/QueryContext.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/QueryContext.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/QueryContext.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingGroup.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingGroup.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingGroup.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingGroup.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingItem.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingItem.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingItem.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingItem.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingResponse.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingResponse.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RankingRankingResponse.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RelatedSearchesRelatedSearchAnswer.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RelatedSearchesRelatedSearchAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RelatedSearchesRelatedSearchAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/RelatedSearchesRelatedSearchAnswer.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Response.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Response.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Response.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Response.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ResponseBase.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ResponseBase.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ResponseBase.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/ResponseBase.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SafeSearch.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SafeSearch.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SafeSearch.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SafeSearch.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchOptionalParameter.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchOptionalParameter.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchOptionalParameter.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchOptionalParameter.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchResponse.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchResponse.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchResponse.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchResponse.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchResultsAnswer.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchResultsAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchResultsAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SearchResultsAnswer.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SpellSuggestions.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SpellSuggestions.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SpellSuggestions.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/SpellSuggestions.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/StructuredValue.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/StructuredValue.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/StructuredValue.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/StructuredValue.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TextFormat.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TextFormat.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TextFormat.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TextFormat.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Thing.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Thing.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Thing.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Thing.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TimeZone.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TimeZone.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TimeZone.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TimeZone.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TimeZoneTimeZoneInformation.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TimeZoneTimeZoneInformation.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TimeZoneTimeZoneInformation.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/TimeZoneTimeZoneInformation.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/VideoObject.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/VideoObject.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/VideoObject.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/VideoObject.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Videos.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Videos.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Videos.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/Videos.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebMetaTag.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebMetaTag.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebMetaTag.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebMetaTag.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebPage.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebPage.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebPage.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebPage.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebWebAnswer.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebWebAnswer.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebWebAnswer.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebWebAnswer.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebWebGrouping.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebWebGrouping.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebWebGrouping.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/WebWebGrouping.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/package-info.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/models/package-info.java diff --git a/cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/package-info.java b/sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/package-info.java similarity index 100% rename from cognitiveservices/data-plane/search/bingwebsearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/package-info.java rename to sdk/cognitiveservices/ms-azure-cs-websearch/src/main/java/com/microsoft/azure/cognitiveservices/search/websearch/package-info.java diff --git a/sdk/cognitiveservices/pom.service.xml b/sdk/cognitiveservices/pom.service.xml index b05ef1bce0107..a65c5aa0bb467 100644 --- a/sdk/cognitiveservices/pom.service.xml +++ b/sdk/cognitiveservices/pom.service.xml @@ -9,6 +9,23 @@ pom 1.0.0 - + ms-azure-cs-spellcheck + ms-azure-cs-textanalytics + ms-azure-cs-luis-runtime + ms-azure-cs-luis-authoring + ms-azure-cs-autosuggest + ms-azure-cs-customimagesearch + ms-azure-cs-customsearch + ms-azure-cs-entitysearch + ms-azure-cs-imagesearch + ms-azure-cs-newssearch + ms-azure-cs-videosearch + ms-azure-cs-visualsearch + ms-azure-cs-websearch + ms-azure-cs-computervision + ms-azure-cs-contentmoderator + ms-azure-cs-customvision-prediction + ms-azure-cs-customvision-training + ms-azure-cs-faceapi diff --git a/cognitiveservices/data-plane/pom.xml b/sdk/cognitiveservices/pom.xml old mode 100755 new mode 100644 similarity index 92% rename from cognitiveservices/data-plane/pom.xml rename to sdk/cognitiveservices/pom.xml index 2e2e36b91d2c9..b563ba399f475 --- a/cognitiveservices/data-plane/pom.xml +++ b/sdk/cognitiveservices/pom.xml @@ -296,23 +296,23 @@ - ./language/bingspellcheck - ./language/luis/authoring - ./language/luis/runtime - ./language/textanalytics - ./search/bingautosuggest - ./search/bingcustomimagesearch - ./search/bingcustomsearch - ./search/bingentitysearch - ./search/bingimagesearch - ./search/bingnewssearch - ./search/bingvideosearch - ./search/bingvisualsearch - ./search/bingwebsearch - ./vision/computervision - ./vision/contentmoderator - ./vision/customvision/prediction - ./vision/customvision/training - ./vision/faceapi + ms-azure-cs-spellcheck + ms-azure-cs-luis-authoring + ms-azure-cs-luis-runtime + ms-azure-cs-textanalytics + ms-azure-cs-autosuggest + ms-azure-cs-customimagesearch + ms-azure-cs-customsearch + ms-azure-cs-entitysearch + ms-azure-cs-imagesearch + ms-azure-cs-newssearch + ms-azure-cs-videosearch + ms-azure-cs-visualsearch + ms-azure-cs-websearch + ms-azure-cs-computervision + ms-azure-cs-contentmoderator + ms-azure-cs-customvision-prediction + ms-azure-cs-customvision-training + ms-azure-cs-faceapi \ No newline at end of file From 83152db5da7037bf5bb7b9cb807aeb78cf17d04d Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Fri, 12 Jul 2019 10:35:38 -0700 Subject: [PATCH 75/85] Move /eventgrid/data-plane to /sdk/eventgrid/microsoft-azure-eventgrid (#4087) * Moved to sdk folder. --- eng/.docsettings.yml | 2 +- .../eventgrid/microsoft-azure-eventgrid}/README.md | 0 .../eventgrid/microsoft-azure-eventgrid}/pom.xml | 7 ++++++- .../azure/eventgrid/DomainCredentials.java | 0 .../microsoft/azure/eventgrid/EventGridClient.java | 0 .../azure/eventgrid/TopicCredentials.java | 0 .../customization/EventGridSubscriber.java | 0 .../customization/SystemEventTypeMappings.java | 0 .../eventgrid/customization/SystemEventTypes.java | 0 .../implementation/EventGridClientImpl.java | 0 .../eventgrid/implementation/package-info.java | 0 .../AppConfigurationKeyValueDeletedEventData.java | 0 .../AppConfigurationKeyValueModifiedEventData.java | 0 .../models/ContainerRegistryArtifactEventData.java | 0 .../ContainerRegistryArtifactEventTarget.java | 0 .../ContainerRegistryChartDeletedEventData.java | 0 .../ContainerRegistryChartPushedEventData.java | 0 .../models/ContainerRegistryEventActor.java | 0 .../models/ContainerRegistryEventData.java | 0 .../models/ContainerRegistryEventRequest.java | 0 .../models/ContainerRegistryEventSource.java | 0 .../models/ContainerRegistryEventTarget.java | 0 .../ContainerRegistryImageDeletedEventData.java | 0 .../ContainerRegistryImagePushedEventData.java | 0 .../models/DeviceConnectionStateEventInfo.java | 0 .../DeviceConnectionStateEventProperties.java | 0 .../models/DeviceLifeCycleEventProperties.java | 0 .../models/DeviceTelemetryEventProperties.java | 0 .../azure/eventgrid/models/DeviceTwinInfo.java | 0 .../eventgrid/models/DeviceTwinInfoProperties.java | 0 .../models/DeviceTwinInfoX509Thumbprint.java | 0 .../azure/eventgrid/models/DeviceTwinMetadata.java | 0 .../eventgrid/models/DeviceTwinProperties.java | 0 .../azure/eventgrid/models/EventGridEvent.java | 0 .../EventHubCaptureFileCreatedEventData.java | 0 .../models/IotHubDeviceConnectedEventData.java | 0 .../models/IotHubDeviceCreatedEventData.java | 0 .../models/IotHubDeviceDeletedEventData.java | 0 .../models/IotHubDeviceDisconnectedEventData.java | 0 .../models/IotHubDeviceTelemetryEventData.java | 0 .../microsoft/azure/eventgrid/models/JobState.java | 0 .../models/MapsGeofenceEnteredEventData.java | 0 .../models/MapsGeofenceEventProperties.java | 0 .../models/MapsGeofenceExitedEventData.java | 0 .../eventgrid/models/MapsGeofenceGeometry.java | 0 .../models/MapsGeofenceResultEventData.java | 0 .../models/MediaJobCanceledEventData.java | 0 .../models/MediaJobCancelingEventData.java | 0 .../azure/eventgrid/models/MediaJobError.java | 0 .../eventgrid/models/MediaJobErrorCategory.java | 0 .../azure/eventgrid/models/MediaJobErrorCode.java | 0 .../eventgrid/models/MediaJobErrorDetail.java | 0 .../eventgrid/models/MediaJobErroredEventData.java | 0 .../models/MediaJobFinishedEventData.java | 0 .../azure/eventgrid/models/MediaJobOutput.java | 0 .../eventgrid/models/MediaJobOutputAsset.java | 0 .../models/MediaJobOutputCanceledEventData.java | 0 .../models/MediaJobOutputCancelingEventData.java | 0 .../models/MediaJobOutputErroredEventData.java | 0 .../models/MediaJobOutputFinishedEventData.java | 0 .../models/MediaJobOutputProcessingEventData.java | 0 .../models/MediaJobOutputProgressEventData.java | 0 .../models/MediaJobOutputScheduledEventData.java | 0 .../models/MediaJobOutputStateChangeEventData.java | 0 .../models/MediaJobProcessingEventData.java | 0 .../azure/eventgrid/models/MediaJobRetry.java | 0 .../models/MediaJobScheduledEventData.java | 0 .../azure/eventgrid/models/MediaJobState.java | 0 .../models/MediaJobStateChangeEventData.java | 0 .../MediaLiveEventConnectionRejectedEventData.java | 0 .../MediaLiveEventEncoderConnectedEventData.java | 0 ...MediaLiveEventEncoderDisconnectedEventData.java | 0 ...LiveEventIncomingDataChunkDroppedEventData.java | 0 ...iaLiveEventIncomingStreamReceivedEventData.java | 0 ...LiveEventIncomingStreamsOutOfSyncEventData.java | 0 ...ventIncomingVideoStreamsOutOfSyncEventData.java | 0 .../MediaLiveEventIngestHeartbeatEventData.java | 0 ...veEventTrackDiscontinuityDetectedEventData.java | 0 .../eventgrid/models/ResourceActionCancelData.java | 0 .../models/ResourceActionFailureData.java | 0 .../models/ResourceActionSuccessData.java | 0 .../eventgrid/models/ResourceDeleteCancelData.java | 0 .../models/ResourceDeleteFailureData.java | 0 .../models/ResourceDeleteSuccessData.java | 0 .../eventgrid/models/ResourceWriteCancelData.java | 0 .../eventgrid/models/ResourceWriteFailureData.java | 0 .../eventgrid/models/ResourceWriteSuccessData.java | 0 ...eMessagesAvailableWithNoListenersEventData.java | 0 ...rMessagesAvailableWithNoListenersEventData.java | 0 .../models/StorageBlobCreatedEventData.java | 0 .../models/StorageBlobDeletedEventData.java | 0 .../models/SubscriptionDeletedEventData.java | 0 .../models/SubscriptionValidationEventData.java | 0 .../models/SubscriptionValidationResponse.java | 0 .../azure/eventgrid/models/package-info.java | 0 .../microsoft/azure/eventgrid/package-info.java | 0 .../microsoft/azure/eventgrid/EventGridTests.java | 2 ++ .../customization/CustomizationTests.java | 4 ++-- .../models/ContosoItemReceivedEventData.java | 0 .../models/ContosoItemSentEventData.java | 0 .../customization/models/DroneShippingInfo.java | 0 .../customization/models/RocketShippingInfo.java | 0 .../customization/models/ShippingInfo.java | 0 .../AppConfigurationKeyValueDeleted.json | 0 .../AppConfigurationKeyValueModified.json | 0 .../ContainerRegistryChartDeletedEvent.json | 0 .../ContainerRegistryChartPushedEvent.json | 0 .../ContainerRegistryImageDeletedEvent.json | 0 .../ContainerRegistryImagePushedEvent.json | 0 .../customization/CustomEventWithArrayData.json | 0 .../customization/CustomEventWithBooleanData.json | 0 .../CustomEventWithPolymorphicData.json | 0 .../customization/CustomEventWithStringData.json | 0 .../test/resources/customization/CustomEvents.json | 0 .../EventGridSubscriptionDeletedEvent.json | 0 .../EventGridSubscriptionValidationEvent.json | 0 .../EventHubCaptureFileCreatedEvent.json | 0 .../customization/IoTHubDeviceConnectedEvent.json | 0 .../customization/IoTHubDeviceCreatedEvent.json | 0 .../customization/IoTHubDeviceDeletedEvent.json | 0 .../IoTHubDeviceDisconnectedEvent.json | 0 .../customization/IoTHubDeviceTelemetryEvent.json | 0 .../customization/MapsGeofenceEnteredEvent.json | 0 .../customization/MapsGeofenceExitedEvent.json | 0 .../customization/MapsGeofenceResultEvent.json | 0 .../customization/MediaJobCanceledEvent.json | 0 .../customization/MediaJobCancelingEvent.json | 0 .../customization/MediaJobErroredEvent.json | 0 .../customization/MediaJobFinishedEvent.json | 0 .../customization/MediaJobOutputCanceledEvent.json | 0 .../MediaJobOutputCancelingEvent.json | 0 .../customization/MediaJobOutputErroredEvent.json | 0 .../customization/MediaJobOutputFinishedEvent.json | 0 .../MediaJobOutputProcessingEvent.json | 0 .../customization/MediaJobOutputProgressEvent.json | 0 .../MediaJobOutputScheduledEvent.json | 0 .../MediaJobOutputStateChangeEvent.json | 0 .../customization/MediaJobProcessingEvent.json | 0 .../customization/MediaJobScheduledEvent.json | 0 .../customization/MediaJobStateChangeEvent.json | 0 .../MediaLiveEventConnectionRejectedEvent.json | 0 .../MediaLiveEventEncoderConnectedEvent.json | 0 .../MediaLiveEventEncoderDisconnectedEvent.json | 0 ...ediaLiveEventIncomingDataChunkDroppedEvent.json | 0 .../MediaLiveEventIncomingStreamReceivedEvent.json | 0 ...ediaLiveEventIncomingStreamsOutOfSyncEvent.json | 0 ...iveEventIncomingVideoStreamsOutOfSyncEvent.json | 0 .../MediaLiveEventIngestHeartbeatEvent.json | 0 ...iaLiveEventTrackDiscontinuityDetectedEvent.json | 0 .../MediaServicesJobStateChangedEvent.json | 0 .../customization/MultipleEventsInSameBatch.json | 0 .../customization/ResourceActionCancelEvent.json | 0 .../customization/ResourceActionFailureEvent.json | 0 .../customization/ResourceActionSuccessEvent.json | 0 .../customization/ResourceDeleteCancelEvent.json | 0 .../customization/ResourceDeleteFailureEvent.json | 0 .../customization/ResourceDeleteSuccessEvent.json | 0 .../customization/ResourceWriteCancelEvent.json | 0 .../customization/ResourceWriteFailureEvent.json | 0 .../customization/ResourceWriteSuccessEvent.json | 0 ...ctiveMessagesAvailableWithNoListenersEvent.json | 0 ...etterMessagesAvailableWithNoListenersEvent.json | 0 .../customization/StorageBlobCreatedEvent.json | 0 .../customization/StorageBlobDeletedEvent.json | 0 .../StorageBlobDeletedEventWithExtraProperty.json | 0 sdk/eventgrid/pom.service.xml | 14 ++++++++++++++ 166 files changed, 25 insertions(+), 4 deletions(-) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/README.md (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/pom.xml (96%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/DomainCredentials.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/EventGridClient.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/TopicCredentials.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/customization/EventGridSubscriber.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/customization/SystemEventTypeMappings.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/customization/SystemEventTypes.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/implementation/EventGridClientImpl.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/implementation/package-info.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/AppConfigurationKeyValueDeletedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/AppConfigurationKeyValueModifiedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryArtifactEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryArtifactEventTarget.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryChartDeletedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryChartPushedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventActor.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventRequest.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventSource.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventTarget.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryImageDeletedEventData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryImagePushedEventData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/DeviceConnectionStateEventInfo.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/DeviceConnectionStateEventProperties.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/DeviceLifeCycleEventProperties.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTelemetryEventProperties.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfo.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfoProperties.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfoX509Thumbprint.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinMetadata.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinProperties.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/EventGridEvent.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/EventHubCaptureFileCreatedEventData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceConnectedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceCreatedEventData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceDeletedEventData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceDisconnectedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceTelemetryEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/JobState.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceEnteredEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceEventProperties.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceExitedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceGeometry.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceResultEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobCanceledEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobCancelingEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobError.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorCategory.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorCode.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorDetail.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErroredEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobFinishedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutput.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputAsset.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputCanceledEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputCancelingEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputErroredEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputFinishedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputProcessingEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputProgressEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputScheduledEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputStateChangeEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobProcessingEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobRetry.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobScheduledEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobState.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobStateChangeEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventConnectionRejectedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventEncoderConnectedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventEncoderDisconnectedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingDataChunkDroppedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingStreamReceivedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingStreamsOutOfSyncEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingVideoStreamsOutOfSyncEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIngestHeartbeatEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventTrackDiscontinuityDetectedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionCancelData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionFailureData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionSuccessData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteCancelData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteFailureData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteSuccessData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteCancelData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteFailureData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteSuccessData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ServiceBusActiveMessagesAvailableWithNoListenersEventData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/StorageBlobCreatedEventData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/StorageBlobDeletedEventData.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionDeletedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionValidationEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionValidationResponse.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/models/package-info.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/main/java/com/microsoft/azure/eventgrid/package-info.java (100%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/java/com/microsoft/azure/eventgrid/EventGridTests.java (98%) mode change 100755 => 100644 rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/java/com/microsoft/azure/eventgrid/customization/CustomizationTests.java (99%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemReceivedEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemSentEventData.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/java/com/microsoft/azure/eventgrid/customization/models/DroneShippingInfo.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/java/com/microsoft/azure/eventgrid/customization/models/RocketShippingInfo.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/java/com/microsoft/azure/eventgrid/customization/models/ShippingInfo.java (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/AppConfigurationKeyValueDeleted.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/AppConfigurationKeyValueModified.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ContainerRegistryChartDeletedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ContainerRegistryChartPushedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ContainerRegistryImageDeletedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ContainerRegistryImagePushedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/CustomEventWithArrayData.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/CustomEventWithBooleanData.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/CustomEventWithPolymorphicData.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/CustomEventWithStringData.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/CustomEvents.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/EventGridSubscriptionDeletedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/EventGridSubscriptionValidationEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/EventHubCaptureFileCreatedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/IoTHubDeviceConnectedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/IoTHubDeviceCreatedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/IoTHubDeviceDeletedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/IoTHubDeviceDisconnectedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/IoTHubDeviceTelemetryEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MapsGeofenceEnteredEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MapsGeofenceExitedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MapsGeofenceResultEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobCanceledEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobCancelingEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobErroredEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobFinishedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobOutputCanceledEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobOutputCancelingEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobOutputErroredEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobOutputFinishedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobOutputProcessingEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobOutputProgressEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobOutputScheduledEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobOutputStateChangeEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobProcessingEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobScheduledEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaJobStateChangeEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaLiveEventConnectionRejectedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaLiveEventEncoderConnectedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaLiveEventEncoderDisconnectedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaLiveEventIncomingDataChunkDroppedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaLiveEventIncomingStreamReceivedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaLiveEventIncomingStreamsOutOfSyncEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaLiveEventIncomingVideoStreamsOutOfSyncEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaLiveEventIngestHeartbeatEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaLiveEventTrackDiscontinuityDetectedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MediaServicesJobStateChangedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/MultipleEventsInSameBatch.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ResourceActionCancelEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ResourceActionFailureEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ResourceActionSuccessEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ResourceDeleteCancelEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ResourceDeleteFailureEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ResourceDeleteSuccessEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ResourceWriteCancelEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ResourceWriteFailureEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ResourceWriteSuccessEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ServiceBusActiveMessagesAvailableWithNoListenersEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/ServiceBusDeadletterMessagesAvailableWithNoListenersEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/StorageBlobCreatedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/StorageBlobDeletedEvent.json (100%) rename {eventgrid/data-plane => sdk/eventgrid/microsoft-azure-eventgrid}/src/test/resources/customization/StorageBlobDeletedEventWithExtraProperty.json (100%) create mode 100644 sdk/eventgrid/pom.service.xml diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml index fde81ca0d4b8f..d82894fb16af9 100644 --- a/eng/.docsettings.yml +++ b/eng/.docsettings.yml @@ -57,7 +57,7 @@ known_content_issues: - ['README.md', '#3113'] - ['sdk/applicationinsights/microsoft-azure-applicationinsights-query/README.md', '#3113'] - ['sdk/batch/microsoft-azure-batch/README.md', '#3113'] - - ['eventgrid/data-plane/README.md', '#3113'] + - ['sdk/eventgrid/microsoft-azure-eventgrid/README.md', '#3113'] - ['eventhubs/data-plane/readme.md', '#3113'] - ['eventhubs/data-plane/azure-eventhubs-eph/Readme.md', '#3113'] - ['sdk/authorization/microsoft-azure-authentication-msi-token-provider/readme.md', '#3113'] diff --git a/eventgrid/data-plane/README.md b/sdk/eventgrid/microsoft-azure-eventgrid/README.md old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/README.md rename to sdk/eventgrid/microsoft-azure-eventgrid/README.md diff --git a/eventgrid/data-plane/pom.xml b/sdk/eventgrid/microsoft-azure-eventgrid/pom.xml old mode 100755 new mode 100644 similarity index 96% rename from eventgrid/data-plane/pom.xml rename to sdk/eventgrid/microsoft-azure-eventgrid/pom.xml index fbef3bf157f7a..674f7f407d618 --- a/eventgrid/data-plane/pom.xml +++ b/sdk/eventgrid/microsoft-azure-eventgrid/pom.xml @@ -14,7 +14,7 @@ Microsoft Azure SDK for eventgrid This package contains Microsoft Azure EventGrid SDK. https://github.com/Azure/azure-sdk-for-java - + The MIT License (MIT) http://opensource.org/licenses/MIT @@ -54,6 +54,11 @@ 1.5.0 test + + commons-io + commons-io + 2.6 + diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/DomainCredentials.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/DomainCredentials.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/DomainCredentials.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/DomainCredentials.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/EventGridClient.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/EventGridClient.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/EventGridClient.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/EventGridClient.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/TopicCredentials.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/TopicCredentials.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/TopicCredentials.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/TopicCredentials.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/customization/EventGridSubscriber.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/customization/EventGridSubscriber.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/customization/EventGridSubscriber.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/customization/EventGridSubscriber.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/customization/SystemEventTypeMappings.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/customization/SystemEventTypeMappings.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/customization/SystemEventTypeMappings.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/customization/SystemEventTypeMappings.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/customization/SystemEventTypes.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/customization/SystemEventTypes.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/customization/SystemEventTypes.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/customization/SystemEventTypes.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/implementation/EventGridClientImpl.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/implementation/EventGridClientImpl.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/implementation/EventGridClientImpl.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/implementation/EventGridClientImpl.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/implementation/package-info.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/implementation/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/implementation/package-info.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/implementation/package-info.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/AppConfigurationKeyValueDeletedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/AppConfigurationKeyValueDeletedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/AppConfigurationKeyValueDeletedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/AppConfigurationKeyValueDeletedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/AppConfigurationKeyValueModifiedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/AppConfigurationKeyValueModifiedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/AppConfigurationKeyValueModifiedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/AppConfigurationKeyValueModifiedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryArtifactEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryArtifactEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryArtifactEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryArtifactEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryArtifactEventTarget.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryArtifactEventTarget.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryArtifactEventTarget.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryArtifactEventTarget.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryChartDeletedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryChartDeletedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryChartDeletedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryChartDeletedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryChartPushedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryChartPushedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryChartPushedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryChartPushedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventActor.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventActor.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventActor.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventActor.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventRequest.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventRequest.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventRequest.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventRequest.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventSource.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventSource.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventSource.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventSource.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventTarget.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventTarget.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventTarget.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryEventTarget.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryImageDeletedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryImageDeletedEventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryImageDeletedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryImageDeletedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryImagePushedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryImagePushedEventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryImagePushedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ContainerRegistryImagePushedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceConnectionStateEventInfo.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceConnectionStateEventInfo.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceConnectionStateEventInfo.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceConnectionStateEventInfo.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceConnectionStateEventProperties.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceConnectionStateEventProperties.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceConnectionStateEventProperties.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceConnectionStateEventProperties.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceLifeCycleEventProperties.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceLifeCycleEventProperties.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceLifeCycleEventProperties.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceLifeCycleEventProperties.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTelemetryEventProperties.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTelemetryEventProperties.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTelemetryEventProperties.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTelemetryEventProperties.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfo.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfo.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfo.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfo.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfoProperties.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfoProperties.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfoProperties.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfoProperties.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfoX509Thumbprint.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfoX509Thumbprint.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfoX509Thumbprint.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinInfoX509Thumbprint.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinMetadata.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinMetadata.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinMetadata.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinMetadata.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinProperties.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinProperties.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinProperties.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/DeviceTwinProperties.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/EventGridEvent.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/EventGridEvent.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/EventGridEvent.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/EventGridEvent.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/EventHubCaptureFileCreatedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/EventHubCaptureFileCreatedEventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/EventHubCaptureFileCreatedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/EventHubCaptureFileCreatedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceConnectedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceConnectedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceConnectedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceConnectedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceCreatedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceCreatedEventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceCreatedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceCreatedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceDeletedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceDeletedEventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceDeletedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceDeletedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceDisconnectedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceDisconnectedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceDisconnectedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceDisconnectedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceTelemetryEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceTelemetryEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceTelemetryEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/IotHubDeviceTelemetryEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/JobState.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/JobState.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/JobState.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/JobState.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceEnteredEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceEnteredEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceEnteredEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceEnteredEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceEventProperties.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceEventProperties.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceEventProperties.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceEventProperties.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceExitedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceExitedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceExitedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceExitedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceGeometry.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceGeometry.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceGeometry.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceGeometry.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceResultEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceResultEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceResultEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MapsGeofenceResultEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobCanceledEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobCanceledEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobCanceledEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobCanceledEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobCancelingEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobCancelingEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobCancelingEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobCancelingEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobError.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobError.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobError.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobError.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorCategory.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorCategory.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorCategory.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorCategory.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorCode.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorCode.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorCode.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorCode.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorDetail.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorDetail.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorDetail.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErrorDetail.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErroredEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErroredEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErroredEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobErroredEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobFinishedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobFinishedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobFinishedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobFinishedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutput.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutput.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutput.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutput.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputAsset.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputAsset.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputAsset.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputAsset.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputCanceledEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputCanceledEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputCanceledEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputCanceledEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputCancelingEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputCancelingEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputCancelingEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputCancelingEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputErroredEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputErroredEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputErroredEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputErroredEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputFinishedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputFinishedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputFinishedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputFinishedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputProcessingEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputProcessingEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputProcessingEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputProcessingEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputProgressEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputProgressEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputProgressEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputProgressEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputScheduledEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputScheduledEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputScheduledEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputScheduledEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputStateChangeEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputStateChangeEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputStateChangeEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobOutputStateChangeEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobProcessingEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobProcessingEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobProcessingEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobProcessingEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobRetry.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobRetry.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobRetry.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobRetry.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobScheduledEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobScheduledEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobScheduledEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobScheduledEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobState.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobState.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobState.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobState.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobStateChangeEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobStateChangeEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobStateChangeEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaJobStateChangeEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventConnectionRejectedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventConnectionRejectedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventConnectionRejectedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventConnectionRejectedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventEncoderConnectedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventEncoderConnectedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventEncoderConnectedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventEncoderConnectedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventEncoderDisconnectedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventEncoderDisconnectedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventEncoderDisconnectedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventEncoderDisconnectedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingDataChunkDroppedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingDataChunkDroppedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingDataChunkDroppedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingDataChunkDroppedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingStreamReceivedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingStreamReceivedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingStreamReceivedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingStreamReceivedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingStreamsOutOfSyncEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingStreamsOutOfSyncEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingStreamsOutOfSyncEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingStreamsOutOfSyncEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingVideoStreamsOutOfSyncEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingVideoStreamsOutOfSyncEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingVideoStreamsOutOfSyncEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIncomingVideoStreamsOutOfSyncEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIngestHeartbeatEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIngestHeartbeatEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIngestHeartbeatEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventIngestHeartbeatEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventTrackDiscontinuityDetectedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventTrackDiscontinuityDetectedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventTrackDiscontinuityDetectedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/MediaLiveEventTrackDiscontinuityDetectedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionCancelData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionCancelData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionCancelData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionCancelData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionFailureData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionFailureData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionFailureData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionFailureData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionSuccessData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionSuccessData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionSuccessData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceActionSuccessData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteCancelData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteCancelData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteCancelData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteCancelData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteFailureData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteFailureData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteFailureData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteFailureData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteSuccessData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteSuccessData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteSuccessData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceDeleteSuccessData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteCancelData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteCancelData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteCancelData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteCancelData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteFailureData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteFailureData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteFailureData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteFailureData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteSuccessData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteSuccessData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteSuccessData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ResourceWriteSuccessData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ServiceBusActiveMessagesAvailableWithNoListenersEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ServiceBusActiveMessagesAvailableWithNoListenersEventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ServiceBusActiveMessagesAvailableWithNoListenersEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ServiceBusActiveMessagesAvailableWithNoListenersEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/StorageBlobCreatedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/StorageBlobCreatedEventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/StorageBlobCreatedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/StorageBlobCreatedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/StorageBlobDeletedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/StorageBlobDeletedEventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/StorageBlobDeletedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/StorageBlobDeletedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionDeletedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionDeletedEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionDeletedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionDeletedEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionValidationEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionValidationEventData.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionValidationEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionValidationEventData.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionValidationResponse.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionValidationResponse.java similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionValidationResponse.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/SubscriptionValidationResponse.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/package-info.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/models/package-info.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/models/package-info.java diff --git a/eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/package-info.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/package-info.java old mode 100755 new mode 100644 similarity index 100% rename from eventgrid/data-plane/src/main/java/com/microsoft/azure/eventgrid/package-info.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/main/java/com/microsoft/azure/eventgrid/package-info.java diff --git a/eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/EventGridTests.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/EventGridTests.java old mode 100755 new mode 100644 similarity index 98% rename from eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/EventGridTests.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/EventGridTests.java index 05473791aa670..962ad6805904d --- a/eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/EventGridTests.java +++ b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/EventGridTests.java @@ -10,6 +10,7 @@ import org.joda.time.DateTime; import org.junit.Test; +import org.junit.Ignore; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; @@ -21,6 +22,7 @@ public class EventGridTests { @Test + @Ignore public void canPublishEvent() throws Exception { String endpoint = System.getenv("EG_ENDPOINT"); String key = System.getenv("EG_KEY"); diff --git a/eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/CustomizationTests.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/CustomizationTests.java similarity index 99% rename from eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/CustomizationTests.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/CustomizationTests.java index d2dc11318afb7..c9c64040e7781 100644 --- a/eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/CustomizationTests.java +++ b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/CustomizationTests.java @@ -70,7 +70,7 @@ import com.microsoft.azure.eventgrid.models.SubscriptionValidationEventData; import org.junit.Assert; import org.junit.Test; -import sun.misc.IOUtils; +import org.apache.commons.io.IOUtils; import java.io.IOException; import java.lang.reflect.Type; @@ -1038,7 +1038,7 @@ public void consumeResourceWriteSuccessEvent() throws IOException { private String getTestPayloadFromFile(String fileName) { ClassLoader classLoader = getClass().getClassLoader(); try { - byte[] bytes = IOUtils.readFully(classLoader.getResourceAsStream("customization\\" + fileName), -1, true); + byte[] bytes = IOUtils.toByteArray(classLoader.getResourceAsStream("customization/" + fileName)); return new String(bytes); } catch (IOException e) { throw new RuntimeException(e); diff --git a/eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemReceivedEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemReceivedEventData.java similarity index 100% rename from eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemReceivedEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemReceivedEventData.java diff --git a/eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemSentEventData.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemSentEventData.java similarity index 100% rename from eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemSentEventData.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemSentEventData.java diff --git a/eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/DroneShippingInfo.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/DroneShippingInfo.java similarity index 100% rename from eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/DroneShippingInfo.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/DroneShippingInfo.java diff --git a/eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/RocketShippingInfo.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/RocketShippingInfo.java similarity index 100% rename from eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/RocketShippingInfo.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/RocketShippingInfo.java diff --git a/eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/ShippingInfo.java b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/ShippingInfo.java similarity index 100% rename from eventgrid/data-plane/src/test/java/com/microsoft/azure/eventgrid/customization/models/ShippingInfo.java rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/ShippingInfo.java diff --git a/eventgrid/data-plane/src/test/resources/customization/AppConfigurationKeyValueDeleted.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/AppConfigurationKeyValueDeleted.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/AppConfigurationKeyValueDeleted.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/AppConfigurationKeyValueDeleted.json diff --git a/eventgrid/data-plane/src/test/resources/customization/AppConfigurationKeyValueModified.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/AppConfigurationKeyValueModified.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/AppConfigurationKeyValueModified.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/AppConfigurationKeyValueModified.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ContainerRegistryChartDeletedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ContainerRegistryChartDeletedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ContainerRegistryChartDeletedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ContainerRegistryChartDeletedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ContainerRegistryChartPushedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ContainerRegistryChartPushedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ContainerRegistryChartPushedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ContainerRegistryChartPushedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ContainerRegistryImageDeletedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ContainerRegistryImageDeletedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ContainerRegistryImageDeletedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ContainerRegistryImageDeletedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ContainerRegistryImagePushedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ContainerRegistryImagePushedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ContainerRegistryImagePushedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ContainerRegistryImagePushedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/CustomEventWithArrayData.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/CustomEventWithArrayData.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/CustomEventWithArrayData.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/CustomEventWithArrayData.json diff --git a/eventgrid/data-plane/src/test/resources/customization/CustomEventWithBooleanData.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/CustomEventWithBooleanData.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/CustomEventWithBooleanData.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/CustomEventWithBooleanData.json diff --git a/eventgrid/data-plane/src/test/resources/customization/CustomEventWithPolymorphicData.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/CustomEventWithPolymorphicData.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/CustomEventWithPolymorphicData.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/CustomEventWithPolymorphicData.json diff --git a/eventgrid/data-plane/src/test/resources/customization/CustomEventWithStringData.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/CustomEventWithStringData.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/CustomEventWithStringData.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/CustomEventWithStringData.json diff --git a/eventgrid/data-plane/src/test/resources/customization/CustomEvents.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/CustomEvents.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/CustomEvents.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/CustomEvents.json diff --git a/eventgrid/data-plane/src/test/resources/customization/EventGridSubscriptionDeletedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/EventGridSubscriptionDeletedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/EventGridSubscriptionDeletedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/EventGridSubscriptionDeletedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/EventGridSubscriptionValidationEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/EventGridSubscriptionValidationEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/EventGridSubscriptionValidationEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/EventGridSubscriptionValidationEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/EventHubCaptureFileCreatedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/EventHubCaptureFileCreatedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/EventHubCaptureFileCreatedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/EventHubCaptureFileCreatedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/IoTHubDeviceConnectedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/IoTHubDeviceConnectedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/IoTHubDeviceConnectedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/IoTHubDeviceConnectedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/IoTHubDeviceCreatedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/IoTHubDeviceCreatedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/IoTHubDeviceCreatedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/IoTHubDeviceCreatedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/IoTHubDeviceDeletedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/IoTHubDeviceDeletedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/IoTHubDeviceDeletedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/IoTHubDeviceDeletedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/IoTHubDeviceDisconnectedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/IoTHubDeviceDisconnectedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/IoTHubDeviceDisconnectedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/IoTHubDeviceDisconnectedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/IoTHubDeviceTelemetryEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/IoTHubDeviceTelemetryEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/IoTHubDeviceTelemetryEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/IoTHubDeviceTelemetryEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MapsGeofenceEnteredEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MapsGeofenceEnteredEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MapsGeofenceEnteredEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MapsGeofenceEnteredEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MapsGeofenceExitedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MapsGeofenceExitedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MapsGeofenceExitedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MapsGeofenceExitedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MapsGeofenceResultEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MapsGeofenceResultEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MapsGeofenceResultEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MapsGeofenceResultEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobCanceledEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobCanceledEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobCanceledEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobCanceledEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobCancelingEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobCancelingEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobCancelingEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobCancelingEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobErroredEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobErroredEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobErroredEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobErroredEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobFinishedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobFinishedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobFinishedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobFinishedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobOutputCanceledEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputCanceledEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobOutputCanceledEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputCanceledEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobOutputCancelingEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputCancelingEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobOutputCancelingEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputCancelingEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobOutputErroredEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputErroredEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobOutputErroredEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputErroredEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobOutputFinishedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputFinishedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobOutputFinishedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputFinishedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobOutputProcessingEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputProcessingEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobOutputProcessingEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputProcessingEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobOutputProgressEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputProgressEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobOutputProgressEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputProgressEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobOutputScheduledEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputScheduledEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobOutputScheduledEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputScheduledEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobOutputStateChangeEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputStateChangeEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobOutputStateChangeEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobOutputStateChangeEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobProcessingEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobProcessingEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobProcessingEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobProcessingEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobScheduledEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobScheduledEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobScheduledEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobScheduledEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaJobStateChangeEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobStateChangeEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaJobStateChangeEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaJobStateChangeEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaLiveEventConnectionRejectedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventConnectionRejectedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaLiveEventConnectionRejectedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventConnectionRejectedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaLiveEventEncoderConnectedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventEncoderConnectedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaLiveEventEncoderConnectedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventEncoderConnectedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaLiveEventEncoderDisconnectedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventEncoderDisconnectedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaLiveEventEncoderDisconnectedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventEncoderDisconnectedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaLiveEventIncomingDataChunkDroppedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventIncomingDataChunkDroppedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaLiveEventIncomingDataChunkDroppedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventIncomingDataChunkDroppedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaLiveEventIncomingStreamReceivedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventIncomingStreamReceivedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaLiveEventIncomingStreamReceivedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventIncomingStreamReceivedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaLiveEventIncomingStreamsOutOfSyncEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventIncomingStreamsOutOfSyncEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaLiveEventIncomingStreamsOutOfSyncEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventIncomingStreamsOutOfSyncEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaLiveEventIncomingVideoStreamsOutOfSyncEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventIncomingVideoStreamsOutOfSyncEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaLiveEventIncomingVideoStreamsOutOfSyncEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventIncomingVideoStreamsOutOfSyncEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaLiveEventIngestHeartbeatEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventIngestHeartbeatEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaLiveEventIngestHeartbeatEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventIngestHeartbeatEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaLiveEventTrackDiscontinuityDetectedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventTrackDiscontinuityDetectedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaLiveEventTrackDiscontinuityDetectedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaLiveEventTrackDiscontinuityDetectedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MediaServicesJobStateChangedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaServicesJobStateChangedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MediaServicesJobStateChangedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MediaServicesJobStateChangedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/MultipleEventsInSameBatch.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MultipleEventsInSameBatch.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/MultipleEventsInSameBatch.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/MultipleEventsInSameBatch.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ResourceActionCancelEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceActionCancelEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ResourceActionCancelEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceActionCancelEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ResourceActionFailureEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceActionFailureEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ResourceActionFailureEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceActionFailureEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ResourceActionSuccessEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceActionSuccessEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ResourceActionSuccessEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceActionSuccessEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ResourceDeleteCancelEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceDeleteCancelEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ResourceDeleteCancelEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceDeleteCancelEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ResourceDeleteFailureEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceDeleteFailureEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ResourceDeleteFailureEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceDeleteFailureEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ResourceDeleteSuccessEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceDeleteSuccessEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ResourceDeleteSuccessEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceDeleteSuccessEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ResourceWriteCancelEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceWriteCancelEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ResourceWriteCancelEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceWriteCancelEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ResourceWriteFailureEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceWriteFailureEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ResourceWriteFailureEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceWriteFailureEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ResourceWriteSuccessEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceWriteSuccessEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ResourceWriteSuccessEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ResourceWriteSuccessEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ServiceBusActiveMessagesAvailableWithNoListenersEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ServiceBusActiveMessagesAvailableWithNoListenersEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ServiceBusActiveMessagesAvailableWithNoListenersEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ServiceBusActiveMessagesAvailableWithNoListenersEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/ServiceBusDeadletterMessagesAvailableWithNoListenersEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ServiceBusDeadletterMessagesAvailableWithNoListenersEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/ServiceBusDeadletterMessagesAvailableWithNoListenersEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/ServiceBusDeadletterMessagesAvailableWithNoListenersEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/StorageBlobCreatedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/StorageBlobCreatedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/StorageBlobCreatedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/StorageBlobCreatedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/StorageBlobDeletedEvent.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/StorageBlobDeletedEvent.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/StorageBlobDeletedEvent.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/StorageBlobDeletedEvent.json diff --git a/eventgrid/data-plane/src/test/resources/customization/StorageBlobDeletedEventWithExtraProperty.json b/sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/StorageBlobDeletedEventWithExtraProperty.json similarity index 100% rename from eventgrid/data-plane/src/test/resources/customization/StorageBlobDeletedEventWithExtraProperty.json rename to sdk/eventgrid/microsoft-azure-eventgrid/src/test/resources/customization/StorageBlobDeletedEventWithExtraProperty.json diff --git a/sdk/eventgrid/pom.service.xml b/sdk/eventgrid/pom.service.xml new file mode 100644 index 0000000000000..74589c55c2717 --- /dev/null +++ b/sdk/eventgrid/pom.service.xml @@ -0,0 +1,14 @@ + + + 4.0.0 + com.azure + azure-eventgrid-service + pom + 1.0.0 + + microsoft-azure-eventgrid + + From 89c2aa23a609666e89e0b25f13317de11299fe05 Mon Sep 17 00:00:00 2001 From: Sameeksha Vaity Date: Fri, 12 Jul 2019 10:44:26 -0700 Subject: [PATCH 76/85] Eventhub annotations (#4313) --- sdk/eventhubs/azure-eventhubs/README.md | 12 ++-- ...ubClient.java => EventHubAsyncClient.java} | 53 +++++++++++++-- .../eventhubs/EventHubClientBuilder.java | 36 +++++----- .../messaging/eventhubs/EventHubConsumer.java | 12 ++-- .../messaging/eventhubs/EventHubProducer.java | 10 ++- .../eventhubs/EventHubProperties.java | 11 ++- .../EventHubSharedAccessKeyCredential.java | 2 + .../eventhubs/PartitionProperties.java | 3 + .../implementation/ConnectionOptions.java | 2 +- .../{ => models}/EventHubConsumerOptions.java | 17 +++-- .../{ => models}/EventHubProducerOptions.java | 10 ++- .../eventhubs/{ => models}/EventPosition.java | 68 +++++++++++-------- .../{ => models}/ProxyAuthenticationType.java | 2 +- .../{ => models}/ProxyConfiguration.java | 4 +- .../eventhubs/{ => models}/SendOptions.java | 16 ++--- .../eventhubs/models/package-info.java | 7 ++ .../messaging/eventhubs/package-info.java | 2 +- .../src/samples/java/ConsumeEvent.java | 12 ++-- ...EventsFromKnownSequenceNumberPosition.java | 13 ++-- .../src/samples/java/GetEventHubMetadata.java | 4 +- .../src/samples/java/PublishEvent.java | 4 +- .../PublishEventsToSpecificPartition.java | 6 +- .../java/PublishEventsWithCustomMetadata.java | 4 +- .../java/PublishEventsWithPartitionKey.java | 6 +- ...entHubClientBuilderJavaDocCodeSamples.java | 12 ++-- .../EventHubConsumerJavaDocCodeSamples.java | 11 +-- .../EventHubProducerJavaDocCodeSamples.java | 6 +- .../messaging/eventhubs/BackCompatTest.java | 8 ++- .../EventDataBatchIntegrationTest.java | 8 ++- .../eventhubs/EventHubClientBuilderTest.java | 4 +- .../EventHubClientIntegrationTest.java | 19 +++--- ...EventHubClientMetadataIntegrationTest.java | 9 +-- .../EventHubConsumerIntegrationTest.java | 12 ++-- .../eventhubs/EventHubConsumerTest.java | 1 + .../eventhubs/EventHubProducerTest.java | 12 ++-- .../EventPositionIntegrationTest.java | 10 +-- .../eventhubs/InteropAmqpPropertiesTest.java | 8 ++- .../messaging/eventhubs/SendOptionsTest.java | 27 ++++---- .../eventhubs/SetPrefetchCountTest.java | 14 ++-- .../eventhubs/implementation/ApiTestBase.java | 2 +- .../implementation/ReactorConnectionTest.java | 2 +- .../EventHubConsumerOptionsTest.java | 2 +- .../EventHubProducerOptionsTest.java | 2 +- .../{ => models}/ProxyConfigurationTest.java | 4 +- 44 files changed, 301 insertions(+), 188 deletions(-) rename sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/{EventHubClient.java => EventHubAsyncClient.java} (85%) rename sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/{ => models}/EventHubConsumerOptions.java (94%) rename sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/{ => models}/EventHubProducerOptions.java (92%) rename sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/{ => models}/EventPosition.java (80%) rename sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/{ => models}/ProxyAuthenticationType.java (91%) rename sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/{ => models}/ProxyConfiguration.java (97%) rename sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/{ => models}/SendOptions.java (89%) create mode 100644 sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/models/package-info.java rename sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/{ => models}/EventHubConsumerOptionsTest.java (98%) rename sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/{ => models}/EventHubProducerOptionsTest.java (96%) rename sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/{ => models}/ProxyConfigurationTest.java (97%) diff --git a/sdk/eventhubs/azure-eventhubs/README.md b/sdk/eventhubs/azure-eventhubs/README.md index 68cddc513e8f5..adc20b3f2cf68 100644 --- a/sdk/eventhubs/azure-eventhubs/README.md +++ b/sdk/eventhubs/azure-eventhubs/README.md @@ -51,12 +51,12 @@ The easiest means for doing so is to use a connection string, which is created a Event Hubs namespace. If you aren't familiar with shared access policies in Azure, you may wish to follow the step-by-step guide to [get an Event Hubs connection string][event_hubs_connection_string]. -Once the connection string is obtained, create an `EventHubClient` using the `EventHubClientBuilder`: +Once the connection string is obtained, create an `EventHubAsyncClient` using the `EventHubClientBuilder`: ```java String connectionString = "<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>"; String eventHubPath = "<< NAME OF THE EVENT HUB >>"; -EventHubClient client = new EventHubClientBuilder() +EventHubAsyncClient client = new EventHubClientBuilder() .connectionString(connectionString, eventHubPath) .buildAsyncClient(); ``` @@ -91,7 +91,7 @@ ClientSecretCredential credential = new ClientSecretCredential() // {your-namespace}.servicebus.windows.net String host = "<< EVENT HUBS HOST >>" String eventHubPath = "<< NAME OF THE EVENT HUB >>"; -EventHubClient client = new EventHubClientBuilder() +EventHubAsyncClient client = new EventHubClientBuilder() .credential(host, eventHubPath, credential) .buildAsyncClient(); ``` @@ -143,7 +143,7 @@ you can also use the send method to send multiple events using a single call. #### Producer creation -With an existing [EventHubClient][eventhubclient], developers can create a producer by calling `createProducer()` or +With an existing [EventHubAsyncClient][eventhubasyncclient], developers can create a producer by calling `createProducer()` or `createProducer(EventHubProducerOptions)`. Creates a producer sends events to any partition, allowing Event Hubs service to route the event to an available @@ -192,7 +192,7 @@ We are creating a consumer that receives events from `partitionID` and only list the partition. ```java -EventHubConsumer consumer = client.createConsumer(EventHubClient.DEFAULT_CONSUMER_GROUP_NAME, partitionID, +EventHubConsumer consumer = client.createConsumer(EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME, partitionID, EventPosition.latest()); ``` @@ -305,7 +305,7 @@ Guidelines](./CONTRIBUTING.md) for more information. [event_hubs_messaging_exceptions]: https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-messaging-exceptions [event_hubs_product_docs]: https://docs.microsoft.com/en-us/azure/event-hubs/ [event_hubs_quotas]: https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-quotas -[eventhubclient]: ./azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClient.java +[eventhubasyncclient]: ./azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubAsyncClient.java [eventhubconsumer]: ./azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducer.java [eventhubproduceroptions]: ./azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducerOptions.java [java_8_sdk_javadocs]: https://docs.oracle.com/javase/8/docs/api/java/util/logging/package-summary.html diff --git a/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClient.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubAsyncClient.java similarity index 85% rename from sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClient.java rename to sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubAsyncClient.java index a9cd13f889fd0..b8fbd025a1bc9 100644 --- a/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClient.java +++ b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubAsyncClient.java @@ -6,11 +6,15 @@ import com.azure.core.amqp.AmqpConnection; import com.azure.core.amqp.exception.AmqpException; import com.azure.core.amqp.exception.ErrorContext; +import com.azure.core.implementation.annotation.ReturnType; +import com.azure.core.implementation.annotation.ServiceClient; +import com.azure.core.implementation.annotation.ServiceMethod; import com.azure.core.implementation.util.ImplUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.implementation.AmqpReceiveLink; import com.azure.messaging.eventhubs.implementation.AmqpResponseMapper; import com.azure.messaging.eventhubs.implementation.AmqpSendLink; +import com.azure.messaging.eventhubs.implementation.AmqpConstants; import com.azure.messaging.eventhubs.implementation.ConnectionOptions; import com.azure.messaging.eventhubs.implementation.EventHubConnection; import com.azure.messaging.eventhubs.implementation.EventHubManagementNode; @@ -20,6 +24,9 @@ import com.azure.messaging.eventhubs.implementation.ReactorHandlerProvider; import com.azure.messaging.eventhubs.implementation.ReactorProvider; import com.azure.messaging.eventhubs.implementation.StringUtil; +import com.azure.messaging.eventhubs.models.EventHubConsumerOptions; +import com.azure.messaging.eventhubs.models.EventHubProducerOptions; +import com.azure.messaging.eventhubs.models.EventPosition; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -31,23 +38,28 @@ import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; +import static com.azure.core.amqp.MessageConstant.ENQUEUED_TIME_UTC_ANNOTATION_NAME; +import static com.azure.core.amqp.MessageConstant.OFFSET_ANNOTATION_NAME; +import static com.azure.core.amqp.MessageConstant.SEQUENCE_NUMBER_ANNOTATION_NAME; + /** * The main point of interaction with Azure Event Hubs, the client offers a connection to a specific Event Hub within * the Event Hubs namespace and offers operations for sending event data, receiving events, and inspecting the connected * Event Hub. * - *

Creating an {@link EventHubClient} using Event Hubs namespace connection string

+ *

Creating an {@link EventHubAsyncClient} using Event Hubs namespace connection string

* * {@codesnippet com.azure.messaging.eventhubs.eventhubclientbuilder.connectionString#string-string} * - *

Creating an {@link EventHubClient} using Event Hub instance connection string

+ *

Creating an {@link EventHubAsyncClient} using Event Hub instance connection string

* * {@codesnippet com.azure.messaging.eventhubs.eventhubclientbuilder.connectionstring#string} * * @see EventHubClientBuilder * @see About Azure Event Hubs */ -public class EventHubClient implements Closeable { +@ServiceClient(builder = EventHubClientBuilder.class, isAsync = true) +public class EventHubAsyncClient implements Closeable { /** * The name of the default consumer group in the Event Hubs service. */ @@ -56,7 +68,7 @@ public class EventHubClient implements Closeable { private static final String RECEIVER_ENTITY_PATH_FORMAT = "%s/ConsumerGroups/%s/Partitions/%s"; private static final String SENDER_ENTITY_PATH_FORMAT = "%s/Partitions/%s"; - private final ClientLogger logger = new ClientLogger(EventHubClient.class); + private final ClientLogger logger = new ClientLogger(EventHubAsyncClient.class); private final String connectionId; private final Mono connectionMono; private final AtomicBoolean hasConnection = new AtomicBoolean(false); @@ -65,7 +77,7 @@ public class EventHubClient implements Closeable { private final EventHubProducerOptions defaultProducerOptions; private final EventHubConsumerOptions defaultConsumerOptions; - EventHubClient(ConnectionOptions connectionOptions, ReactorProvider provider, ReactorHandlerProvider handlerProvider) { + EventHubAsyncClient(ConnectionOptions connectionOptions, ReactorProvider provider, ReactorHandlerProvider handlerProvider) { Objects.requireNonNull(connectionOptions); Objects.requireNonNull(provider); Objects.requireNonNull(handlerProvider); @@ -91,6 +103,7 @@ public class EventHubClient implements Closeable { * * @return The set of information for the Event Hub that this client is associated with. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono getProperties() { return connectionMono.flatMap(connection -> connection.getManagementNode().flatMap(EventHubManagementNode::getEventHubProperties)); } @@ -100,6 +113,7 @@ public Mono getProperties() { * * @return A Flux of identifiers for the partitions of an Event Hub. */ + @ServiceMethod(returns = ReturnType.COLLECTION) public Flux getPartitionIds() { return getProperties().flatMapMany(properties -> Flux.fromArray(properties.partitionIds())); } @@ -111,6 +125,7 @@ public Flux getPartitionIds() { * @param partitionId The unique identifier of a partition associated with the Event Hub. * @return The set of information for the requested partition under the Event Hub this client is associated with. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono getPartitionProperties(String partitionId) { return connectionMono.flatMap( connection -> connection.getManagementNode().flatMap(node -> { @@ -249,7 +264,7 @@ public EventHubConsumer createConsumer(String consumerGroup, String partitionId, return connection.createSession(entityPath).cast(EventHubSession.class); }).flatMap(session -> { logger.info("Creating consumer."); - return session.createConsumer(linkName, entityPath, eventPosition.getExpression(), connectionOptions.timeout(), + return session.createConsumer(linkName, entityPath, getExpression(eventPosition), connectionOptions.timeout(), clonedOptions.retry(), options.ownerLevel(), options.identifier()).cast(AmqpReceiveLink.class); }); @@ -275,6 +290,32 @@ public void close() { } } + private static String getExpression(EventPosition eventPosition) { + final String isInclusiveFlag = eventPosition.isInclusive() ? "=" : ""; + + // order of preference + if (eventPosition.offset() != null) { + return String.format(AmqpConstants.AMQP_ANNOTATION_FORMAT, OFFSET_ANNOTATION_NAME.getValue(), isInclusiveFlag, eventPosition.offset()); + } + + if (eventPosition.sequenceNumber() != null) { + return String.format(AmqpConstants.AMQP_ANNOTATION_FORMAT, SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), isInclusiveFlag, eventPosition.sequenceNumber()); + } + + if (eventPosition.enqueuedDateTime() != null) { + String ms; + try { + ms = Long.toString(eventPosition.enqueuedDateTime().toEpochMilli()); + } catch (ArithmeticException ex) { + ms = Long.toString(Long.MAX_VALUE); + } + + return String.format(AmqpConstants.AMQP_ANNOTATION_FORMAT, ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue(), isInclusiveFlag, ms); + } + + throw new IllegalArgumentException("No starting position was set."); + } + private static class ResponseMapper implements AmqpResponseMapper { @Override public EventHubProperties toEventHubProperties(Map amqpBody) { diff --git a/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java index a336bd7774d43..a7152dd1e525a 100644 --- a/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java +++ b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java @@ -7,6 +7,7 @@ import com.azure.core.amqp.TransportType; import com.azure.core.credentials.TokenCredential; import com.azure.core.exception.AzureException; +import com.azure.core.implementation.annotation.ServiceClientBuilder; import com.azure.core.implementation.util.ImplUtils; import com.azure.core.util.configuration.BaseConfigurations; import com.azure.core.util.configuration.Configuration; @@ -17,6 +18,8 @@ import com.azure.messaging.eventhubs.implementation.ConnectionStringProperties; import com.azure.messaging.eventhubs.implementation.ReactorHandlerProvider; import com.azure.messaging.eventhubs.implementation.ReactorProvider; +import com.azure.messaging.eventhubs.models.ProxyAuthenticationType; +import com.azure.messaging.eventhubs.models.ProxyConfiguration; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; @@ -30,29 +33,30 @@ /** * This class provides a fluent builder API to help aid the configuration and instantiation of the {@link - * EventHubClient}. Calling {@link #buildAsyncClient()} constructs an instant of the client. + * EventHubAsyncClient}. Calling {@link #buildAsyncClient()} constructs an instant of the client. * *

* The client requires credentials or a connection string to perform operations against Azure Event Hubs. Setting * credentials by using {@link #connectionString(String)}, {@link #connectionString(String, String)}, or {@link - * #credential(String, String, TokenCredential)}, is required in order to construct an {@link EventHubClient}. + * #credential(String, String, TokenCredential)}, is required in order to construct an {@link EventHubAsyncClient}. *

* - *

Creating an {@link EventHubClient} using Event Hubs namespace connection string

+ *

Creating an {@link EventHubAsyncClient} using Event Hubs namespace connection string

* * {@codesnippet com.azure.messaging.eventhubs.eventhubclientbuilder.connectionString#string-string} * - *

Creating an {@link EventHubClient} using Event Hub instance connection string

+ *

Creating an {@link EventHubAsyncClient} using Event Hub instance connection string

* * {@codesnippet com.azure.messaging.eventhubs.eventhubclientbuilder.connectionstring#string} * - *

Creating an {@link EventHubClient} using Event Hub with no {@link Retry}, different timeout and new + *

Creating an {@link EventHubAsyncClient} using Event Hub with no {@link Retry}, different timeout and new * Scheduler

* * {@codesnippet com.azure.messaging.eventhubs.eventhubclientbuilder.retry-timeout-scheduler} * - * @see EventHubClient + * @see EventHubAsyncClient */ +@ServiceClientBuilder(serviceClients = EventHubAsyncClient.class) public class EventHubClientBuilder { private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; @@ -151,10 +155,10 @@ public EventHubClientBuilder connectionString(String connectionString, String ev /** * Sets the configuration store that is used during construction of the service client. * - * If not specified, the default configuration store is used to configure the {@link EventHubClient}. Use {@link + * If not specified, the default configuration store is used to configure the {@link EventHubAsyncClient}. Use {@link * Configuration#NONE} to bypass using configuration settings during construction. * - * @param configuration The configuration store used to configure the {@link EventHubClient}. + * @param configuration The configuration store used to configure the {@link EventHubAsyncClient}. * @return The updated {@link EventHubClientBuilder} object. */ public EventHubClientBuilder configuration(Configuration configuration) { @@ -191,7 +195,7 @@ public EventHubClientBuilder credential(String host, String eventHubPath, TokenC } /** - * Sets the proxy configuration to use for {@link EventHubClient}. When a proxy is configured, {@link + * Sets the proxy configuration to use for {@link EventHubAsyncClient}. When a proxy is configured, {@link * TransportType#AMQP_WEB_SOCKETS} must be used for the transport type. * * @param proxyConfiguration The proxy configuration to use. @@ -228,7 +232,7 @@ public EventHubClientBuilder transportType(TransportType transport) { } /** - * Sets the default operation timeout for operations performed using {@link EventHubClient} and {@link + * Sets the default operation timeout for operations performed using {@link EventHubAsyncClient} and {@link * EventHubConsumer} such as starting the communication link with the service and sending messages. * * @param timeout Duration for operation timeout. @@ -240,7 +244,7 @@ public EventHubClientBuilder timeout(Duration timeout) { } /** - * Sets the retry policy for {@link EventHubClient}. If not specified, {@link Retry#getDefaultRetry()} is used. + * Sets the retry policy for {@link EventHubAsyncClient}. If not specified, {@link Retry#getDefaultRetry()} is used. * * @param retry The retry policy to use. * @return The updated {@link EventHubClientBuilder} object. @@ -251,8 +255,8 @@ public EventHubClientBuilder retry(Retry retry) { } /** - * Creates a new {@link EventHubClient} based on options set on this builder. Every time {@code buildAsyncClient()} - * is invoked, a new instance of {@link EventHubClient} is created. + * Creates a new {@link EventHubAsyncClient} based on options set on this builder. Every time {@code buildAsyncClient()} + * is invoked, a new instance of {@link EventHubAsyncClient} is created. * *

* The following options are used if ones are not specified in the builder: @@ -269,12 +273,12 @@ public EventHubClientBuilder retry(Retry retry) { *

  • If no scheduler is specified, an {@link Schedulers#elastic() elastic scheduler} is used.
  • * * - * @return A new {@link EventHubClient} instance with all the configured options. + * @return A new {@link EventHubAsyncClient} instance with all the configured options. * @throws IllegalArgumentException if the credentials have not been set using either {@link * #connectionString(String)} or {@link #credential(String, String, TokenCredential)}. Or, if a proxy is * specified but the transport type is not {@link TransportType#AMQP_WEB_SOCKETS web sockets}. */ - public EventHubClient buildAsyncClient() { + public EventHubAsyncClient buildAsyncClient() { configuration = configuration == null ? ConfigurationManager.getConfiguration().clone() : configuration; if (credentials == null) { @@ -320,7 +324,7 @@ public EventHubClient buildAsyncClient() { final ConnectionOptions parameters = new ConnectionOptions(host, eventHubPath, credentials, authorizationType, timeout, transport, retry, proxyConfiguration, scheduler); - return new EventHubClient(parameters, provider, handlerProvider); + return new EventHubAsyncClient(parameters, provider, handlerProvider); } private ProxyConfiguration getDefaultProxyConfiguration(Configuration configuration) { diff --git a/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java index e66e509a26449..19bdefe5663c8 100644 --- a/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java +++ b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java @@ -4,7 +4,10 @@ package com.azure.messaging.eventhubs; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.implementation.annotation.Immutable; import com.azure.messaging.eventhubs.implementation.AmqpReceiveLink; +import com.azure.messaging.eventhubs.models.EventHubConsumerOptions; +import com.azure.messaging.eventhubs.models.EventPosition; import reactor.core.publisher.BaseSubscriber; import reactor.core.publisher.EmitterProcessor; import reactor.core.publisher.Flux; @@ -41,9 +44,10 @@ * * {@codesnippet com.azure.messaging.eventhubs.eventhubconsumer.receiveBackpressure} * - * @see EventHubClient#createConsumer(String, String, EventPosition) - * @see EventHubClient#createConsumer(String, String, EventPosition, EventHubConsumerOptions) + * @see EventHubAsyncClient#createConsumer(String, String, EventPosition) + * @see EventHubAsyncClient#createConsumer(String, String, EventPosition, EventHubConsumerOptions) */ +@Immutable public class EventHubConsumer implements Closeable { private static final AtomicReferenceFieldUpdater RECEIVE_LINK_FIELD_UPDATER = AtomicReferenceFieldUpdater.newUpdater(EventHubConsumer.class, AmqpReceiveLink.class, "receiveLink"); @@ -127,8 +131,8 @@ public void close() throws IOException { } /** - * Begin consuming events until there are no longer any subscribers, or the parent {@link EventHubClient#close() - * EventHubClient.close()} is called. + * Begin consuming events until there are no longer any subscribers, or the parent {@link EventHubAsyncClient#close() + * EventHubAsyncClient.close()} is called. * *

    Consuming events from Event Hub

    * diff --git a/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducer.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducer.java index 03989de29869b..e15cbebd17675 100644 --- a/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducer.java +++ b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducer.java @@ -5,11 +5,14 @@ import com.azure.core.amqp.exception.AmqpException; import com.azure.core.amqp.exception.ErrorCondition; +import com.azure.core.implementation.annotation.Immutable; import com.azure.core.implementation.util.ImplUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.implementation.AmqpSendLink; import com.azure.messaging.eventhubs.implementation.ErrorContextProvider; import com.azure.messaging.eventhubs.implementation.EventDataUtil; +import com.azure.messaging.eventhubs.models.EventHubProducerOptions; +import com.azure.messaging.eventhubs.models.SendOptions; import org.apache.qpid.proton.message.Message; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; @@ -74,8 +77,9 @@ * * {@codesnippet com.azure.messaging.eventhubs.eventhubproducer.send#publisher-sendOptions} * - * @see EventHubClient#createProducer() + * @see EventHubAsyncClient#createProducer() */ +@Immutable public class EventHubProducer implements Closeable { /** * The default maximum allowable size, in bytes, for a batch to be sent. @@ -276,11 +280,11 @@ private static class EventDataCollector implements Collector client.createConsumer(EventHubClient.DEFAULT_CONSUMER_GROUP_NAME, id, EventPosition.latest())); + .map(id -> client.createConsumer(EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME, id, EventPosition.latest())); final List consumerSubscriptions = consumers.map(consumer -> { return consumer.receive().subscribe(event -> { diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientBuilderTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientBuilderTest.java index 3070ed065883b..b8ab75b9237b2 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientBuilderTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientBuilderTest.java @@ -5,6 +5,8 @@ import com.azure.core.amqp.TransportType; import com.azure.messaging.eventhubs.implementation.ClientConstants; +import com.azure.messaging.eventhubs.models.ProxyAuthenticationType; +import com.azure.messaging.eventhubs.models.ProxyConfiguration; import org.junit.Assert; import org.junit.Test; @@ -39,7 +41,7 @@ public void missingConnectionString() { @Test public void defaultProxyConfigurationBuilder() { final EventHubClientBuilder builder = new EventHubClientBuilder(); - final EventHubClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient(); + final EventHubAsyncClient client = builder.connectionString(CORRECT_CONNECTION_STRING).buildAsyncClient(); Assert.assertNotNull(client); } diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientIntegrationTest.java index 7d3deba988ecf..ba80afd99c381 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientIntegrationTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientIntegrationTest.java @@ -6,6 +6,9 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.implementation.ApiTestBase; import com.azure.messaging.eventhubs.implementation.ReactorHandlerProvider; +import com.azure.messaging.eventhubs.models.EventHubConsumerOptions; +import com.azure.messaging.eventhubs.models.EventHubProducerOptions; +import com.azure.messaging.eventhubs.models.EventPosition; import org.junit.Assert; import org.junit.Ignore; import org.junit.Rule; @@ -24,16 +27,16 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static com.azure.messaging.eventhubs.EventHubClient.DEFAULT_CONSUMER_GROUP_NAME; +import static com.azure.messaging.eventhubs.EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME; import static java.nio.charset.StandardCharsets.UTF_8; /** - * Tests scenarios on {@link EventHubClient}. + * Tests scenarios on {@link EventHubAsyncClient}. */ public class EventHubClientIntegrationTest extends ApiTestBase { private static final String PARTITION_ID = "0"; - private EventHubClient client; + private EventHubAsyncClient client; @Rule public TestName testName = new TestName(); @@ -50,7 +53,7 @@ protected String testName() { @Override protected void beforeTest() { ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(getReactorProvider()); - client = new EventHubClient(getConnectionOptions(), getReactorProvider(), handlerProvider); + client = new EventHubAsyncClient(getConnectionOptions(), getReactorProvider(), handlerProvider); } @Override @@ -60,7 +63,7 @@ protected void afterTest() { @Test(expected = NullPointerException.class) public void nullConstructor() throws NullPointerException { - new EventHubClient(null, null, null); + new EventHubAsyncClient(null, null, null); } /** @@ -146,9 +149,9 @@ public void parallelEventHubClients() throws InterruptedException { }); final CountDownLatch countDownLatch = new CountDownLatch(numberOfClients); - final EventHubClient[] clients = new EventHubClient[numberOfClients]; + final EventHubAsyncClient[] clients = new EventHubAsyncClient[numberOfClients]; for (int i = 0; i < numberOfClients; i++) { - clients[i] = new EventHubClient(getConnectionOptions(), getReactorProvider(), new ReactorHandlerProvider(getReactorProvider())); + clients[i] = new EventHubAsyncClient(getConnectionOptions(), getReactorProvider(), new ReactorHandlerProvider(getReactorProvider())); } final EventHubProducer producer = clients[0].createProducer(new EventHubProducerOptions().partitionId(PARTITION_ID)); @@ -156,7 +159,7 @@ public void parallelEventHubClients() throws InterruptedException { final Disposable.Composite subscriptions = Disposables.composite(); try { - for (final EventHubClient hubClient : clients) { + for (final EventHubAsyncClient hubClient : clients) { final EventHubConsumer consumer = hubClient.createConsumer(DEFAULT_CONSUMER_GROUP_NAME, PARTITION_ID, EventPosition.latest()); consumers.add(consumer); diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientMetadataIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientMetadataIntegrationTest.java index 26a8499b9fbee..7758f5d9c0aae 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientMetadataIntegrationTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubClientMetadataIntegrationTest.java @@ -14,6 +14,7 @@ import com.azure.messaging.eventhubs.implementation.ConnectionOptions; import com.azure.messaging.eventhubs.implementation.ConnectionStringProperties; import com.azure.messaging.eventhubs.implementation.ReactorHandlerProvider; +import com.azure.messaging.eventhubs.models.ProxyConfiguration; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; @@ -31,7 +32,7 @@ */ public class EventHubClientMetadataIntegrationTest extends ApiTestBase { private final String[] expectedPartitionIds = new String[]{"0", "1"}; - private EventHubClient client; + private EventHubAsyncClient client; private ReactorHandlerProvider handlerProvider; private String eventHubPath; @@ -53,7 +54,7 @@ protected void beforeTest() { eventHubPath = getConnectionOptions().eventHubPath(); handlerProvider = new ReactorHandlerProvider(getReactorProvider()); - client = new EventHubClient(getConnectionOptions(), getReactorProvider(), handlerProvider); + client = new EventHubAsyncClient(getConnectionOptions(), getReactorProvider(), handlerProvider); } @Override @@ -134,7 +135,7 @@ public void getPartitionPropertiesInvalidToken() throws InvalidKeyException, NoS final ConnectionOptions connectionOptions = new ConnectionOptions(original.endpoint().getHost(), original.eventHubPath(), badTokenProvider, getAuthorizationType(), TIMEOUT, TransportType.AMQP, Retry.getNoRetry(), ProxyConfiguration.SYSTEM_DEFAULTS, getConnectionOptions().scheduler()); - final EventHubClient client = new EventHubClient(connectionOptions, getReactorProvider(), handlerProvider); + final EventHubAsyncClient client = new EventHubAsyncClient(connectionOptions, getReactorProvider(), handlerProvider); // Act & Assert StepVerifier.create(client.getProperties()) @@ -159,7 +160,7 @@ public void getPartitionPropertiesNonExistentHub() { final ConnectionOptions connectionOptions = new ConnectionOptions(original.endpoint().getHost(), "invalid-event-hub", getTokenCredential(), getAuthorizationType(), TIMEOUT, TransportType.AMQP, Retry.getNoRetry(), ProxyConfiguration.SYSTEM_DEFAULTS, getConnectionOptions().scheduler()); - final EventHubClient client = new EventHubClient(connectionOptions, getReactorProvider(), handlerProvider); + final EventHubAsyncClient client = new EventHubAsyncClient(connectionOptions, getReactorProvider(), handlerProvider); // Act & Assert StepVerifier.create(client.getPartitionIds()) diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerIntegrationTest.java index dd512717b464d..46c57aaca1c6b 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerIntegrationTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerIntegrationTest.java @@ -11,6 +11,10 @@ import com.azure.messaging.eventhubs.implementation.ConnectionOptions; import com.azure.messaging.eventhubs.implementation.ConnectionStringProperties; import com.azure.messaging.eventhubs.implementation.ReactorHandlerProvider; +import com.azure.messaging.eventhubs.models.EventHubConsumerOptions; +import com.azure.messaging.eventhubs.models.EventHubProducerOptions; +import com.azure.messaging.eventhubs.models.EventPosition; +import com.azure.messaging.eventhubs.models.ProxyConfiguration; import org.junit.Assert; import org.junit.Ignore; import org.junit.Rule; @@ -31,7 +35,7 @@ import java.util.function.Consumer; import static com.azure.core.amqp.exception.ErrorCondition.RESOURCE_LIMIT_EXCEEDED; -import static com.azure.messaging.eventhubs.EventHubClient.DEFAULT_CONSUMER_GROUP_NAME; +import static com.azure.messaging.eventhubs.EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME; import static java.nio.charset.StandardCharsets.UTF_8; /** @@ -46,7 +50,7 @@ public class EventHubConsumerIntegrationTest extends ApiTestBase { // The maximum number of receivers on a partition + consumer group is 5. private static final int MAX_NUMBER_OF_CONSUMERS = 5; - private EventHubClient client; + private EventHubAsyncClient client; public EventHubConsumerIntegrationTest() { super(new ClientLogger(EventHubConsumerIntegrationTest.class)); @@ -68,7 +72,7 @@ protected void beforeTest() { properties.eventHubPath(), getTokenCredential(), getAuthorizationType(), TIMEOUT, TransportType.AMQP, Retry.getNoRetry(), ProxyConfiguration.SYSTEM_DEFAULTS, Schedulers.newSingle("single-threaded")); - client = new EventHubClient(connectionOptions, getReactorProvider(), handlerProvider); + client = new EventHubAsyncClient(connectionOptions, getReactorProvider(), handlerProvider); } @Override @@ -77,7 +81,7 @@ protected void afterTest() { } /** - * Tests that the same EventHubClient can create multiple EventHubConsumers listening to different partitions. + * Tests that the same EventHubAsyncClient can create multiple EventHubConsumers listening to different partitions. */ @Test public void parallelCreationOfReceivers() { diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerTest.java index 8b98ced4b4fb1..3271864c39cea 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerTest.java @@ -7,6 +7,7 @@ import com.azure.core.amqp.Retry; import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.implementation.AmqpReceiveLink; +import com.azure.messaging.eventhubs.models.EventHubConsumerOptions; import org.apache.qpid.proton.message.Message; import org.junit.After; import org.junit.Assert; diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerTest.java index 58bfeb2f82961..56e44f777736f 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerTest.java @@ -7,6 +7,8 @@ import com.azure.core.amqp.exception.AmqpException; import com.azure.core.amqp.exception.ErrorCondition; import com.azure.messaging.eventhubs.implementation.AmqpSendLink; +import com.azure.messaging.eventhubs.models.EventHubProducerOptions; +import com.azure.messaging.eventhubs.models.SendOptions; import org.apache.qpid.proton.amqp.messaging.Section; import org.apache.qpid.proton.message.Message; import org.junit.After; @@ -74,7 +76,7 @@ public void sendMultipleMessages() { when(sendLink.send(anyList())).thenReturn(Mono.empty()); final int maxMessageSize = 16 * 1024; - final SendOptions options = new SendOptions().maximumSizeInBytes(maxMessageSize); + final SendOptions options = new SendOptions(); final EventHubProducerOptions producerOptions = new EventHubProducerOptions().retry(Retry.getNoRetry()).timeout(Duration.ofSeconds(30)); final EventHubProducer producer = new EventHubProducer(Mono.just(sendLink), producerOptions); @@ -101,8 +103,7 @@ public void sendSingleMessage() { when(sendLink.send(any(Message.class))).thenReturn(Mono.empty()); - final int maxMessageSize = 16 * 1024; - final SendOptions options = new SendOptions().maximumSizeInBytes(maxMessageSize); + final SendOptions options = new SendOptions(); final EventHubProducerOptions producerOptions = new EventHubProducerOptions().retry(Retry.getNoRetry()).timeout(Duration.ofSeconds(30)); final EventHubProducer producer = new EventHubProducer(Mono.just(sendLink), producerOptions); @@ -154,14 +155,13 @@ public void partitionProducerCannotSendWithPartitionKey() { */ @Test public void sendTooManyMessages() { - final Flux testData = Flux.range(0, 20).flatMap(number -> { + final Flux testData = Flux.range(0, 500).flatMap(number -> { final EventData data = new EventData(CONTENTS.getBytes(UTF_8)); return Flux.just(data); }); final AmqpSendLink sendLink = mock(AmqpSendLink.class); - final int maxMessageSize = 16 * 1024; - final SendOptions options = new SendOptions().maximumSizeInBytes(maxMessageSize); + final SendOptions options = new SendOptions(); final EventHubProducerOptions producerOptions = new EventHubProducerOptions().retry(Retry.getNoRetry()).timeout(Duration.ofSeconds(30)); final EventHubProducer producer = new EventHubProducer(Mono.just(sendLink), producerOptions); diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java index d9337acf5435b..04a8f19aab2dd 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java @@ -6,6 +6,8 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.implementation.ApiTestBase; import com.azure.messaging.eventhubs.implementation.ReactorHandlerProvider; +import com.azure.messaging.eventhubs.models.EventHubProducerOptions; +import com.azure.messaging.eventhubs.models.EventPosition; import org.junit.Assert; import org.junit.Ignore; import org.junit.Rule; @@ -25,7 +27,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; -import static com.azure.messaging.eventhubs.EventHubClient.DEFAULT_CONSUMER_GROUP_NAME; +import static com.azure.messaging.eventhubs.EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME; import static com.azure.messaging.eventhubs.TestUtils.isMatchingEvent; import static java.nio.charset.StandardCharsets.UTF_8; @@ -45,7 +47,7 @@ public class EventPositionIntegrationTest extends ApiTestBase { private static final String MESSAGE_TRACKING_VALUE = UUID.randomUUID().toString(); private static final AtomicReference MESSAGES_PUSHED_INSTANT = new AtomicReference<>(); - private EventHubClient client; + private EventHubAsyncClient client; public EventPositionIntegrationTest() { super(new ClientLogger(EventPositionIntegrationTest.class)); @@ -64,7 +66,7 @@ protected void beforeTest() { skipIfNotRecordMode(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(getReactorProvider()); - client = new EventHubClient(getConnectionOptions(), getReactorProvider(), handlerProvider); + client = new EventHubAsyncClient(getConnectionOptions(), getReactorProvider(), handlerProvider); setupEventTestData(client); } @@ -330,7 +332,7 @@ public void receiveMessageFromSequenceNumberNonInclusive() { * When we run this test, we check if there have been events already pushed to the partition, if not, we push some * events there. */ - private void setupEventTestData(EventHubClient client) { + private void setupEventTestData(EventHubAsyncClient client) { if (HAS_PUSHED_EVENTS.getAndSet(true)) { logger.info("Already pushed events to partition. Skipping."); return; diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java index d8d47b64accaf..c3aefcb3c4ebf 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java @@ -8,6 +8,8 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.implementation.ApiTestBase; import com.azure.messaging.eventhubs.implementation.ReactorHandlerProvider; +import com.azure.messaging.eventhubs.models.EventHubProducerOptions; +import com.azure.messaging.eventhubs.models.EventPosition; import org.apache.qpid.proton.Proton; import org.apache.qpid.proton.amqp.Binary; import org.apache.qpid.proton.amqp.Symbol; @@ -36,7 +38,7 @@ public class InteropAmqpPropertiesTest extends ApiTestBase { private static final String PARTITION_ID = "0"; private static final String PAYLOAD = "test-message"; - private EventHubClient client; + private EventHubAsyncClient client; private EventHubProducer producer; private EventHubConsumer consumer; @@ -55,11 +57,11 @@ protected String testName() { @Override protected void beforeTest() { final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(getReactorProvider()); - client = new EventHubClient(getConnectionOptions(), getReactorProvider(), handlerProvider); + client = new EventHubAsyncClient(getConnectionOptions(), getReactorProvider(), handlerProvider); final EventHubProducerOptions producerOptions = new EventHubProducerOptions().partitionId(PARTITION_ID).retry(Retry.getNoRetry()).timeout(Duration.ofSeconds(30)); producer = client.createProducer(producerOptions); - consumer = client.createConsumer(EventHubClient.DEFAULT_CONSUMER_GROUP_NAME, PARTITION_ID, EventPosition.latest()); + consumer = client.createConsumer(EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME, PARTITION_ID, EventPosition.latest()); } @Override diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SendOptionsTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SendOptionsTest.java index 141ee2e961fd6..3905cfb8fcc24 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SendOptionsTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SendOptionsTest.java @@ -3,6 +3,7 @@ package com.azure.messaging.eventhubs; +import com.azure.messaging.eventhubs.models.SendOptions; import org.junit.Assert; import org.junit.Test; @@ -15,7 +16,7 @@ public class SendOptionsTest { public void createDefault() { SendOptions options = new SendOptions(); - Assert.assertEquals(EventHubProducer.MAX_MESSAGE_LENGTH_BYTES, options.maximumSizeInBytes()); + // Assert.assertEquals(EventHubProducer.MAX_MESSAGE_LENGTH_BYTES, options.maximumSizeInBytes()); Assert.assertNull(options.partitionKey()); } @@ -27,9 +28,9 @@ public void setMaximumSize() { int size = 1024; SendOptions options = new SendOptions(); - options.maximumSizeInBytes(size); + // options.maximumSizeInBytes(size); - Assert.assertEquals(size, options.maximumSizeInBytes()); + // Assert.assertEquals(size, options.maximumSizeInBytes()); Assert.assertNull(options.partitionKey()); } @@ -43,7 +44,7 @@ public void setPartitionKey() { options.partitionKey(partitionKey); - Assert.assertEquals(EventHubProducer.MAX_MESSAGE_LENGTH_BYTES, options.maximumSizeInBytes()); + // Assert.assertEquals(EventHubProducer.MAX_MESSAGE_LENGTH_BYTES, options.maximumSizeInBytes()); Assert.assertEquals(partitionKey, options.partitionKey()); } @@ -55,18 +56,19 @@ public void cloneIdentical() { // Arrange String partitionKey = "My partition key"; int size = 800; - SendOptions options = new SendOptions().partitionKey(partitionKey).maximumSizeInBytes(size); + // SendOptions options = new SendOptions().partitionKey(partitionKey).maximumSizeInBytes(size); + SendOptions options = new SendOptions().partitionKey(partitionKey); // Act SendOptions clone = options.clone(); // Assert Assert.assertNotSame(clone, options); - Assert.assertEquals(size, options.maximumSizeInBytes()); + // Assert.assertEquals(size, options.maximumSizeInBytes()); Assert.assertEquals(partitionKey, options.partitionKey()); Assert.assertEquals(partitionKey, clone.partitionKey()); - Assert.assertEquals(size, clone.maximumSizeInBytes()); + // Assert.assertEquals(size, clone.maximumSizeInBytes()); } @@ -82,18 +84,19 @@ public void cloneModifyContents() { String partitionKey = "A new partition key"; int size = 24; - SendOptions options = new SendOptions().partitionKey(originalPartitionKey).maximumSizeInBytes(originalSize); + // SendOptions options = new SendOptions().partitionKey(originalPartitionKey).maximumSizeInBytes(originalSize); + SendOptions options = new SendOptions().partitionKey(originalPartitionKey); SendOptions clone = options.clone(); // Act - clone.partitionKey(partitionKey) - .maximumSizeInBytes(size); + // clone.partitionKey(partitionKey).maximumSizeInBytes(size); + clone.partitionKey(partitionKey); // Assert Assert.assertEquals(partitionKey, clone.partitionKey()); - Assert.assertEquals(size, clone.maximumSizeInBytes()); + // Assert.assertEquals(size, clone.maximumSizeInBytes()); - Assert.assertEquals(originalSize, options.maximumSizeInBytes()); + // Assert.assertEquals(originalSize, options.maximumSizeInBytes()); Assert.assertEquals(originalPartitionKey, options.partitionKey()); } } diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java index a292d9b2be827..80d1c7548cb26 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java @@ -7,6 +7,8 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.implementation.ApiTestBase; import com.azure.messaging.eventhubs.implementation.ReactorHandlerProvider; +import com.azure.messaging.eventhubs.models.EventHubConsumerOptions; +import com.azure.messaging.eventhubs.models.EventPosition; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; @@ -24,8 +26,10 @@ */ public class SetPrefetchCountTest extends ApiTestBase { private static final String PARTITION_ID = "0"; + // Default number of events to fetch when creating the consumer. + private static final int DEFAULT_PREFETCH_COUNT = 500; - private EventHubClient client; + private EventHubAsyncClient client; private EventHubProducer producer; private EventHubConsumer consumer; @@ -46,7 +50,7 @@ protected void beforeTest() { skipIfNotRecordMode(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(getReactorProvider()); - client = new EventHubClient(getConnectionOptions(), getReactorProvider(), handlerProvider); + client = new EventHubAsyncClient(getConnectionOptions(), getReactorProvider(), handlerProvider); producer = client.createProducer(); } @@ -63,13 +67,13 @@ public void setLargePrefetchCount() throws InterruptedException { // Arrange // Since we cannot test receiving very large prefetch like 10000 in a unit test, DefaultPrefetchCount * 3 was // chosen - final int eventCount = EventHubConsumerOptions.DEFAULT_PREFETCH_COUNT * 3; + final int eventCount = DEFAULT_PREFETCH_COUNT * 3; final CountDownLatch countDownLatch = new CountDownLatch(eventCount); final EventHubConsumerOptions options = new EventHubConsumerOptions() .retry(Retry.getDefaultRetry()) .prefetchCount(2000); - consumer = client.createConsumer(EventHubClient.DEFAULT_CONSUMER_GROUP_NAME, PARTITION_ID, + consumer = client.createConsumer(EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME, PARTITION_ID, EventPosition.latest(), options); final Disposable subscription = consumer.receive() @@ -99,7 +103,7 @@ public void setSmallPrefetchCount() throws InterruptedException { final CountDownLatch countDownLatch = new CountDownLatch(eventCount); final EventHubConsumerOptions options = new EventHubConsumerOptions().prefetchCount(11); - consumer = client.createConsumer(EventHubClient.DEFAULT_CONSUMER_GROUP_NAME, PARTITION_ID, + consumer = client.createConsumer(EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME, PARTITION_ID, EventPosition.latest(), options); final Disposable subscription = consumer.receive() diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ApiTestBase.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ApiTestBase.java index 544c105838d2e..c6dfeec5ff7e3 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ApiTestBase.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ApiTestBase.java @@ -11,7 +11,7 @@ import com.azure.core.test.TestMode; import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.EventHubSharedAccessKeyCredential; -import com.azure.messaging.eventhubs.ProxyConfiguration; +import com.azure.messaging.eventhubs.models.ProxyConfiguration; import org.apache.qpid.proton.reactor.Reactor; import org.apache.qpid.proton.reactor.Selectable; import org.junit.After; diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionTest.java index 449fe21e82b76..e631a76f3fb96 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionTest.java @@ -8,7 +8,7 @@ import com.azure.core.amqp.Retry; import com.azure.core.amqp.TransportType; import com.azure.core.credentials.TokenCredential; -import com.azure.messaging.eventhubs.ProxyConfiguration; +import com.azure.messaging.eventhubs.models.ProxyConfiguration; import com.azure.messaging.eventhubs.implementation.handler.ConnectionHandler; import com.azure.messaging.eventhubs.implementation.handler.SessionHandler; import org.apache.qpid.proton.amqp.Symbol; diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerOptionsTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/models/EventHubConsumerOptionsTest.java similarity index 98% rename from sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerOptionsTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/models/EventHubConsumerOptionsTest.java index a7ee3620c1e50..c9b240487f2f9 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerOptionsTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/models/EventHubConsumerOptionsTest.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.messaging.eventhubs; +package com.azure.messaging.eventhubs.models; import org.junit.Assert; import org.junit.Test; diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerOptionsTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/models/EventHubProducerOptionsTest.java similarity index 96% rename from sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerOptionsTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/models/EventHubProducerOptionsTest.java index 12db5b6cc92da..eba44d5b987f0 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerOptionsTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/models/EventHubProducerOptionsTest.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.messaging.eventhubs; +package com.azure.messaging.eventhubs.models; import com.azure.core.amqp.ExponentialRetry; import com.azure.core.amqp.Retry; diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyConfigurationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/models/ProxyConfigurationTest.java similarity index 97% rename from sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyConfigurationTest.java rename to sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/models/ProxyConfigurationTest.java index 5ab9fc2ca0029..f34722f9127b7 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyConfigurationTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/models/ProxyConfigurationTest.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.messaging.eventhubs; +package com.azure.messaging.eventhubs.models; import org.junit.Assert; import org.junit.Test; @@ -14,7 +14,7 @@ import java.net.InetSocketAddress; import java.net.Proxy; -import static com.azure.messaging.eventhubs.ProxyConfiguration.SYSTEM_DEFAULTS; +import static com.azure.messaging.eventhubs.models.ProxyConfiguration.SYSTEM_DEFAULTS; @RunWith(Theories.class) public class ProxyConfigurationTest { From 1ec9438d210a125ec9b265c121a9b70c217e5922 Mon Sep 17 00:00:00 2001 From: Gauri Prasad <51212198+gapra-msft@users.noreply.github.com> Date: Fri, 12 Jul 2019 11:57:48 -0700 Subject: [PATCH 77/85] Storage SAS implementation (#4404) * SAS implementation * Fixed some minor formatting issues * Fixed checkstyle problems and test issue --- .../azure/storage/blob/BlobAsyncClient.java | 259 ++++ .../com/azure/storage/blob/BlobClient.java | 207 ++++ .../com/azure/storage/blob/Constants.java | 15 + .../storage/blob/ContainerAsyncClient.java | 231 ++++ .../azure/storage/blob/ContainerClient.java | 188 +++ .../storage/blob/SASQueryParameters.java | 4 +- .../blob/ServiceSASSignatureValues.java | 182 +-- .../storage/blob/StorageAsyncClient.java | 70 ++ .../com/azure/storage/blob/StorageClient.java | 49 + .../java/com/azure/storage/blob/Utility.java | 23 + .../credentials/SASTokenCredential.java | 96 +- .../policy/SharedKeyCredentialPolicy.java | 9 + .../com/azure/storage/blob/SASTest.groovy | 1079 +++++++++++++++++ 13 files changed, 2315 insertions(+), 97 deletions(-) create mode 100644 storage/client/blob/src/test/java/com/azure/storage/blob/SASTest.groovy diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/BlobAsyncClient.java b/storage/client/blob/src/main/java/com/azure/storage/blob/BlobAsyncClient.java index 7ec72ecf30b53..5042f9e782af5 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/BlobAsyncClient.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/BlobAsyncClient.java @@ -21,6 +21,8 @@ import com.azure.storage.blob.models.ModifiedAccessConditions; import com.azure.storage.blob.models.ReliableDownloadOptions; import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.common.credentials.SharedKeyCredential; import io.netty.buffer.ByteBuf; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -35,6 +37,7 @@ import java.nio.channels.AsynchronousFileChannel; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; +import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; @@ -774,4 +777,260 @@ public Mono> getAccountInfo() { .getAccountInfo() .map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.deserializedHeaders()))); } + + /** + * Generates a user delegation SAS with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + BlobSASPermission permissions, OffsetDateTime expiryTime) { + return this.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, null /* + startTime */, null /* version */, null /*sasProtocol */, null /* ipRange */, null /* cacheControl */, null + /*contentDisposition */, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); + } + + /** + * Generates a user delegation SAS token with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, + SASProtocol sasProtocol, IPRange ipRange) { + return this.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, + version, sasProtocol, ipRange, null /* cacheControl */, null /* contentDisposition */, null /* + contentEncoding */, null /* contentLanguage */, null /* contentType */); + } + + /** + * Generates a user delegation SAS token with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * @param cacheControl + * An optional {@code String} cache-control header for the SAS. + * @param contentDisposition + * An optional {@code String} content-disposition header for the SAS. + * @param contentEncoding + * An optional {@code String} content-encoding header for the SAS. + * @param contentLanguage + * An optional {@code String} content-language header for the SAS. + * @param contentType + * An optional {@code String} content-type header for the SAS. + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, + SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, + String contentEncoding, String contentLanguage, String contentType) { + + ServiceSASSignatureValues serviceSASSignatureValues = new ServiceSASSignatureValues(version, sasProtocol, + startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange, null /* identifier*/, + cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); + + ServiceSASSignatureValues values = configureServiceSASSignatureValues(serviceSASSignatureValues, accountName); + + SASQueryParameters sasQueryParameters = values.generateSASQueryParameters(userDelegationKey); + + return sasQueryParameters.encode(); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(BlobSASPermission permissions, OffsetDateTime expiryTime) { + return this.generateSAS(null, permissions, expiryTime, null /* startTime */, /* identifier */ null /* + version */, null /* sasProtocol */, null /* ipRange */, null /* cacheControl */, null /* contentLanguage*/, + null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier) { + return this.generateSAS(identifier, null /* permissions */, null /* expiryTime */, null /* startTime */, + null /* version */, null /* sasProtocol */, null /* ipRange */, null /* cacheControl */, null /* + contentLanguage*/, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, + OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { + return this.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange, null + /* cacheControl */, null /* contentLanguage*/, null /* contentEncoding */, null /* contentLanguage */, + null /* contentType */); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * @param cacheControl + * An optional {@code String} cache-control header for the SAS. + * @param contentDisposition + * An optional {@code String} content-disposition header for the SAS. + * @param contentEncoding + * An optional {@code String} content-encoding header for the SAS. + * @param contentLanguage + * An optional {@code String} content-language header for the SAS. + * @param contentType + * An optional {@code String} content-type header for the SAS. + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, + OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, + String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { + + ServiceSASSignatureValues serviceSASSignatureValues = new ServiceSASSignatureValues(version, sasProtocol, + startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange, identifier, + cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); + + SharedKeyCredential sharedKeyCredential = + Utility.getSharedKeyCredential(this.blobAsyncRawClient.azureBlobStorage.httpPipeline()); + + Utility.assertNotNull("sharedKeyCredential", sharedKeyCredential); + + ServiceSASSignatureValues values = configureServiceSASSignatureValues(serviceSASSignatureValues, + sharedKeyCredential.accountName()); + + SASQueryParameters sasQueryParameters = values.generateSASQueryParameters(sharedKeyCredential); + + return sasQueryParameters.encode(); + } + + /** + * Sets serviceSASSignatureValues parameters dependent on the current blob type + */ + ServiceSASSignatureValues configureServiceSASSignatureValues(ServiceSASSignatureValues serviceSASSignatureValues, + String accountName) { + + // Set canonical name + serviceSASSignatureValues.canonicalName(this.blobAsyncRawClient.azureBlobStorage.url(), accountName); + + // Set snapshotId + serviceSASSignatureValues.snapshotId(getSnapshotId()); + + // Set resource + if (isSnapshot()) { + serviceSASSignatureValues.resource(Constants.UrlConstants.SAS_BLOB_SNAPSHOT_CONSTANT); + } else { + serviceSASSignatureValues.resource(Constants.UrlConstants.SAS_BLOB_CONSTANT); + } + + return serviceSASSignatureValues; + } + + /** + * Gets the snapshotId for a blob resource + * + * @return + * A string that represents the snapshotId of the snapshot blob + */ + public String getSnapshotId() { + return this.blobAsyncRawClient.snapshot; + } + + /** + * Determines if a blob is a snapshot + * + * @return + * A boolean that indicates if a blob is a snapshot + */ + public boolean isSnapshot() { + return this.blobAsyncRawClient.snapshot != null; + } } diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/BlobClient.java b/storage/client/blob/src/main/java/com/azure/storage/blob/BlobClient.java index f47c3cf6d7830..21a2212713f5c 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/BlobClient.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/BlobClient.java @@ -16,6 +16,7 @@ import com.azure.storage.blob.models.ModifiedAccessConditions; import com.azure.storage.blob.models.ReliableDownloadOptions; import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.models.UserDelegationKey; import reactor.core.publisher.Mono; import java.io.IOException; @@ -23,6 +24,7 @@ import java.io.UncheckedIOException; import java.net.URL; import java.time.Duration; +import java.time.OffsetDateTime; /** * Client to a blob of any type: block, append, or page. It may only be instantiated through a {@link BlobClientBuilder} or via @@ -800,4 +802,209 @@ public Response getAccountInfo(Duration timeout) { return Utility.blockWithOptionalTimeout(response, timeout); } + + /** + * Generates a user delegation SAS token with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + BlobSASPermission permissions, OffsetDateTime expiryTime) { + return this.blobAsyncClient.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime); + } + + /** + * Generates a user delegation SAS token with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, + SASProtocol sasProtocol, IPRange ipRange) { + return this.blobAsyncClient.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, + startTime, version, sasProtocol, ipRange); + } + + /** + * Generates a user delegation SAS token with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * @param cacheControl + * An optional {@code String} cache-control header for the SAS. + * @param contentDisposition + * An optional {@code String} content-disposition header for the SAS. + * @param contentEncoding + * An optional {@code String} content-encoding header for the SAS. + * @param contentLanguage + * An optional {@code String} content-language header for the SAS. + * @param contentType + * An optional {@code String} content-type header for the SAS. + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, + SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, + String contentEncoding, String contentLanguage, String contentType) { + return this.blobAsyncClient.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, + startTime, version, sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, + contentLanguage, contentType); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(OffsetDateTime expiryTime, BlobSASPermission permissions) { + return this.blobAsyncClient.generateSAS(permissions, expiryTime); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier) { + return this.blobAsyncClient.generateSAS(identifier); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, + OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { + return this.blobAsyncClient.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, + ipRange); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * @param cacheControl + * An optional {@code String} cache-control header for the SAS. + * @param contentDisposition + * An optional {@code String} content-disposition header for the SAS. + * @param contentEncoding + * An optional {@code String} content-encoding header for the SAS. + * @param contentLanguage + * An optional {@code String} content-language header for the SAS. + * @param contentType + * An optional {@code String} content-type header for the SAS. + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, + OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, + String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { + return this.blobAsyncClient.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, + ipRange, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); + } + + /** + * Gets the snapshotId for a blob resource + * + * @return + * A string that represents the snapshotId of the snapshot blob + */ + public String getSnapshotId() { + return this.blobAsyncClient.getSnapshotId(); + } + + /** + * Determines if a blob is a snapshot + * + * @return + * A boolean that indicates if a blob is a snapshot + */ + public boolean isSnapshot() { + return this.blobAsyncClient.isSnapshot(); + } } diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/Constants.java b/storage/client/blob/src/main/java/com/azure/storage/blob/Constants.java index 653625b572c15..fa812df4b531b 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/Constants.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/Constants.java @@ -288,6 +288,21 @@ static final class UrlConstants { */ public static final String SAS_SIGNED_KEY_VERSION = "skv"; + /** + * The SAS blob constant. + */ + public static final String SAS_BLOB_CONSTANT = "b"; + + /** + * The SAS blob snapshot constant. + */ + public static final String SAS_BLOB_SNAPSHOT_CONSTANT = "bs"; + + /** + * The SAS blob snapshot constant. + */ + public static final String SAS_CONTAINER_CONSTANT = "c"; + private UrlConstants() { // Private to prevent construction. } diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/ContainerAsyncClient.java b/storage/client/blob/src/main/java/com/azure/storage/blob/ContainerAsyncClient.java index 406a7440b0c5b..f979f084ac151 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/ContainerAsyncClient.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/ContainerAsyncClient.java @@ -24,12 +24,15 @@ import com.azure.storage.blob.models.PublicAccessType; import com.azure.storage.blob.models.SignedIdentifier; import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.common.credentials.SharedKeyCredential; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.net.MalformedURLException; import java.net.URL; import java.time.Duration; +import java.time.OffsetDateTime; import java.util.List; /** @@ -878,4 +881,232 @@ public Mono> getAccountInfo() { .getAccountInfo() .map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.deserializedHeaders()))); } + + /** + * Generates a user delegation SAS with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + ContainerSASPermission permissions, OffsetDateTime expiryTime) { + return this.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, null /* + startTime */, null /* version */, null /* sasProtocol */, null /* ipRange */, null /* cacheControl */, null + /* contentDisposition */, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); + } + + /** + * Generates a user delegation SAS token with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + ContainerSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, + SASProtocol sasProtocol, IPRange ipRange) { + return this.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, + version, sasProtocol, ipRange, null /* cacheControl */, null /* contentDisposition */, null /* + contentEncoding */, null /* contentLanguage */, null /* contentType */); + } + + /** + * Generates a user delegation SAS token with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * @param cacheControl + * An optional {@code String} cache-control header for the SAS. + * @param contentDisposition + * An optional {@code String} content-disposition header for the SAS. + * @param contentEncoding + * An optional {@code String} content-encoding header for the SAS. + * @param contentLanguage + * An optional {@code String} content-language header for the SAS. + * @param contentType + * An optional {@code String} content-type header for the SAS. + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + ContainerSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, + SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, + String contentEncoding, String contentLanguage, String contentType) { + ServiceSASSignatureValues serviceSASSignatureValues = new ServiceSASSignatureValues(version, sasProtocol, + startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange, null /* identifier*/, + cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); + + ServiceSASSignatureValues values = configureServiceSASSignatureValues(serviceSASSignatureValues, accountName); + + SASQueryParameters sasQueryParameters = values.generateSASQueryParameters(userDelegationKey); + + return sasQueryParameters.encode(); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(ContainerSASPermission permissions, OffsetDateTime expiryTime) { + return this.generateSAS(null, permissions, /* identifier */ expiryTime, null /* startTime */, null /* version + */, null /* sasProtocol */, null /* ipRange */, null /* cacheControl */, null /* contentDisposition */, + null /* contentEncoding */, null /* contentLanguage */, null /*contentType*/); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier) { + return this.generateSAS(identifier, null /* permissions*/, null /* expiryTime */, null /* startTime */, null + /* version */, null /* sasProtocol */, null /* ipRange */, null /* cacheControl */, null /* + contentDisposition */, null /* contentEncoding */, null /* contentLanguage */, null /*contentType*/); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier, ContainerSASPermission permissions, OffsetDateTime expiryTime, + OffsetDateTime startTime, + String version, SASProtocol sasProtocol, IPRange ipRange) { + return this.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange, null + /* cacheControl */, null /* contentDisposition */, null /* contentEncoding */, null /* contentLanguage */, + null /*contentType*/); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * @param cacheControl + * An optional {@code String} cache-control header for the SAS. + * @param contentDisposition + * An optional {@code String} content-disposition header for the SAS. + * @param contentEncoding + * An optional {@code String} content-encoding header for the SAS. + * @param contentLanguage + * An optional {@code String} content-language header for the SAS. + * @param contentType + * An optional {@code String} content-type header for the SAS. + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier, ContainerSASPermission permissions, OffsetDateTime expiryTime, + OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, + String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { + ServiceSASSignatureValues serviceSASSignatureValues = new ServiceSASSignatureValues(version, sasProtocol, + startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange, identifier, + cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); + + SharedKeyCredential sharedKeyCredential = + Utility.getSharedKeyCredential(this.containerAsyncRawClient.azureBlobStorage.httpPipeline()); + + Utility.assertNotNull("sharedKeyCredential", sharedKeyCredential); + + ServiceSASSignatureValues values = configureServiceSASSignatureValues(serviceSASSignatureValues, + sharedKeyCredential.accountName()); + + SASQueryParameters sasQueryParameters = values.generateSASQueryParameters(sharedKeyCredential); + + return sasQueryParameters.encode(); + } + + /** + * Sets serviceSASSignatureValues parameters dependent on the current blob type + */ + private ServiceSASSignatureValues configureServiceSASSignatureValues(ServiceSASSignatureValues serviceSASSignatureValues, String accountName) { + // Set canonical name + serviceSASSignatureValues.canonicalName(this.containerAsyncRawClient.azureBlobStorage.url(), accountName); + + // Set snapshotId to null + serviceSASSignatureValues.snapshotId(null); + + // Set resource + serviceSASSignatureValues.resource(Constants.UrlConstants.SAS_CONTAINER_CONSTANT); + return serviceSASSignatureValues; + } } diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/ContainerClient.java b/storage/client/blob/src/main/java/com/azure/storage/blob/ContainerClient.java index b8c1f9d8bd09e..c9733fd3a7f61 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/ContainerClient.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/ContainerClient.java @@ -15,11 +15,13 @@ import com.azure.storage.blob.models.PublicAccessType; import com.azure.storage.blob.models.SignedIdentifier; import com.azure.storage.blob.models.StorageAccountInfo; +import com.azure.storage.blob.models.UserDelegationKey; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.net.URL; import java.time.Duration; +import java.time.OffsetDateTime; import java.util.List; /** @@ -738,4 +740,190 @@ public Response getAccountInfo(Duration timeout) { return Utility.blockWithOptionalTimeout(response, timeout); } + + /** + * Generates a user delegation SAS token with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + ContainerSASPermission permissions, OffsetDateTime expiryTime) { + return this.containerAsyncClient.generateUserDelegationSAS(userDelegationKey, accountName, permissions, + expiryTime); + } + + /** + * Generates a user delegation SAS token with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + ContainerSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, + SASProtocol sasProtocol, IPRange ipRange) { + return this.containerAsyncClient.generateUserDelegationSAS(userDelegationKey, accountName, permissions, + expiryTime, startTime, version, sasProtocol, ipRange); + } + + /** + * Generates a user delegation SAS token with the specified parameters + * + * @param userDelegationKey + * The {@code UserDelegationKey} user delegation key for the SAS + * @param accountName + * The {@code String} account name for the SAS + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * @param cacheControl + * An optional {@code String} cache-control header for the SAS. + * @param contentDisposition + * An optional {@code String} content-disposition header for the SAS. + * @param contentEncoding + * An optional {@code String} content-encoding header for the SAS. + * @param contentLanguage + * An optional {@code String} content-language header for the SAS. + * @param contentType + * An optional {@code String} content-type header for the SAS. + * + * @return + * A string that represents the SAS token + */ + public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, + ContainerSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, + SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, + String contentEncoding, String contentLanguage, String contentType) { + return this.containerAsyncClient.generateUserDelegationSAS(userDelegationKey, accountName, permissions, + expiryTime, startTime, version, sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, + contentLanguage, contentType); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(ContainerSASPermission permissions, OffsetDateTime expiryTime) { + return this.containerAsyncClient.generateSAS(permissions, expiryTime); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier) { + return this.containerAsyncClient.generateSAS(identifier); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier, ContainerSASPermission permissions, OffsetDateTime expiryTime, + OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { + return this.containerAsyncClient.generateSAS(identifier, permissions, expiryTime, startTime, version, + sasProtocol, ipRange); + } + + /** + * Generates a SAS token with the specified parameters + * + * @param identifier + * The {@code String} name of the access policy on the container this SAS references if any + * @param permissions + * The {@code ContainerSASPermissions} permission for the SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the SAS + * @param startTime + * An optional {@code OffsetDateTime} start time for the SAS + * @param version + * An optional {@code String} version for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * @param cacheControl + * An optional {@code String} cache-control header for the SAS. + * @param contentDisposition + * An optional {@code String} content-disposition header for the SAS. + * @param contentEncoding + * An optional {@code String} content-encoding header for the SAS. + * @param contentLanguage + * An optional {@code String} content-language header for the SAS. + * @param contentType + * An optional {@code String} content-type header for the SAS. + * + * @return + * A string that represents the SAS token + */ + public String generateSAS(String identifier, ContainerSASPermission permissions, OffsetDateTime expiryTime, + OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, + String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { + return this.containerAsyncClient.generateSAS(identifier, permissions, expiryTime, startTime, version, + sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); + } } diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/SASQueryParameters.java b/storage/client/blob/src/main/java/com/azure/storage/blob/SASQueryParameters.java index b6afd82addcab..cd918e636bbd4 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/SASQueryParameters.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/SASQueryParameters.java @@ -333,9 +333,7 @@ UserDelegationKey userDelegationKey() { private void tryAppendQueryParameter(StringBuilder sb, String param, Object value) { if (value != null) { - if (sb.length() == 0) { - sb.append('?'); - } else { + if (sb.length() != 0) { sb.append('&'); } sb.append(safeURLEncode(param)).append('=').append(safeURLEncode(value.toString())); diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/ServiceSASSignatureValues.java b/storage/client/blob/src/main/java/com/azure/storage/blob/ServiceSASSignatureValues.java index 7450ae699f5a4..114c28eb71209 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/ServiceSASSignatureValues.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/ServiceSASSignatureValues.java @@ -6,6 +6,8 @@ import com.azure.storage.blob.models.UserDelegationKey; import com.azure.storage.common.credentials.SharedKeyCredential; +import java.net.MalformedURLException; +import java.net.URL; import java.security.InvalidKeyException; import java.time.OffsetDateTime; @@ -40,9 +42,9 @@ final class ServiceSASSignatureValues { private IPRange ipRange; - private String containerName; + private String canonicalName; - private String blobName; + private String resource; private String snapshotId; @@ -64,6 +66,43 @@ final class ServiceSASSignatureValues { ServiceSASSignatureValues() { } + /** + * Creates an object with the specified expiry time and permissions + * @param expiryTime + * @param permissions + */ + ServiceSASSignatureValues(OffsetDateTime expiryTime, String permissions) { + this.expiryTime = expiryTime; + this.permissions = permissions; + } + + /** + * Creates an object with the specified identifier + * @param identifier + */ + ServiceSASSignatureValues(String identifier) { + this.identifier = identifier; + } + + ServiceSASSignatureValues(String version, SASProtocol sasProtocol, OffsetDateTime startTime, + OffsetDateTime expiryTime, String permission, IPRange ipRange, String identifier, String cacheControl, + String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { + if (version != null) { + this.version = version; + } + this.protocol = sasProtocol; + this.startTime = startTime; + this.expiryTime = expiryTime; + this.permissions = permission; + this.ipRange = ipRange; + this.identifier = identifier; + this.cacheControl = cacheControl; + this.contentDisposition = contentDisposition; + this.contentEncoding = contentEncoding; + this.contentLanguage = contentLanguage; + this.contentType = contentType; + } + /** * The version of the service this SAS will target. If not specified, it will default to the version targeted by the * library. @@ -159,32 +198,51 @@ public ServiceSASSignatureValues ipRange(IPRange ipRange) { } /** - * The name of the container the SAS user may access. + * The resource the SAS user may access. */ - public String containerName() { - return containerName; + public String resource() { + return resource; } /** - * The name of the container the SAS user may access. + * The resource the SAS user may access. */ - public ServiceSASSignatureValues containerName(String containerName) { - this.containerName = containerName; + public ServiceSASSignatureValues resource(String resource) { + this.resource = resource; return this; } /** - * The name of the blob the SAS user may access. + * The canonical name of the object the SAS user may access. */ - public String blobName() { - return blobName; + public String canonicalName() { + return canonicalName; } /** - * The name of the blob the SAS user may access. + * The canonical name of the object the SAS user may access. */ - public ServiceSASSignatureValues blobName(String blobName) { - this.blobName = blobName; + public ServiceSASSignatureValues canonicalName(String canonicalName) { + this.canonicalName = canonicalName; + return this; + } + + /** + * The canonical name of the object the SAS user may access. + * @throws RuntimeException If urlString is a malformed URL. + */ + public ServiceSASSignatureValues canonicalName(String urlString, String accountName) { + URL url = null; + try { + url = new URL(urlString); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + + StringBuilder canonicalName = new StringBuilder("/blob"); + canonicalName.append('/').append(accountName).append(url.getPath()); + this.canonicalName = canonicalName.toString(); + return this; } @@ -192,7 +250,7 @@ public ServiceSASSignatureValues blobName(String blobName) { * The specific snapshot the SAS user may access. */ public String snapshotId() { - return snapshotId; + return this.snapshotId; } /** @@ -309,13 +367,10 @@ public ServiceSASSignatureValues contentType(String contentType) { */ public SASQueryParameters generateSASQueryParameters(SharedKeyCredential sharedKeyCredentials) { Utility.assertNotNull("sharedKeyCredentials", sharedKeyCredentials); - assertGenerateOK(); - - String resource = getResource(); - String verifiedPermissions = getVerifiedPermissions(); + assertGenerateOK(false); // Signature is generated on the un-url-encoded values. - final String stringToSign = stringToSign(verifiedPermissions, resource, sharedKeyCredentials); + final String stringToSign = stringToSign(); String signature = null; try { @@ -336,22 +391,15 @@ public SASQueryParameters generateSASQueryParameters(SharedKeyCredential sharedK * @param delegationKey * A {@link UserDelegationKey} object used to sign the SAS values. * - * @param accountName - * Name of the account holding the resource this SAS is authorizing. - * * @return {@link SASQueryParameters} * @throws Error If the accountKey is not a valid Base64-encoded string. */ - public SASQueryParameters generateSASQueryParameters(UserDelegationKey delegationKey, String accountName) { + public SASQueryParameters generateSASQueryParameters(UserDelegationKey delegationKey) { Utility.assertNotNull("delegationKey", delegationKey); - Utility.assertNotNull("accountName", accountName); - assertGenerateOK(); - - String resource = getResource(); - String verifiedPermissions = getVerifiedPermissions(); + assertGenerateOK(true); // Signature is generated on the un-url-encoded values. - final String stringToSign = stringToSign(verifiedPermissions, resource, delegationKey, accountName); + final String stringToSign = stringToSign(delegationKey); String signature = null; try { @@ -369,70 +417,39 @@ public SASQueryParameters generateSASQueryParameters(UserDelegationKey delegatio /** * Common assertions for generateSASQueryParameters overloads. */ - private void assertGenerateOK() { + private void assertGenerateOK(boolean usingUserDelegation) { Utility.assertNotNull("version", this.version); - Utility.assertNotNull("containerName", this.containerName); - if (blobName == null && snapshotId != null) { - throw new IllegalArgumentException("Cannot set a snapshotId without a blobName."); - } - } + Utility.assertNotNull("canonicalName", this.canonicalName); - /** - * Gets the resource string for SAS tokens based on object state. - */ - private String getResource() { - String resource = "c"; - if (!Utility.isNullOrEmpty(this.blobName)) { - resource = snapshotId != null && !snapshotId.isEmpty() ? "bs" : "b"; - } - - return resource; - } - - /** - * Gets the verified permissions string for SAS tokens based on object state. - */ - private String getVerifiedPermissions() { - String verifiedPermissions = null; - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - if (Utility.isNullOrEmpty(this.blobName)) { - if (this.permissions != null) { - verifiedPermissions = ContainerSASPermission.parse(this.permissions).toString(); + // Ensure either (expiryTime and permissions) or (identifier) is set + if (this.expiryTime == null || this.permissions == null) { + // Identifier is not required if user delegation is being used + if (!usingUserDelegation) { + Utility.assertNotNull("identifier", this.identifier); } } else { - if (this.permissions != null) { - verifiedPermissions = BlobSASPermission.parse(this.permissions).toString(); - } + Utility.assertNotNull("expiryTime", this.expiryTime); + Utility.assertNotNull("permissions", this.permissions); } - return verifiedPermissions; - } - - private String getCanonicalName(String accountName) { - // Container: "/blob/account/containername" - // Blob: "/blob/account/containername/blobname" - StringBuilder canonicalName = new StringBuilder("/blob"); - canonicalName.append('/').append(accountName).append('/').append(this.containerName); - - if (!Utility.isNullOrEmpty(this.blobName)) { - canonicalName.append("/").append(this.blobName); + if (this.resource != null && this.resource.equals(Constants.UrlConstants.SAS_CONTAINER_CONSTANT)) { + if (this.snapshotId != null) { + throw new IllegalArgumentException("Cannot set a snapshotId without resource being a blob."); + } } - - return canonicalName.toString(); } - private String stringToSign(final String verifiedPermissions, final String resource, - final SharedKeyCredential sharedKeyCredentials) { + private String stringToSign() { return String.join("\n", - verifiedPermissions == null ? "" : verifiedPermissions, + this.permissions == null ? "" : this.permissions, this.startTime == null ? "" : Utility.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Utility.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), - getCanonicalName(sharedKeyCredentials.accountName()), + this.canonicalName == null ? "" : this.canonicalName, this.identifier == null ? "" : this.identifier, this.ipRange == null ? (new IPRange()).toString() : this.ipRange.toString(), this.protocol == null ? "" : protocol.toString(), this.version == null ? "" : this.version, - resource == null ? "" : resource, + this.resource == null ? "" : this.resource, this.snapshotId == null ? "" : this.snapshotId, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, @@ -442,13 +459,12 @@ private String stringToSign(final String verifiedPermissions, final String resou ); } - private String stringToSign(final String verifiedPermissions, final String resource, - final UserDelegationKey key, final String accountName) { + private String stringToSign(final UserDelegationKey key) { return String.join("\n", - verifiedPermissions == null ? "" : verifiedPermissions, + this.permissions == null ? "" : this.permissions, this.startTime == null ? "" : Utility.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime), this.expiryTime == null ? "" : Utility.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime), - getCanonicalName(accountName), + this.canonicalName == null ? "" : this.canonicalName, key.signedOid() == null ? "" : key.signedOid(), key.signedTid() == null ? "" : key.signedTid(), key.signedStart() == null ? "" : Utility.ISO_8601_UTC_DATE_FORMATTER.format(key.signedStart()), @@ -458,7 +474,7 @@ private String stringToSign(final String verifiedPermissions, final String resou this.ipRange == null ? new IPRange().toString() : this.ipRange.toString(), this.protocol == null ? "" : this.protocol.toString(), this.version == null ? "" : this.version, - resource == null ? "" : resource, + this.resource == null ? "" : this.resource, this.snapshotId == null ? "" : this.snapshotId, this.cacheControl == null ? "" : this.cacheControl, this.contentDisposition == null ? "" : this.contentDisposition, diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/StorageAsyncClient.java b/storage/client/blob/src/main/java/com/azure/storage/blob/StorageAsyncClient.java index d5b0aecc3a3f1..c6c48d7e5770d 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/StorageAsyncClient.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/StorageAsyncClient.java @@ -18,6 +18,7 @@ import com.azure.storage.blob.models.StorageServiceProperties; import com.azure.storage.blob.models.StorageServiceStats; import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.common.credentials.SharedKeyCredential; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -233,4 +234,73 @@ public Mono> getAccountInfo() { .getAccountInfo() .map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.deserializedHeaders()))); } + + /** + * Generates an account SAS token with the specified parameters + * + * @param accountSASService + * The {@code AccountSASService} services for the account SAS + * @param accountSASResourceType + * An optional {@code AccountSASResourceType} resources for the account SAS + * @param accountSASPermission + * The {@code AccountSASPermission} permission for the account SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the account SAS + * + * @return + * A string that represents the SAS token + */ + public String generateAccountSAS(AccountSASService accountSASService, AccountSASResourceType accountSASResourceType, + AccountSASPermission accountSASPermission, OffsetDateTime expiryTime) { + return this.generateAccountSAS(accountSASService, accountSASResourceType, accountSASPermission, expiryTime, + null /* startTime */, null /* version */, null /* ipRange */, null /* sasProtocol */); + } + + /** + * Generates an account SAS token with the specified parameters + * + * @param accountSASService + * The {@code AccountSASService} services for the account SAS + * @param accountSASResourceType + * An optional {@code AccountSASResourceType} resources for the account SAS + * @param accountSASPermission + * The {@code AccountSASPermission} permission for the account SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the account SAS + * @param startTime + * The {@code OffsetDateTime} start time for the account SAS + * @param version + * The {@code String} version for the account SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateAccountSAS(AccountSASService accountSASService, AccountSASResourceType accountSASResourceType, + AccountSASPermission accountSASPermission, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, IPRange ipRange, + SASProtocol sasProtocol) { + + AccountSASSignatureValues accountSASSignatureValues = new AccountSASSignatureValues(); + accountSASSignatureValues.services(accountSASService == null ? null : accountSASService.toString()); + accountSASSignatureValues.resourceTypes(accountSASResourceType == null ? null : accountSASResourceType.toString()); + accountSASSignatureValues.permissions(accountSASPermission == null ? null : accountSASPermission.toString()); + accountSASSignatureValues.expiryTime(expiryTime); + accountSASSignatureValues.startTime(startTime); + + if (version != null) { + accountSASSignatureValues.version(version); + } + + accountSASSignatureValues.ipRange(ipRange); + accountSASSignatureValues.protocol(sasProtocol); + + SharedKeyCredential sharedKeyCredential = Utility.getSharedKeyCredential(this.storageAsyncRawClient.azureBlobStorage.httpPipeline()); + + SASQueryParameters sasQueryParameters = accountSASSignatureValues.generateSASQueryParameters(sharedKeyCredential); + + return sasQueryParameters.encode(); + } } diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/StorageClient.java b/storage/client/blob/src/main/java/com/azure/storage/blob/StorageClient.java index f18cf0640fbd9..c895cdda58bbc 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/StorageClient.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/StorageClient.java @@ -290,4 +290,53 @@ public Response getAccountInfo(Duration timeout) { return Utility.blockWithOptionalTimeout(response, timeout); } + + /** + * Generates an account SAS token with the specified parameters + * + * @param accountSASService + * The {@code AccountSASService} services for the account SAS + * @param accountSASResourceType + * An optional {@code AccountSASResourceType} resources for the account SAS + * @param accountSASPermission + * The {@code AccountSASPermission} permission for the account SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the account SAS + * + * @return + * A string that represents the SAS token + */ + public String generateAccountSAS(AccountSASService accountSASService, AccountSASResourceType accountSASResourceType, + AccountSASPermission accountSASPermission, OffsetDateTime expiryTime) { + return this.storageAsyncClient.generateAccountSAS(accountSASService, accountSASResourceType, accountSASPermission, expiryTime); + } + + /** + * Generates an account SAS token with the specified parameters + * + * @param accountSASService + * The {@code AccountSASService} services for the account SAS + * @param accountSASResourceType + * An optional {@code AccountSASResourceType} resources for the account SAS + * @param accountSASPermission + * The {@code AccountSASPermission} permission for the account SAS + * @param expiryTime + * The {@code OffsetDateTime} expiry time for the account SAS + * @param startTime + * The {@code OffsetDateTime} start time for the account SAS + * @param version + * The {@code String} version for the account SAS + * @param ipRange + * An optional {@code IPRange} ip address range for the SAS + * @param sasProtocol + * An optional {@code SASProtocol} protocol for the SAS + * + * @return + * A string that represents the SAS token + */ + public String generateAccountSAS(AccountSASService accountSASService, AccountSASResourceType accountSASResourceType, + AccountSASPermission accountSASPermission, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, IPRange ipRange, + SASProtocol sasProtocol) { + return this.storageAsyncClient.generateAccountSAS(accountSASService, accountSASResourceType, accountSASPermission, expiryTime, startTime, version, ipRange, sasProtocol); + } } diff --git a/storage/client/blob/src/main/java/com/azure/storage/blob/Utility.java b/storage/client/blob/src/main/java/com/azure/storage/blob/Utility.java index 3b5d073c4023e..252a5e83bbaf2 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/blob/Utility.java +++ b/storage/client/blob/src/main/java/com/azure/storage/blob/Utility.java @@ -5,9 +5,13 @@ import com.azure.core.http.HttpHeader; import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.implementation.http.UrlBuilder; import com.azure.storage.blob.models.StorageErrorException; import com.azure.storage.blob.models.UserDelegationKey; +import com.azure.storage.common.credentials.SharedKeyCredential; +import com.azure.storage.common.policy.SharedKeyCredentialPolicy; import reactor.core.publisher.Mono; import reactor.util.annotation.Nullable; @@ -387,4 +391,23 @@ static T blockWithOptionalTimeout(Mono response, @Nullable Duration timeo return response.block(timeout); } } + + /** + * Gets the SharedKeyCredential from the HttpPipeline + * + * @param httpPipeline + * The {@code HttpPipeline} httpPipeline from which a sharedKeyCredential will be extracted + * + * @return The {@code SharedKeyCredential} sharedKeyCredential in the httpPipeline + */ + static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { + for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { + HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); + if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { + SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; + return sharedKeyCredentialPolicy.sharedKeyCredential(); + } + } + return null; + } } diff --git a/storage/client/blob/src/main/java/com/azure/storage/common/credentials/SASTokenCredential.java b/storage/client/blob/src/main/java/com/azure/storage/common/credentials/SASTokenCredential.java index fe93273e3f64e..4dce1c831ce21 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/common/credentials/SASTokenCredential.java +++ b/storage/client/blob/src/main/java/com/azure/storage/common/credentials/SASTokenCredential.java @@ -18,12 +18,27 @@ public final class SASTokenCredential { private static final String SIGNED_PERMISSIONS = "sp"; private static final String SIGNED_EXPIRY = "se"; private static final String SIGNATURE = "sig"; + private static final String SIGNED_RESOURCE = "sr"; // Optional SAS token pieces private static final String SIGNED_START = "st"; private static final String SIGNED_PROTOCOL = "spr"; private static final String SIGNED_IP = "sip"; + private static final String CACHE_CONTROL = "rscc"; + private static final String CONTENT_DISPOSITION = "rscd"; + private static final String CONTENT_ENCODING = "rsce"; + private static final String CONTENT_LANGUAGE = "rscl"; + private static final String CONTENT_TYPE = "rsct"; + + // Possible User Delegation Key pieces + private static final String SIGNED_KEY_O_ID = "skoid"; + private static final String SIGNED_KEY_T_ID = "sktid"; + private static final String SIGNED_KEY_START = "skt"; + private static final String SIGNED_KEY_EXPIRY = "ske"; + private static final String SIGNED_KEY_SERVICE = "sks"; + private static final String SIGNED_KEY_VERSION = "skv"; + private final String sasToken; /** @@ -57,20 +72,34 @@ public static SASTokenCredential fromQuery(String query) { queryParams.put(key, queryParam); } - if (queryParams.size() < 6 - || !queryParams.containsKey(SIGNED_VERSION) - || !queryParams.containsKey(SIGNED_SERVICES) - || !queryParams.containsKey(SIGNED_RESOURCE_TYPES) - || !queryParams.containsKey(SIGNED_PERMISSIONS) - || !queryParams.containsKey(SIGNED_EXPIRY) - || !queryParams.containsKey(SIGNATURE)) { + /* Because ServiceSAS only requires expiry and permissions, both of which could be on the container + acl, the only guaranteed indication of a SAS is the signature. We'll let the service validate + the other query parameters. */ + if (!queryParams.containsKey(SIGNATURE)) { return null; } - StringBuilder sasTokenBuilder = new StringBuilder(queryParams.get(SIGNED_VERSION)) - .append("&").append(queryParams.get(SIGNED_SERVICES)) - .append("&").append(queryParams.get(SIGNED_RESOURCE_TYPES)) - .append("&").append(queryParams.get(SIGNED_PERMISSIONS)); + StringBuilder sasTokenBuilder = new StringBuilder(); + + if (queryParams.containsKey(SIGNED_VERSION)) { + sasTokenBuilder.append(queryParams.get(SIGNED_VERSION)); + } + + if (queryParams.containsKey(SIGNED_SERVICES)) { + sasTokenBuilder.append("&").append(queryParams.get(SIGNED_SERVICES)); + } + + if (queryParams.containsKey(SIGNED_RESOURCE_TYPES)) { + sasTokenBuilder.append("&").append(queryParams.get(SIGNED_RESOURCE_TYPES)); + } + + if (queryParams.containsKey(SIGNED_PERMISSIONS)) { + sasTokenBuilder.append("&").append(queryParams.get(SIGNED_PERMISSIONS)); + } + + if (queryParams.containsKey(SIGNED_RESOURCE)) { + sasTokenBuilder.append("&").append(queryParams.get(SIGNED_RESOURCE)); + } // SIGNED_START is optional if (queryParams.containsKey(SIGNED_START)) { @@ -89,6 +118,51 @@ public static SASTokenCredential fromQuery(String query) { sasTokenBuilder.append("&").append(queryParams.get(SIGNED_PROTOCOL)); } + if (queryParams.containsKey(CACHE_CONTROL)) { + sasTokenBuilder.append("&").append(queryParams.get(CACHE_CONTROL)); + } + + if (queryParams.containsKey(CONTENT_DISPOSITION)) { + sasTokenBuilder.append("&").append(queryParams.get(CONTENT_DISPOSITION)); + } + + if (queryParams.containsKey(CONTENT_ENCODING)) { + sasTokenBuilder.append("&").append(queryParams.get(CONTENT_ENCODING)); + } + + if (queryParams.containsKey(CONTENT_LANGUAGE)) { + sasTokenBuilder.append("&").append(queryParams.get(CONTENT_LANGUAGE)); + } + + if (queryParams.containsKey(CONTENT_TYPE)) { + sasTokenBuilder.append("&").append(queryParams.get(CONTENT_TYPE)); + } + + // User Delegation Key Parameters + if (queryParams.containsKey(SIGNED_KEY_O_ID)) { + sasTokenBuilder.append("&").append(queryParams.get(SIGNED_KEY_O_ID)); + } + + if (queryParams.containsKey(SIGNED_KEY_T_ID)) { + sasTokenBuilder.append("&").append(queryParams.get(SIGNED_KEY_T_ID)); + } + + if (queryParams.containsKey(SIGNED_KEY_START)) { + sasTokenBuilder.append("&").append(queryParams.get(SIGNED_KEY_START)); + } + + if (queryParams.containsKey(SIGNED_KEY_EXPIRY)) { + sasTokenBuilder.append("&").append(queryParams.get(SIGNED_KEY_EXPIRY)); + } + + if (queryParams.containsKey(SIGNED_KEY_SERVICE)) { + sasTokenBuilder.append("&").append(queryParams.get(SIGNED_KEY_SERVICE)); + } + + if (queryParams.containsKey(SIGNED_KEY_VERSION)) { + sasTokenBuilder.append("&").append(queryParams.get(SIGNED_KEY_VERSION)); + } + sasTokenBuilder.append("&").append(queryParams.get(SIGNATURE)); return new SASTokenCredential(sasTokenBuilder.toString()); diff --git a/storage/client/blob/src/main/java/com/azure/storage/common/policy/SharedKeyCredentialPolicy.java b/storage/client/blob/src/main/java/com/azure/storage/common/policy/SharedKeyCredentialPolicy.java index 8ee1284591dd2..743eae8f262e4 100644 --- a/storage/client/blob/src/main/java/com/azure/storage/common/policy/SharedKeyCredentialPolicy.java +++ b/storage/client/blob/src/main/java/com/azure/storage/common/policy/SharedKeyCredentialPolicy.java @@ -24,6 +24,15 @@ public SharedKeyCredentialPolicy(SharedKeyCredential credential) { this.credential = credential; } + /** + * Gets the shared key credential linked to the policy. + * @return + * The {@link SharedKeyCredential} linked to the policy. + */ + public SharedKeyCredential sharedKeyCredential() { + return this.credential; + } + @Override public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { String authorizationValue = credential.generateAuthorizationHeader(context.httpRequest().url(), diff --git a/storage/client/blob/src/test/java/com/azure/storage/blob/SASTest.groovy b/storage/client/blob/src/test/java/com/azure/storage/blob/SASTest.groovy new file mode 100644 index 0000000000000..1ebf9860f2ac3 --- /dev/null +++ b/storage/client/blob/src/test/java/com/azure/storage/blob/SASTest.groovy @@ -0,0 +1,1079 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob + +import com.azure.storage.blob.models.AccessPolicy +import com.azure.storage.blob.models.BlobRange +import com.azure.storage.blob.models.SignedIdentifier +import com.azure.storage.blob.models.StorageErrorCode +import com.azure.storage.blob.models.UserDelegationKey +import com.azure.storage.common.credentials.SASTokenCredential +import com.azure.storage.common.credentials.SharedKeyCredential +import spock.lang.Unroll + +import java.time.LocalDateTime +import java.time.OffsetDateTime +import java.time.ZoneOffset + +class SASTest extends APISpec { + + def "responseError"() { + when: + cu.listBlobsFlat() + + then: + def e = thrown(StorageException) + e.errorCode() == StorageErrorCode.INVALID_QUERY_PARAMETER_VALUE + e.statusCode() == 400 + e.message().contains("Value for one of the query parameters specified in the request URI is invalid.") + e.getMessage().contains(" Date: Fri, 12 Jul 2019 12:12:26 -0700 Subject: [PATCH 78/85] Move core to sdk/core (#4413) * Moved core * Repointed POMs where appropriate. --- eng/.docsettings.yml | 8 ++++---- pom.client.xml | 2 +- sdk/appconfiguration/pom.service.xml | 2 +- {core => sdk/core}/.gitignore | 0 {core => sdk/core}/README.md | 0 {core => sdk/core}/azure-core-amqp/README.md | 0 {core => sdk/core}/azure-core-amqp/pom.xml | 0 .../src/main/java/com/azure/core/amqp/AmqpConnection.java | 0 .../main/java/com/azure/core/amqp/AmqpEndpointState.java | 0 .../java/com/azure/core/amqp/AmqpExceptionHandler.java | 0 .../src/main/java/com/azure/core/amqp/AmqpLink.java | 0 .../src/main/java/com/azure/core/amqp/AmqpSession.java | 0 .../main/java/com/azure/core/amqp/AmqpShutdownSignal.java | 0 .../src/main/java/com/azure/core/amqp/CBSNode.java | 0 .../java/com/azure/core/amqp/EndpointStateNotifier.java | 0 .../main/java/com/azure/core/amqp/ExponentialRetry.java | 0 .../main/java/com/azure/core/amqp/MessageConstant.java | 0 .../src/main/java/com/azure/core/amqp/Retry.java | 0 .../src/main/java/com/azure/core/amqp/TransportType.java | 0 .../java/com/azure/core/amqp/exception/AmqpException.java | 0 .../com/azure/core/amqp/exception/AmqpResponseCode.java | 0 .../com/azure/core/amqp/exception/ErrorCondition.java | 0 .../java/com/azure/core/amqp/exception/ErrorContext.java | 0 .../java/com/azure/core/amqp/exception/ExceptionUtil.java | 0 .../com/azure/core/amqp/exception/LinkErrorContext.java | 0 .../core/amqp/exception/OperationCancelledException.java | 0 .../azure/core/amqp/exception/SessionErrorContext.java | 0 .../java/com/azure/core/amqp/exception/package-info.java | 0 .../src/main/java/com/azure/core/amqp/package-info.java | 0 .../java/com/azure/core/amqp/AmqpShutdownSignalTest.java | 0 .../java/com/azure/core/amqp/ExponentialRetryTest.java | 0 .../java/com/azure/core/amqp/MessageConstantTest.java | 0 .../src/test/java/com/azure/core/amqp/RetryTest.java | 0 .../test/java/com/azure/core/amqp/TransportTypeTest.java | 0 .../com/azure/core/amqp/exception/AmqpExceptionTest.java | 0 .../azure/core/amqp/exception/AmqpResponseCodeTest.java | 0 .../com/azure/core/amqp/exception/ErrorContextTest.java | 0 .../com/azure/core/amqp/exception/ExceptionUtilTest.java | 0 .../azure/core/amqp/exception/LinkErrorContextTest.java | 0 .../amqp/exception/OperationCancelledExceptionTest.java | 0 .../core/amqp/exception/SessionErrorContextTest.java | 0 {core => sdk/core}/azure-core-management/pom.xml | 0 .../com/azure/core/management/AsyncOperationResource.java | 0 .../main/java/com/azure/core/management/CloudError.java | 0 .../java/com/azure/core/management/CloudException.java | 0 .../java/com/azure/core/management/OperationState.java | 0 .../src/main/java/com/azure/core/management/Page.java | 0 .../main/java/com/azure/core/management/PagedList.java | 0 .../src/main/java/com/azure/core/management/Resource.java | 0 .../main/java/com/azure/core/management/SubResource.java | 0 .../com/azure/core/management/annotations/AzureHost.java | 0 .../azure/core/management/annotations/package-info.java | 0 .../implementation/AzureAsyncOperationPollStrategy.java | 0 .../azure/core/management/implementation/AzureProxy.java | 0 .../management/implementation/CompletedPollStrategy.java | 0 .../management/implementation/LocationPollStrategy.java | 0 .../core/management/implementation/OperationStatus.java | 0 .../core/management/implementation/PollStrategy.java | 0 .../implementation/ProvisioningStatePollStrategy.java | 0 .../implementation/ResourceWithProvisioningState.java | 0 .../main/java/com/azure/core/management/package-info.java | 0 .../core/management/serializer/AzureJacksonAdapter.java | 0 .../management/serializer/CloudErrorDeserializer.java | 0 .../azure/core/management/serializer/package-info.java | 0 .../azure/core/management/AzureProxyToRestProxyTests.java | 0 .../management/AzureProxyToRestProxyWithMockTests.java | 0 .../management/AzureProxyToRestProxyWithNettyTests.java | 0 .../test/java/com/azure/core/management/AzureTests.java | 0 .../test/java/com/azure/core/management/HttpBinJSON.java | 0 .../test/java/com/azure/core/management/MockResource.java | 0 .../java/com/azure/core/management/MyAzureException.java | 0 .../java/com/azure/core/management/PagedListTests.java | 0 .../azure/core/management/http/MockAzureHttpClient.java | 0 .../core/management/implementation/AzureProxyTests.java | 0 .../com/azure/core/management/implementation/Value.java | 0 .../azure/core/management/implementation/ValueTests.java | 0 {core => sdk/core}/azure-core-test/README.md | 0 {core => sdk/core}/azure-core-test/pom.xml | 0 .../main/java/com/azure/core/test/InterceptorManager.java | 0 .../src/main/java/com/azure/core/test/TestBase.java | 0 .../src/main/java/com/azure/core/test/TestMode.java | 0 .../java/com/azure/core/test/http/MockHttpResponse.java | 0 .../java/com/azure/core/test/http/PlaybackClient.java | 0 .../main/java/com/azure/core/test/http/package-info.java | 0 .../com/azure/core/test/models/NetworkCallRecord.java | 0 .../java/com/azure/core/test/models/RecordedData.java | 0 .../java/com/azure/core/test/models/package-info.java | 0 .../src/main/java/com/azure/core/test/package-info.java | 0 .../azure/core/test/policy/RecordNetworkCallPolicy.java | 0 .../java/com/azure/core/test/policy/package-info.java | 0 .../java/com/azure/core/test/utils/ResourceNamer.java | 0 .../java/com/azure/core/test/utils/TestResourceNamer.java | 0 .../main/java/com/azure/core/test/utils/package-info.java | 0 {core => sdk/core}/azure-core/README.md | 0 {core => sdk/core}/azure-core/pom.xml | 0 .../src/main/java/com/azure/core/AzureEnvironment.java | 0 .../main/java/com/azure/core/credentials/AccessToken.java | 0 .../core/credentials/BasicAuthenticationCredential.java | 0 .../java/com/azure/core/credentials/SimpleTokenCache.java | 0 .../java/com/azure/core/credentials/TokenCredential.java | 0 .../java/com/azure/core/credentials/package-info.java | 0 .../java/com/azure/core/exception/AzureException.java | 0 .../core/exception/ClientAuthenticationException.java | 0 .../java/com/azure/core/exception/DecodeException.java | 0 .../com/azure/core/exception/HttpRequestException.java | 0 .../com/azure/core/exception/HttpResponseException.java | 0 .../com/azure/core/exception/ResourceExistsException.java | 0 .../azure/core/exception/ResourceModifiedException.java | 0 .../azure/core/exception/ResourceNotFoundException.java | 0 .../azure/core/exception/ServiceResponseException.java | 0 .../azure/core/exception/TooManyRedirectsException.java | 0 .../main/java/com/azure/core/exception/package-info.java | 0 .../src/main/java/com/azure/core/http/HttpClient.java | 0 .../src/main/java/com/azure/core/http/HttpHeader.java | 0 .../src/main/java/com/azure/core/http/HttpHeaders.java | 0 .../src/main/java/com/azure/core/http/HttpMethod.java | 0 .../src/main/java/com/azure/core/http/HttpPipeline.java | 0 .../java/com/azure/core/http/HttpPipelineBuilder.java | 0 .../java/com/azure/core/http/HttpPipelineCallContext.java | 0 .../java/com/azure/core/http/HttpPipelineNextPolicy.java | 0 .../src/main/java/com/azure/core/http/HttpRequest.java | 0 .../src/main/java/com/azure/core/http/HttpResponse.java | 0 .../src/main/java/com/azure/core/http/ProxyOptions.java | 0 .../main/java/com/azure/core/http/ReactorNettyClient.java | 0 .../src/main/java/com/azure/core/http/package-info.java | 0 .../java/com/azure/core/http/policy/AddDatePolicy.java | 0 .../java/com/azure/core/http/policy/AddHeadersPolicy.java | 0 .../core/http/policy/BearerTokenAuthenticationPolicy.java | 0 .../java/com/azure/core/http/policy/CookiePolicy.java | 0 .../main/java/com/azure/core/http/policy/HostPolicy.java | 0 .../com/azure/core/http/policy/HttpLogDetailLevel.java | 0 .../com/azure/core/http/policy/HttpLoggingPolicy.java | 0 .../com/azure/core/http/policy/HttpPipelinePolicy.java | 0 .../main/java/com/azure/core/http/policy/PortPolicy.java | 0 .../java/com/azure/core/http/policy/ProtocolPolicy.java | 0 .../azure/core/http/policy/ProxyAuthenticationPolicy.java | 0 .../java/com/azure/core/http/policy/RequestIdPolicy.java | 0 .../main/java/com/azure/core/http/policy/RetryPolicy.java | 0 .../java/com/azure/core/http/policy/TimeoutPolicy.java | 0 .../java/com/azure/core/http/policy/UserAgentPolicy.java | 0 .../java/com/azure/core/http/policy/package-info.java | 0 .../src/main/java/com/azure/core/http/rest/Page.java | 0 .../src/main/java/com/azure/core/http/rest/PagedFlux.java | 0 .../main/java/com/azure/core/http/rest/PagedResponse.java | 0 .../src/main/java/com/azure/core/http/rest/Response.java | 0 .../main/java/com/azure/core/http/rest/ResponseBase.java | 0 .../java/com/azure/core/http/rest/SimpleResponse.java | 0 .../java/com/azure/core/http/rest/StreamResponse.java | 0 .../main/java/com/azure/core/http/rest/VoidResponse.java | 0 .../main/java/com/azure/core/http/rest/package-info.java | 0 .../java/com/azure/core/implementation/Base64Url.java | 0 .../com/azure/core/implementation/CollectionFormat.java | 0 .../com/azure/core/implementation/DateTimeRfc1123.java | 0 .../com/azure/core/implementation/EncodedParameter.java | 0 .../azure/core/implementation/OperationDescription.java | 0 .../com/azure/core/implementation/PercentEscaper.java | 0 .../java/com/azure/core/implementation/RestProxy.java | 0 .../java/com/azure/core/implementation/Substitution.java | 0 .../azure/core/implementation/SwaggerInterfaceParser.java | 0 .../azure/core/implementation/SwaggerMethodParser.java | 0 .../implementation/UnexpectedExceptionInformation.java | 0 .../main/java/com/azure/core/implementation/UnixTime.java | 0 .../java/com/azure/core/implementation/UrlEscapers.java | 0 .../java/com/azure/core/implementation/Validator.java | 0 .../com/azure/core/implementation/annotation/Beta.java | 0 .../azure/core/implementation/annotation/BodyParam.java | 0 .../com/azure/core/implementation/annotation/Delete.java | 0 .../core/implementation/annotation/ExpectedResponses.java | 0 .../com/azure/core/implementation/annotation/Fluent.java | 0 .../azure/core/implementation/annotation/FormParam.java | 0 .../com/azure/core/implementation/annotation/Get.java | 0 .../com/azure/core/implementation/annotation/Head.java | 0 .../core/implementation/annotation/HeaderCollection.java | 0 .../azure/core/implementation/annotation/HeaderParam.java | 0 .../com/azure/core/implementation/annotation/Headers.java | 0 .../com/azure/core/implementation/annotation/Host.java | 0 .../azure/core/implementation/annotation/HostParam.java | 0 .../azure/core/implementation/annotation/Immutable.java | 0 .../azure/core/implementation/annotation/JsonFlatten.java | 0 .../com/azure/core/implementation/annotation/Patch.java | 0 .../azure/core/implementation/annotation/PathParam.java | 0 .../com/azure/core/implementation/annotation/Post.java | 0 .../com/azure/core/implementation/annotation/Put.java | 0 .../azure/core/implementation/annotation/QueryParam.java | 0 .../core/implementation/annotation/ResumeOperation.java | 0 .../azure/core/implementation/annotation/ReturnType.java | 0 .../implementation/annotation/ReturnValueWireType.java | 0 .../core/implementation/annotation/ServiceClient.java | 0 .../implementation/annotation/ServiceClientBuilder.java | 0 .../core/implementation/annotation/ServiceInterface.java | 0 .../core/implementation/annotation/ServiceMethod.java | 0 .../implementation/annotation/SkipParentValidation.java | 0 .../annotation/UnexpectedResponseExceptionType.java | 0 .../annotation/UnexpectedResponseExceptionTypes.java | 0 .../core/implementation/annotation/package-info.java | 0 .../exception/InvalidReturnTypeException.java | 0 .../exception/MissingRequiredAnnotationException.java | 0 .../azure/core/implementation/exception/package-info.java | 0 .../core/implementation/http/BufferedHttpResponse.java | 0 .../com/azure/core/implementation/http/ContentType.java | 0 .../azure/core/implementation/http/PagedResponseBase.java | 0 .../com/azure/core/implementation/http/UrlBuilder.java | 0 .../java/com/azure/core/implementation/http/UrlToken.java | 0 .../com/azure/core/implementation/http/UrlTokenType.java | 0 .../com/azure/core/implementation/http/UrlTokenizer.java | 0 .../azure/core/implementation/http/UrlTokenizerState.java | 0 .../com/azure/core/implementation/http/package-info.java | 0 .../http/policy/spi/AfterRetryPolicyProvider.java | 0 .../http/policy/spi/BeforeRetryPolicyProvider.java | 0 .../http/policy/spi/HttpPolicyProviders.java | 0 .../implementation/http/policy/spi/PolicyProvider.java | 0 .../core/implementation/http/policy/spi/package-info.java | 0 .../java/com/azure/core/implementation/package-info.java | 0 .../serializer/HttpResponseBodyDecoder.java | 0 .../implementation/serializer/HttpResponseDecodeData.java | 0 .../implementation/serializer/HttpResponseDecoder.java | 0 .../serializer/HttpResponseHeaderDecoder.java | 0 .../azure/core/implementation/serializer/ItemPage.java | 0 .../serializer/MalformedValueException.java | 0 .../core/implementation/serializer/SerializerAdapter.java | 0 .../implementation/serializer/SerializerEncoding.java | 0 .../jackson/AdditionalPropertiesDeserializer.java | 0 .../jackson/AdditionalPropertiesSerializer.java | 0 .../serializer/jackson/Base64UrlSerializer.java | 0 .../serializer/jackson/ByteArraySerializer.java | 0 .../serializer/jackson/DateTimeRfc1123Serializer.java | 0 .../serializer/jackson/DateTimeSerializer.java | 0 .../serializer/jackson/DurationSerializer.java | 0 .../serializer/jackson/FlatteningDeserializer.java | 0 .../serializer/jackson/FlatteningSerializer.java | 0 .../implementation/serializer/jackson/JacksonAdapter.java | 0 .../implementation/serializer/jackson/package-info.java | 0 .../core/implementation/serializer/package-info.java | 0 .../com/azure/core/implementation/tracing/Tracer.java | 0 .../azure/core/implementation/tracing/TracerProxy.java | 0 .../com/azure/core/implementation/util/Base64Util.java | 0 .../java/com/azure/core/implementation/util/FluxUtil.java | 0 .../com/azure/core/implementation/util/ImplUtils.java | 0 .../com/azure/core/implementation/util/ScopeUtil.java | 0 .../java/com/azure/core/implementation/util/TypeUtil.java | 0 .../com/azure/core/implementation/util/package-info.java | 0 .../src/main/java/com/azure/core/package-info.java | 0 .../src/main/java/com/azure/core/util/Context.java | 0 .../java/com/azure/core/util/ExpandableStringEnum.java | 0 .../azure/core/util/configuration/BaseConfigurations.java | 0 .../com/azure/core/util/configuration/Configuration.java | 0 .../core/util/configuration/ConfigurationManager.java | 0 .../azure/core/util/configuration/NoopConfiguration.java | 0 .../com/azure/core/util/configuration/package-info.java | 0 .../java/com/azure/core/util/logging/ClientLogger.java | 0 .../java/com/azure/core/util/logging/package-info.java | 0 .../src/main/java/com/azure/core/util/package-info.java | 0 .../java/com/azure/core/util/polling/PollResponse.java | 0 .../src/main/java/com/azure/core/util/polling/Poller.java | 0 .../java/com/azure/core/util/polling/package-info.java | 0 .../core/http/rest/PagedFluxJavaDocCodeSnippets.java | 0 .../util/ClientLoggerJavaDocCodeSnippets.java | 0 .../implementation/util/FluxUtilJavaDocCodeSnippets.java | 0 .../util/polling/PollResponseJavaDocCodeSnippets.java | 0 .../core/util/polling/PollerJavaDocCodeSnippets.java | 0 .../src/test/java/com/azure/core/ConfigurationTests.java | 0 .../src/test/java/com/azure/core/MockServer.java | 0 .../test/java/com/azure/core/MyOtherRestException.java | 0 .../src/test/java/com/azure/core/MyRestException.java | 0 .../src/test/java/com/azure/core/UserAgentTests.java | 0 .../java/com/azure/core/credentials/CredentialsTests.java | 0 .../java/com/azure/core/credentials/TokenCacheTests.java | 0 .../test/java/com/azure/core/entities/AccessPolicy.java | 0 .../java/com/azure/core/entities/HttpBinFormDataJSON.java | 0 .../test/java/com/azure/core/entities/HttpBinHeaders.java | 0 .../test/java/com/azure/core/entities/HttpBinJSON.java | 0 .../com/azure/core/entities/SignedIdentifierInner.java | 0 .../com/azure/core/entities/SignedIdentifiersWrapper.java | 0 .../src/test/java/com/azure/core/entities/Slide.java | 0 .../src/test/java/com/azure/core/entities/Slideshow.java | 0 .../test/java/com/azure/core/http/HttpHeaderTests.java | 0 .../test/java/com/azure/core/http/HttpHeadersTests.java | 0 .../test/java/com/azure/core/http/HttpMethodTests.java | 0 .../test/java/com/azure/core/http/HttpPipelineTests.java | 0 .../test/java/com/azure/core/http/HttpRequestTests.java | 0 .../src/test/java/com/azure/core/http/MockHttpClient.java | 0 .../test/java/com/azure/core/http/MockHttpResponse.java | 0 .../java/com/azure/core/http/ReactorNettyClientTests.java | 0 .../java/com/azure/core/http/policy/HostPolicyTests.java | 0 .../com/azure/core/http/policy/ProtocolPolicyTests.java | 0 .../core/http/policy/ProxyAuthenticationPolicyTests.java | 0 .../com/azure/core/http/policy/RequestIdPolicyTests.java | 0 .../java/com/azure/core/http/policy/RetryPolicyTests.java | 0 .../test/java/com/azure/core/http/rest/PagedFluxTest.java | 0 .../com/azure/core/implementation/Base64UrlTests.java | 0 .../azure/core/implementation/EncodedParameterTests.java | 0 .../azure/core/implementation/RestProxyStressTests.java | 0 .../com/azure/core/implementation/RestProxyTests.java | 0 .../implementation/RestProxyWithHttpProxyNettyTests.java | 0 .../azure/core/implementation/RestProxyWithMockTests.java | 0 .../core/implementation/RestProxyWithNettyTests.java | 0 .../com/azure/core/implementation/RestProxyXMLTests.java | 0 .../com/azure/core/implementation/SubstitutionTests.java | 0 .../core/implementation/SwaggerInterfaceParserTests.java | 0 .../core/implementation/SwaggerMethodParserTests.java | 0 .../com/azure/core/implementation/UrlEscaperTests.java | 0 .../com/azure/core/implementation/ValidatorTests.java | 0 .../azure/core/implementation/http/UrlBuilderTests.java | 0 .../azure/core/implementation/http/UrlTokenizerTests.java | 0 .../jackson/AdditionalPropertiesSerializerTests.java | 0 .../serializer/jackson/DateTimeSerializerTests.java | 0 .../serializer/jackson/DurationSerializerTests.java | 0 .../serializer/jackson/FlatteningSerializerTests.java | 0 .../serializer/jackson/JacksonAdapterTests.java | 0 .../com/azure/core/implementation/util/FluxUtilTests.java | 0 .../test/java/com/azure/core/implementation/util/Foo.java | 0 .../java/com/azure/core/implementation/util/FooChild.java | 0 .../azure/core/implementation/util/ImplUtilsTests.java | 0 .../com/azure/core/implementation/util/TypeUtilTests.java | 0 .../java/com/azure/core/util/polling/PollerTests.java | 0 .../azure-core/src/test/resources/GetContainerACLs.xml | 0 .../src/test/resources/GetXMLWithAttributes.xml | 0 .../core}/azure-core/src/test/resources/upload.txt | 0 sdk/core/pom.service.xml | 5 ++++- {core => sdk/core}/pom.xml | 2 +- sdk/eventhubs/pom.service.xml | 2 +- sdk/keyvault/pom.service.xml | 2 +- 322 files changed, 13 insertions(+), 10 deletions(-) rename {core => sdk/core}/.gitignore (100%) rename {core => sdk/core}/README.md (100%) rename {core => sdk/core}/azure-core-amqp/README.md (100%) rename {core => sdk/core}/azure-core-amqp/pom.xml (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpConnection.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpEndpointState.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpExceptionHandler.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpLink.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpSession.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpShutdownSignal.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/CBSNode.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/EndpointStateNotifier.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/ExponentialRetry.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/MessageConstant.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/Retry.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/TransportType.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/AmqpException.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/AmqpResponseCode.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ErrorCondition.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ErrorContext.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ExceptionUtil.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/LinkErrorContext.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/OperationCancelledException.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/SessionErrorContext.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/package-info.java (100%) rename {core => sdk/core}/azure-core-amqp/src/main/java/com/azure/core/amqp/package-info.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/AmqpShutdownSignalTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/ExponentialRetryTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/MessageConstantTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/RetryTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/TransportTypeTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/AmqpExceptionTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/AmqpResponseCodeTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/ErrorContextTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/ExceptionUtilTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/LinkErrorContextTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/OperationCancelledExceptionTest.java (100%) rename {core => sdk/core}/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/SessionErrorContextTest.java (100%) rename {core => sdk/core}/azure-core-management/pom.xml (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/AsyncOperationResource.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/CloudError.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/CloudException.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/OperationState.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/Page.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/PagedList.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/Resource.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/SubResource.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/annotations/AzureHost.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/annotations/package-info.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/implementation/AzureAsyncOperationPollStrategy.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/implementation/AzureProxy.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/implementation/CompletedPollStrategy.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/implementation/LocationPollStrategy.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/implementation/OperationStatus.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/implementation/PollStrategy.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/implementation/ProvisioningStatePollStrategy.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/implementation/ResourceWithProvisioningState.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/package-info.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/serializer/AzureJacksonAdapter.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/serializer/CloudErrorDeserializer.java (100%) rename {core => sdk/core}/azure-core-management/src/main/java/com/azure/core/management/serializer/package-info.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyTests.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyWithMockTests.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyWithNettyTests.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/AzureTests.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/HttpBinJSON.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/MockResource.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/MyAzureException.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/PagedListTests.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/http/MockAzureHttpClient.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/implementation/AzureProxyTests.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/implementation/Value.java (100%) rename {core => sdk/core}/azure-core-management/src/test/java/com/azure/core/management/implementation/ValueTests.java (100%) rename {core => sdk/core}/azure-core-test/README.md (100%) rename {core => sdk/core}/azure-core-test/pom.xml (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/InterceptorManager.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/TestBase.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/TestMode.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/http/MockHttpResponse.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/http/PlaybackClient.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/http/package-info.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/models/NetworkCallRecord.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/models/RecordedData.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/models/package-info.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/package-info.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/policy/RecordNetworkCallPolicy.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/policy/package-info.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/utils/ResourceNamer.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/utils/TestResourceNamer.java (100%) rename {core => sdk/core}/azure-core-test/src/main/java/com/azure/core/test/utils/package-info.java (100%) rename {core => sdk/core}/azure-core/README.md (100%) rename {core => sdk/core}/azure-core/pom.xml (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/AzureEnvironment.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/credentials/AccessToken.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/credentials/BasicAuthenticationCredential.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/credentials/SimpleTokenCache.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/credentials/TokenCredential.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/credentials/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/AzureException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/ClientAuthenticationException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/DecodeException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/HttpRequestException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/HttpResponseException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/ResourceExistsException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/ResourceModifiedException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/ResourceNotFoundException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/ServiceResponseException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/TooManyRedirectsException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/exception/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/HttpClient.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/HttpHeader.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/HttpHeaders.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/HttpMethod.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/HttpPipeline.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/HttpPipelineBuilder.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/HttpPipelineCallContext.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/HttpPipelineNextPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/HttpRequest.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/HttpResponse.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/ReactorNettyClient.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/AddDatePolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/AddHeadersPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/BearerTokenAuthenticationPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/CookiePolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/HostPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/HttpLogDetailLevel.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/HttpPipelinePolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/PortPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/ProtocolPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/ProxyAuthenticationPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/RequestIdPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/RetryPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/TimeoutPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/UserAgentPolicy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/policy/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/rest/Page.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/rest/PagedFlux.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/rest/PagedResponse.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/rest/Response.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/rest/ResponseBase.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/rest/SimpleResponse.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/rest/StreamResponse.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/rest/VoidResponse.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/http/rest/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/Base64Url.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/CollectionFormat.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/DateTimeRfc1123.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/EncodedParameter.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/OperationDescription.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/PercentEscaper.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/RestProxy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/Substitution.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/SwaggerInterfaceParser.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/SwaggerMethodParser.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/UnexpectedExceptionInformation.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/UnixTime.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/UrlEscapers.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/Validator.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Beta.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/BodyParam.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Delete.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/ExpectedResponses.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Fluent.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/FormParam.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Get.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Head.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/HeaderCollection.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/HeaderParam.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Headers.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Host.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/HostParam.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Immutable.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/JsonFlatten.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Patch.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/PathParam.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Post.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/Put.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/QueryParam.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/ResumeOperation.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/ReturnType.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/ReturnValueWireType.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceClient.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceClientBuilder.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceInterface.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceMethod.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/SkipParentValidation.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/UnexpectedResponseExceptionType.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/UnexpectedResponseExceptionTypes.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/annotation/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/exception/InvalidReturnTypeException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/exception/MissingRequiredAnnotationException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/exception/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/BufferedHttpResponse.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/ContentType.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/PagedResponseBase.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/UrlBuilder.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/UrlToken.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenType.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenizer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenizerState.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/AfterRetryPolicyProvider.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/BeforeRetryPolicyProvider.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/HttpPolicyProviders.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/PolicyProvider.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseBodyDecoder.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseDecodeData.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseDecoder.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseHeaderDecoder.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/ItemPage.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/MalformedValueException.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/SerializerAdapter.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/SerializerEncoding.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesDeserializer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesSerializer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/Base64UrlSerializer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/ByteArraySerializer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DateTimeRfc1123Serializer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DateTimeSerializer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DurationSerializer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/FlatteningDeserializer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/FlatteningSerializer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/JacksonAdapter.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/serializer/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/tracing/Tracer.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/tracing/TracerProxy.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/util/Base64Util.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/util/FluxUtil.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/util/ImplUtils.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/util/ScopeUtil.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/util/TypeUtil.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/implementation/util/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/Context.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/ExpandableStringEnum.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/configuration/BaseConfigurations.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/configuration/Configuration.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/configuration/ConfigurationManager.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/configuration/NoopConfiguration.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/configuration/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/logging/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/package-info.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/polling/PollResponse.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/polling/Poller.java (100%) rename {core => sdk/core}/azure-core/src/main/java/com/azure/core/util/polling/package-info.java (100%) rename {core => sdk/core}/azure-core/src/samples/java/com/azure/core/http/rest/PagedFluxJavaDocCodeSnippets.java (100%) rename {core => sdk/core}/azure-core/src/samples/java/com/azure/core/implementation/util/ClientLoggerJavaDocCodeSnippets.java (100%) rename {core => sdk/core}/azure-core/src/samples/java/com/azure/core/implementation/util/FluxUtilJavaDocCodeSnippets.java (100%) rename {core => sdk/core}/azure-core/src/samples/java/com/azure/core/util/polling/PollResponseJavaDocCodeSnippets.java (100%) rename {core => sdk/core}/azure-core/src/samples/java/com/azure/core/util/polling/PollerJavaDocCodeSnippets.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/ConfigurationTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/MockServer.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/MyOtherRestException.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/MyRestException.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/UserAgentTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/credentials/CredentialsTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/credentials/TokenCacheTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/entities/AccessPolicy.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/entities/HttpBinFormDataJSON.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/entities/HttpBinHeaders.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/entities/HttpBinJSON.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/entities/SignedIdentifierInner.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/entities/SignedIdentifiersWrapper.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/entities/Slide.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/entities/Slideshow.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/HttpHeaderTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/HttpHeadersTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/HttpMethodTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/HttpPipelineTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/HttpRequestTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/MockHttpClient.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/MockHttpResponse.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/ReactorNettyClientTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/policy/HostPolicyTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/policy/ProtocolPolicyTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/policy/ProxyAuthenticationPolicyTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/policy/RequestIdPolicyTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/policy/RetryPolicyTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/http/rest/PagedFluxTest.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/Base64UrlTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/EncodedParameterTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/RestProxyStressTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/RestProxyTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithHttpProxyNettyTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithMockTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithNettyTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/RestProxyXMLTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/SubstitutionTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/SwaggerInterfaceParserTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/SwaggerMethodParserTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/UrlEscaperTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/ValidatorTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/http/UrlBuilderTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/http/UrlTokenizerTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesSerializerTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/DateTimeSerializerTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/DurationSerializerTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/FlatteningSerializerTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/JacksonAdapterTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/util/Foo.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/util/FooChild.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/util/ImplUtilsTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/implementation/util/TypeUtilTests.java (100%) rename {core => sdk/core}/azure-core/src/test/java/com/azure/core/util/polling/PollerTests.java (100%) rename {core => sdk/core}/azure-core/src/test/resources/GetContainerACLs.xml (100%) rename {core => sdk/core}/azure-core/src/test/resources/GetXMLWithAttributes.xml (100%) rename {core => sdk/core}/azure-core/src/test/resources/upload.txt (100%) rename {core => sdk/core}/pom.xml (97%) diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml index d82894fb16af9..9a97c9831e858 100644 --- a/eng/.docsettings.yml +++ b/eng/.docsettings.yml @@ -43,9 +43,9 @@ known_presence_issues: - ['sdk/mediaservices/microsoft-azure-media', '#2847'] - ['mediaservices/data-plane', '#2847'] - ['core/build-tools', '#2847'] - - ['core/azure-core', '#2847'] - - ['core/azure-core-auth', '#2847'] - - ['core/azure-core-management', '#2847'] + - ['sdk/core/azure-core', '#2847'] + - ['sdk/core/azure-core-auth', '#2847'] + - ['sdk/core/azure-core-management', '#2847'] - ['cosmosdb/data-plane/commons-test-utils', '#2847'] - ['cosmosdb/data-plane/sdk', '#2847'] - ['sdk/cosmos/sdk', '#2847'] @@ -66,7 +66,7 @@ known_content_issues: - ['sdk/servicebus/README.md', '#3113'] - ['storage/data-plane/README.md', '#3113'] - ['storage/data-plane/swagger/README.md', '#3113'] - - ['core/README.md', '#3113'] + - ['sdk/core/README.md', '#3113'] - ['cosmosdb/data-plane/README.md', '#3113'] - ['cosmosdb/data-plane/benchmark/README.md', '#3113'] - ['cosmosdb/data-plane/changelog/README.md', '#3113'] diff --git a/pom.client.xml b/pom.client.xml index 6d5510e1db74a..d4ed7878ba447 100644 --- a/pom.client.xml +++ b/pom.client.xml @@ -740,7 +740,7 @@ ./sdk/appconfiguration/azure-data-appconfiguration - ./core + ./sdk/core ./sdk/eventhubs/azure-eventhubs ./sdk/keyvault/azure-keyvault-secrets ./sdk/keyvault/azure-keyvault-keys diff --git a/sdk/appconfiguration/pom.service.xml b/sdk/appconfiguration/pom.service.xml index e33082c71b929..5e032d27570c0 100644 --- a/sdk/appconfiguration/pom.service.xml +++ b/sdk/appconfiguration/pom.service.xml @@ -9,7 +9,7 @@ pom 1.0.0 + ../core azure-data-appconfiguration - ../../core diff --git a/core/.gitignore b/sdk/core/.gitignore similarity index 100% rename from core/.gitignore rename to sdk/core/.gitignore diff --git a/core/README.md b/sdk/core/README.md similarity index 100% rename from core/README.md rename to sdk/core/README.md diff --git a/core/azure-core-amqp/README.md b/sdk/core/azure-core-amqp/README.md similarity index 100% rename from core/azure-core-amqp/README.md rename to sdk/core/azure-core-amqp/README.md diff --git a/core/azure-core-amqp/pom.xml b/sdk/core/azure-core-amqp/pom.xml similarity index 100% rename from core/azure-core-amqp/pom.xml rename to sdk/core/azure-core-amqp/pom.xml diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpConnection.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpConnection.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpConnection.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpConnection.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpEndpointState.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpEndpointState.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpEndpointState.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpEndpointState.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpExceptionHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpExceptionHandler.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpExceptionHandler.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpExceptionHandler.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpLink.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpLink.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpLink.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpLink.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpSession.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpSession.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpSession.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpSession.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpShutdownSignal.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpShutdownSignal.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpShutdownSignal.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpShutdownSignal.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/CBSNode.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/CBSNode.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/CBSNode.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/CBSNode.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/EndpointStateNotifier.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/EndpointStateNotifier.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/EndpointStateNotifier.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/EndpointStateNotifier.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/ExponentialRetry.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/ExponentialRetry.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/ExponentialRetry.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/ExponentialRetry.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/MessageConstant.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/MessageConstant.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/MessageConstant.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/MessageConstant.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/Retry.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/Retry.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/Retry.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/Retry.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/TransportType.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/TransportType.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/TransportType.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/TransportType.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/AmqpException.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/AmqpException.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/AmqpException.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/AmqpException.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/AmqpResponseCode.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/AmqpResponseCode.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/AmqpResponseCode.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/AmqpResponseCode.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ErrorCondition.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ErrorCondition.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ErrorCondition.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ErrorCondition.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ErrorContext.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ErrorContext.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ErrorContext.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ErrorContext.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ExceptionUtil.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ExceptionUtil.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ExceptionUtil.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/ExceptionUtil.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/LinkErrorContext.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/LinkErrorContext.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/LinkErrorContext.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/LinkErrorContext.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/OperationCancelledException.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/OperationCancelledException.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/OperationCancelledException.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/OperationCancelledException.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/SessionErrorContext.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/SessionErrorContext.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/SessionErrorContext.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/SessionErrorContext.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/package-info.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/package-info.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/package-info.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/exception/package-info.java diff --git a/core/azure-core-amqp/src/main/java/com/azure/core/amqp/package-info.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/package-info.java similarity index 100% rename from core/azure-core-amqp/src/main/java/com/azure/core/amqp/package-info.java rename to sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/package-info.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/AmqpShutdownSignalTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/AmqpShutdownSignalTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/AmqpShutdownSignalTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/AmqpShutdownSignalTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/ExponentialRetryTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/ExponentialRetryTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/ExponentialRetryTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/ExponentialRetryTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/MessageConstantTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/MessageConstantTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/MessageConstantTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/MessageConstantTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/RetryTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/RetryTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/RetryTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/RetryTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/TransportTypeTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/TransportTypeTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/TransportTypeTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/TransportTypeTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/AmqpExceptionTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/AmqpExceptionTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/AmqpExceptionTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/AmqpExceptionTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/AmqpResponseCodeTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/AmqpResponseCodeTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/AmqpResponseCodeTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/AmqpResponseCodeTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/ErrorContextTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/ErrorContextTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/ErrorContextTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/ErrorContextTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/ExceptionUtilTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/ExceptionUtilTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/ExceptionUtilTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/ExceptionUtilTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/LinkErrorContextTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/LinkErrorContextTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/LinkErrorContextTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/LinkErrorContextTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/OperationCancelledExceptionTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/OperationCancelledExceptionTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/OperationCancelledExceptionTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/OperationCancelledExceptionTest.java diff --git a/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/SessionErrorContextTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/SessionErrorContextTest.java similarity index 100% rename from core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/SessionErrorContextTest.java rename to sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/exception/SessionErrorContextTest.java diff --git a/core/azure-core-management/pom.xml b/sdk/core/azure-core-management/pom.xml similarity index 100% rename from core/azure-core-management/pom.xml rename to sdk/core/azure-core-management/pom.xml diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/AsyncOperationResource.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/AsyncOperationResource.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/AsyncOperationResource.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/AsyncOperationResource.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/CloudError.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/CloudError.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/CloudError.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/CloudError.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/CloudException.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/CloudException.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/CloudException.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/CloudException.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/OperationState.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/OperationState.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/OperationState.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/OperationState.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/Page.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/Page.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/Page.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/Page.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/PagedList.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/PagedList.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/PagedList.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/PagedList.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/Resource.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/Resource.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/Resource.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/Resource.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/SubResource.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/SubResource.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/SubResource.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/SubResource.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/annotations/AzureHost.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/annotations/AzureHost.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/annotations/AzureHost.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/annotations/AzureHost.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/annotations/package-info.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/annotations/package-info.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/annotations/package-info.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/annotations/package-info.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/implementation/AzureAsyncOperationPollStrategy.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/AzureAsyncOperationPollStrategy.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/implementation/AzureAsyncOperationPollStrategy.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/AzureAsyncOperationPollStrategy.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/implementation/AzureProxy.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/AzureProxy.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/implementation/AzureProxy.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/AzureProxy.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/implementation/CompletedPollStrategy.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/CompletedPollStrategy.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/implementation/CompletedPollStrategy.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/CompletedPollStrategy.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/implementation/LocationPollStrategy.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/LocationPollStrategy.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/implementation/LocationPollStrategy.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/LocationPollStrategy.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/implementation/OperationStatus.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/OperationStatus.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/implementation/OperationStatus.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/OperationStatus.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/implementation/PollStrategy.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/PollStrategy.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/implementation/PollStrategy.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/PollStrategy.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/implementation/ProvisioningStatePollStrategy.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/ProvisioningStatePollStrategy.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/implementation/ProvisioningStatePollStrategy.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/ProvisioningStatePollStrategy.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/implementation/ResourceWithProvisioningState.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/ResourceWithProvisioningState.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/implementation/ResourceWithProvisioningState.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/ResourceWithProvisioningState.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/package-info.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/package-info.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/package-info.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/package-info.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/serializer/AzureJacksonAdapter.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/serializer/AzureJacksonAdapter.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/serializer/AzureJacksonAdapter.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/serializer/AzureJacksonAdapter.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/serializer/CloudErrorDeserializer.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/serializer/CloudErrorDeserializer.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/serializer/CloudErrorDeserializer.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/serializer/CloudErrorDeserializer.java diff --git a/core/azure-core-management/src/main/java/com/azure/core/management/serializer/package-info.java b/sdk/core/azure-core-management/src/main/java/com/azure/core/management/serializer/package-info.java similarity index 100% rename from core/azure-core-management/src/main/java/com/azure/core/management/serializer/package-info.java rename to sdk/core/azure-core-management/src/main/java/com/azure/core/management/serializer/package-info.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyTests.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyTests.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyTests.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyTests.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyWithMockTests.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyWithMockTests.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyWithMockTests.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyWithMockTests.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyWithNettyTests.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyWithNettyTests.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyWithNettyTests.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureProxyToRestProxyWithNettyTests.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/AzureTests.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureTests.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/AzureTests.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/AzureTests.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/HttpBinJSON.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/HttpBinJSON.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/HttpBinJSON.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/HttpBinJSON.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/MockResource.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/MockResource.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/MockResource.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/MockResource.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/MyAzureException.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/MyAzureException.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/MyAzureException.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/MyAzureException.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/PagedListTests.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/PagedListTests.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/PagedListTests.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/PagedListTests.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/http/MockAzureHttpClient.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/http/MockAzureHttpClient.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/http/MockAzureHttpClient.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/http/MockAzureHttpClient.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/implementation/AzureProxyTests.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/implementation/AzureProxyTests.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/implementation/AzureProxyTests.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/implementation/AzureProxyTests.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/implementation/Value.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/implementation/Value.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/implementation/Value.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/implementation/Value.java diff --git a/core/azure-core-management/src/test/java/com/azure/core/management/implementation/ValueTests.java b/sdk/core/azure-core-management/src/test/java/com/azure/core/management/implementation/ValueTests.java similarity index 100% rename from core/azure-core-management/src/test/java/com/azure/core/management/implementation/ValueTests.java rename to sdk/core/azure-core-management/src/test/java/com/azure/core/management/implementation/ValueTests.java diff --git a/core/azure-core-test/README.md b/sdk/core/azure-core-test/README.md similarity index 100% rename from core/azure-core-test/README.md rename to sdk/core/azure-core-test/README.md diff --git a/core/azure-core-test/pom.xml b/sdk/core/azure-core-test/pom.xml similarity index 100% rename from core/azure-core-test/pom.xml rename to sdk/core/azure-core-test/pom.xml diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/InterceptorManager.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/InterceptorManager.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/InterceptorManager.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/InterceptorManager.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/TestBase.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestBase.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/TestBase.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestBase.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/TestMode.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestMode.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/TestMode.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/TestMode.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/http/MockHttpResponse.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/http/MockHttpResponse.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/http/MockHttpResponse.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/http/MockHttpResponse.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/http/PlaybackClient.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/http/PlaybackClient.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/http/PlaybackClient.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/http/PlaybackClient.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/http/package-info.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/http/package-info.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/http/package-info.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/http/package-info.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/models/NetworkCallRecord.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/models/NetworkCallRecord.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/models/NetworkCallRecord.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/models/NetworkCallRecord.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/models/RecordedData.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/models/RecordedData.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/models/RecordedData.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/models/RecordedData.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/models/package-info.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/models/package-info.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/models/package-info.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/models/package-info.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/package-info.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/package-info.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/package-info.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/package-info.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/policy/RecordNetworkCallPolicy.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/policy/RecordNetworkCallPolicy.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/policy/RecordNetworkCallPolicy.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/policy/RecordNetworkCallPolicy.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/policy/package-info.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/policy/package-info.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/policy/package-info.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/policy/package-info.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/utils/ResourceNamer.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/utils/ResourceNamer.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/utils/ResourceNamer.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/utils/ResourceNamer.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/utils/TestResourceNamer.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/utils/TestResourceNamer.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/utils/TestResourceNamer.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/utils/TestResourceNamer.java diff --git a/core/azure-core-test/src/main/java/com/azure/core/test/utils/package-info.java b/sdk/core/azure-core-test/src/main/java/com/azure/core/test/utils/package-info.java similarity index 100% rename from core/azure-core-test/src/main/java/com/azure/core/test/utils/package-info.java rename to sdk/core/azure-core-test/src/main/java/com/azure/core/test/utils/package-info.java diff --git a/core/azure-core/README.md b/sdk/core/azure-core/README.md similarity index 100% rename from core/azure-core/README.md rename to sdk/core/azure-core/README.md diff --git a/core/azure-core/pom.xml b/sdk/core/azure-core/pom.xml similarity index 100% rename from core/azure-core/pom.xml rename to sdk/core/azure-core/pom.xml diff --git a/core/azure-core/src/main/java/com/azure/core/AzureEnvironment.java b/sdk/core/azure-core/src/main/java/com/azure/core/AzureEnvironment.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/AzureEnvironment.java rename to sdk/core/azure-core/src/main/java/com/azure/core/AzureEnvironment.java diff --git a/core/azure-core/src/main/java/com/azure/core/credentials/AccessToken.java b/sdk/core/azure-core/src/main/java/com/azure/core/credentials/AccessToken.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/credentials/AccessToken.java rename to sdk/core/azure-core/src/main/java/com/azure/core/credentials/AccessToken.java diff --git a/core/azure-core/src/main/java/com/azure/core/credentials/BasicAuthenticationCredential.java b/sdk/core/azure-core/src/main/java/com/azure/core/credentials/BasicAuthenticationCredential.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/credentials/BasicAuthenticationCredential.java rename to sdk/core/azure-core/src/main/java/com/azure/core/credentials/BasicAuthenticationCredential.java diff --git a/core/azure-core/src/main/java/com/azure/core/credentials/SimpleTokenCache.java b/sdk/core/azure-core/src/main/java/com/azure/core/credentials/SimpleTokenCache.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/credentials/SimpleTokenCache.java rename to sdk/core/azure-core/src/main/java/com/azure/core/credentials/SimpleTokenCache.java diff --git a/core/azure-core/src/main/java/com/azure/core/credentials/TokenCredential.java b/sdk/core/azure-core/src/main/java/com/azure/core/credentials/TokenCredential.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/credentials/TokenCredential.java rename to sdk/core/azure-core/src/main/java/com/azure/core/credentials/TokenCredential.java diff --git a/core/azure-core/src/main/java/com/azure/core/credentials/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/credentials/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/credentials/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/credentials/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/AzureException.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/AzureException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/AzureException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/AzureException.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/ClientAuthenticationException.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/ClientAuthenticationException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/ClientAuthenticationException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/ClientAuthenticationException.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/DecodeException.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/DecodeException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/DecodeException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/DecodeException.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/HttpRequestException.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/HttpRequestException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/HttpRequestException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/HttpRequestException.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/HttpResponseException.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/HttpResponseException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/HttpResponseException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/HttpResponseException.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/ResourceExistsException.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/ResourceExistsException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/ResourceExistsException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/ResourceExistsException.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/ResourceModifiedException.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/ResourceModifiedException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/ResourceModifiedException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/ResourceModifiedException.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/ResourceNotFoundException.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/ResourceNotFoundException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/ResourceNotFoundException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/ResourceNotFoundException.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/ServiceResponseException.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/ServiceResponseException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/ServiceResponseException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/ServiceResponseException.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/TooManyRedirectsException.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/TooManyRedirectsException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/TooManyRedirectsException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/TooManyRedirectsException.java diff --git a/core/azure-core/src/main/java/com/azure/core/exception/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/exception/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/exception/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/exception/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/HttpClient.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpClient.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/HttpClient.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/HttpClient.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/HttpHeader.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpHeader.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/HttpHeader.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/HttpHeader.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/HttpHeaders.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpHeaders.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/HttpHeaders.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/HttpHeaders.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/HttpMethod.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpMethod.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/HttpMethod.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/HttpMethod.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/HttpPipeline.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpPipeline.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/HttpPipeline.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/HttpPipeline.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/HttpPipelineBuilder.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpPipelineBuilder.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/HttpPipelineBuilder.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/HttpPipelineBuilder.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/HttpPipelineCallContext.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpPipelineCallContext.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/HttpPipelineCallContext.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/HttpPipelineCallContext.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/HttpPipelineNextPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpPipelineNextPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/HttpPipelineNextPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/HttpPipelineNextPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/HttpRequest.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpRequest.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/HttpRequest.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/HttpRequest.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/HttpResponse.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpResponse.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/HttpResponse.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/HttpResponse.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/ProxyOptions.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/ReactorNettyClient.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/ReactorNettyClient.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/ReactorNettyClient.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/ReactorNettyClient.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/AddDatePolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AddDatePolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/AddDatePolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AddDatePolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/AddHeadersPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AddHeadersPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/AddHeadersPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AddHeadersPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/BearerTokenAuthenticationPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/BearerTokenAuthenticationPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/BearerTokenAuthenticationPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/BearerTokenAuthenticationPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/CookiePolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/CookiePolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/CookiePolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/CookiePolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/HostPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HostPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/HostPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HostPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogDetailLevel.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogDetailLevel.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogDetailLevel.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogDetailLevel.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/HttpPipelinePolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpPipelinePolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/HttpPipelinePolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpPipelinePolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/PortPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/PortPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/PortPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/PortPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/ProtocolPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ProtocolPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/ProtocolPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ProtocolPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/ProxyAuthenticationPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ProxyAuthenticationPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/ProxyAuthenticationPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ProxyAuthenticationPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/RequestIdPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RequestIdPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/RequestIdPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RequestIdPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/RetryPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RetryPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/RetryPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RetryPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/TimeoutPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/TimeoutPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/TimeoutPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/TimeoutPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/UserAgentPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/UserAgentPolicy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/UserAgentPolicy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/UserAgentPolicy.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/policy/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/policy/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/policy/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/rest/Page.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/Page.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/rest/Page.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/rest/Page.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/rest/PagedFlux.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/PagedFlux.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/rest/PagedFlux.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/rest/PagedFlux.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/rest/PagedResponse.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/PagedResponse.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/rest/PagedResponse.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/rest/PagedResponse.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/rest/Response.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/Response.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/rest/Response.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/rest/Response.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/rest/ResponseBase.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/ResponseBase.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/rest/ResponseBase.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/rest/ResponseBase.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/rest/SimpleResponse.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/SimpleResponse.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/rest/SimpleResponse.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/rest/SimpleResponse.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/rest/StreamResponse.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/StreamResponse.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/rest/StreamResponse.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/rest/StreamResponse.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/rest/VoidResponse.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/VoidResponse.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/rest/VoidResponse.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/rest/VoidResponse.java diff --git a/core/azure-core/src/main/java/com/azure/core/http/rest/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/http/rest/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/http/rest/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/Base64Url.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/Base64Url.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/Base64Url.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/Base64Url.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/CollectionFormat.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/CollectionFormat.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/CollectionFormat.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/CollectionFormat.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/DateTimeRfc1123.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/DateTimeRfc1123.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/DateTimeRfc1123.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/DateTimeRfc1123.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/EncodedParameter.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/EncodedParameter.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/EncodedParameter.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/EncodedParameter.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/OperationDescription.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/OperationDescription.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/OperationDescription.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/OperationDescription.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/PercentEscaper.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/PercentEscaper.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/PercentEscaper.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/PercentEscaper.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/RestProxy.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/RestProxy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/RestProxy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/RestProxy.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/Substitution.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/Substitution.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/Substitution.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/Substitution.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/SwaggerInterfaceParser.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/SwaggerInterfaceParser.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/SwaggerInterfaceParser.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/SwaggerInterfaceParser.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/SwaggerMethodParser.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/SwaggerMethodParser.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/SwaggerMethodParser.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/SwaggerMethodParser.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/UnexpectedExceptionInformation.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/UnexpectedExceptionInformation.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/UnexpectedExceptionInformation.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/UnexpectedExceptionInformation.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/UnixTime.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/UnixTime.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/UnixTime.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/UnixTime.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/UrlEscapers.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/UrlEscapers.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/UrlEscapers.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/UrlEscapers.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/Validator.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/Validator.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/Validator.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/Validator.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Beta.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Beta.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Beta.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Beta.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/BodyParam.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/BodyParam.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/BodyParam.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/BodyParam.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Delete.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Delete.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Delete.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Delete.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ExpectedResponses.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ExpectedResponses.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/ExpectedResponses.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ExpectedResponses.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Fluent.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Fluent.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Fluent.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Fluent.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/FormParam.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/FormParam.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/FormParam.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/FormParam.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Get.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Get.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Get.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Get.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Head.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Head.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Head.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Head.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/HeaderCollection.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/HeaderCollection.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/HeaderCollection.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/HeaderCollection.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/HeaderParam.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/HeaderParam.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/HeaderParam.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/HeaderParam.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Headers.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Headers.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Headers.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Headers.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Host.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Host.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Host.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Host.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/HostParam.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/HostParam.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/HostParam.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/HostParam.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Immutable.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Immutable.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Immutable.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Immutable.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/JsonFlatten.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/JsonFlatten.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/JsonFlatten.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/JsonFlatten.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Patch.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Patch.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Patch.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Patch.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/PathParam.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/PathParam.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/PathParam.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/PathParam.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Post.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Post.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Post.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Post.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Put.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Put.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/Put.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/Put.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/QueryParam.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/QueryParam.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/QueryParam.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/QueryParam.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ResumeOperation.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ResumeOperation.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/ResumeOperation.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ResumeOperation.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ReturnType.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ReturnType.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/ReturnType.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ReturnType.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ReturnValueWireType.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ReturnValueWireType.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/ReturnValueWireType.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ReturnValueWireType.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceClient.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceClient.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceClient.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceClient.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceClientBuilder.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceClientBuilder.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceClientBuilder.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceClientBuilder.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceInterface.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceInterface.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceInterface.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceInterface.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceMethod.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceMethod.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceMethod.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/ServiceMethod.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/SkipParentValidation.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/SkipParentValidation.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/SkipParentValidation.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/SkipParentValidation.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/UnexpectedResponseExceptionType.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/UnexpectedResponseExceptionType.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/UnexpectedResponseExceptionType.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/UnexpectedResponseExceptionType.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/UnexpectedResponseExceptionTypes.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/UnexpectedResponseExceptionTypes.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/UnexpectedResponseExceptionTypes.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/UnexpectedResponseExceptionTypes.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/annotation/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/annotation/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/annotation/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/exception/InvalidReturnTypeException.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/exception/InvalidReturnTypeException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/exception/InvalidReturnTypeException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/exception/InvalidReturnTypeException.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/exception/MissingRequiredAnnotationException.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/exception/MissingRequiredAnnotationException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/exception/MissingRequiredAnnotationException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/exception/MissingRequiredAnnotationException.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/exception/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/exception/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/exception/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/exception/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/BufferedHttpResponse.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/BufferedHttpResponse.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/BufferedHttpResponse.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/BufferedHttpResponse.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/ContentType.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/ContentType.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/ContentType.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/ContentType.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/PagedResponseBase.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/PagedResponseBase.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/PagedResponseBase.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/PagedResponseBase.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlBuilder.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlBuilder.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/UrlBuilder.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlBuilder.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlToken.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlToken.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/UrlToken.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlToken.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenType.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenType.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenType.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenType.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenizer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenizer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenizer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenizer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenizerState.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenizerState.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenizerState.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/UrlTokenizerState.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/AfterRetryPolicyProvider.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/AfterRetryPolicyProvider.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/AfterRetryPolicyProvider.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/AfterRetryPolicyProvider.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/BeforeRetryPolicyProvider.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/BeforeRetryPolicyProvider.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/BeforeRetryPolicyProvider.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/BeforeRetryPolicyProvider.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/HttpPolicyProviders.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/HttpPolicyProviders.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/HttpPolicyProviders.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/HttpPolicyProviders.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/PolicyProvider.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/PolicyProvider.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/PolicyProvider.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/PolicyProvider.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/policy/spi/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseBodyDecoder.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseBodyDecoder.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseBodyDecoder.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseBodyDecoder.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseDecodeData.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseDecodeData.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseDecodeData.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseDecodeData.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseDecoder.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseDecoder.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseDecoder.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseDecoder.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseHeaderDecoder.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseHeaderDecoder.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseHeaderDecoder.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseHeaderDecoder.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/ItemPage.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/ItemPage.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/ItemPage.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/ItemPage.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/MalformedValueException.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/MalformedValueException.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/MalformedValueException.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/MalformedValueException.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/SerializerAdapter.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/SerializerAdapter.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/SerializerAdapter.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/SerializerAdapter.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/SerializerEncoding.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/SerializerEncoding.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/SerializerEncoding.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/SerializerEncoding.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesDeserializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesDeserializer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesDeserializer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesDeserializer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesSerializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesSerializer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesSerializer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesSerializer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/Base64UrlSerializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/Base64UrlSerializer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/Base64UrlSerializer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/Base64UrlSerializer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/ByteArraySerializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/ByteArraySerializer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/ByteArraySerializer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/ByteArraySerializer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DateTimeRfc1123Serializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DateTimeRfc1123Serializer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DateTimeRfc1123Serializer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DateTimeRfc1123Serializer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DateTimeSerializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DateTimeSerializer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DateTimeSerializer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DateTimeSerializer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DurationSerializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DurationSerializer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DurationSerializer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/DurationSerializer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/FlatteningDeserializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/FlatteningDeserializer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/FlatteningDeserializer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/FlatteningDeserializer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/FlatteningSerializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/FlatteningSerializer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/FlatteningSerializer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/FlatteningSerializer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/JacksonAdapter.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/JacksonAdapter.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/JacksonAdapter.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/JacksonAdapter.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/jackson/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/serializer/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/serializer/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/tracing/Tracer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/tracing/Tracer.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/tracing/Tracer.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/tracing/Tracer.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/tracing/TracerProxy.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/tracing/TracerProxy.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/tracing/TracerProxy.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/tracing/TracerProxy.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/util/Base64Util.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/Base64Util.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/util/Base64Util.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/Base64Util.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/util/FluxUtil.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/FluxUtil.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/util/FluxUtil.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/FluxUtil.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/util/ImplUtils.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/ImplUtils.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/util/ImplUtils.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/ImplUtils.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/util/ScopeUtil.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/ScopeUtil.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/util/ScopeUtil.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/ScopeUtil.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/util/TypeUtil.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/TypeUtil.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/util/TypeUtil.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/TypeUtil.java diff --git a/core/azure-core/src/main/java/com/azure/core/implementation/util/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/implementation/util/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/implementation/util/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/Context.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/Context.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/Context.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/Context.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/ExpandableStringEnum.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/ExpandableStringEnum.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/ExpandableStringEnum.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/ExpandableStringEnum.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/configuration/BaseConfigurations.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/configuration/BaseConfigurations.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/configuration/BaseConfigurations.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/configuration/BaseConfigurations.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/configuration/Configuration.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/configuration/Configuration.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/configuration/Configuration.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/configuration/Configuration.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/configuration/ConfigurationManager.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/configuration/ConfigurationManager.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/configuration/ConfigurationManager.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/configuration/ConfigurationManager.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/configuration/NoopConfiguration.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/configuration/NoopConfiguration.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/configuration/NoopConfiguration.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/configuration/NoopConfiguration.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/configuration/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/configuration/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/configuration/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/configuration/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/logging/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/logging/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/logging/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/package-info.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/polling/PollResponse.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollResponse.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/polling/PollResponse.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollResponse.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/polling/Poller.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/Poller.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/polling/Poller.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/polling/Poller.java diff --git a/core/azure-core/src/main/java/com/azure/core/util/polling/package-info.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/package-info.java similarity index 100% rename from core/azure-core/src/main/java/com/azure/core/util/polling/package-info.java rename to sdk/core/azure-core/src/main/java/com/azure/core/util/polling/package-info.java diff --git a/core/azure-core/src/samples/java/com/azure/core/http/rest/PagedFluxJavaDocCodeSnippets.java b/sdk/core/azure-core/src/samples/java/com/azure/core/http/rest/PagedFluxJavaDocCodeSnippets.java similarity index 100% rename from core/azure-core/src/samples/java/com/azure/core/http/rest/PagedFluxJavaDocCodeSnippets.java rename to sdk/core/azure-core/src/samples/java/com/azure/core/http/rest/PagedFluxJavaDocCodeSnippets.java diff --git a/core/azure-core/src/samples/java/com/azure/core/implementation/util/ClientLoggerJavaDocCodeSnippets.java b/sdk/core/azure-core/src/samples/java/com/azure/core/implementation/util/ClientLoggerJavaDocCodeSnippets.java similarity index 100% rename from core/azure-core/src/samples/java/com/azure/core/implementation/util/ClientLoggerJavaDocCodeSnippets.java rename to sdk/core/azure-core/src/samples/java/com/azure/core/implementation/util/ClientLoggerJavaDocCodeSnippets.java diff --git a/core/azure-core/src/samples/java/com/azure/core/implementation/util/FluxUtilJavaDocCodeSnippets.java b/sdk/core/azure-core/src/samples/java/com/azure/core/implementation/util/FluxUtilJavaDocCodeSnippets.java similarity index 100% rename from core/azure-core/src/samples/java/com/azure/core/implementation/util/FluxUtilJavaDocCodeSnippets.java rename to sdk/core/azure-core/src/samples/java/com/azure/core/implementation/util/FluxUtilJavaDocCodeSnippets.java diff --git a/core/azure-core/src/samples/java/com/azure/core/util/polling/PollResponseJavaDocCodeSnippets.java b/sdk/core/azure-core/src/samples/java/com/azure/core/util/polling/PollResponseJavaDocCodeSnippets.java similarity index 100% rename from core/azure-core/src/samples/java/com/azure/core/util/polling/PollResponseJavaDocCodeSnippets.java rename to sdk/core/azure-core/src/samples/java/com/azure/core/util/polling/PollResponseJavaDocCodeSnippets.java diff --git a/core/azure-core/src/samples/java/com/azure/core/util/polling/PollerJavaDocCodeSnippets.java b/sdk/core/azure-core/src/samples/java/com/azure/core/util/polling/PollerJavaDocCodeSnippets.java similarity index 100% rename from core/azure-core/src/samples/java/com/azure/core/util/polling/PollerJavaDocCodeSnippets.java rename to sdk/core/azure-core/src/samples/java/com/azure/core/util/polling/PollerJavaDocCodeSnippets.java diff --git a/core/azure-core/src/test/java/com/azure/core/ConfigurationTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/ConfigurationTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/ConfigurationTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/ConfigurationTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/MockServer.java b/sdk/core/azure-core/src/test/java/com/azure/core/MockServer.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/MockServer.java rename to sdk/core/azure-core/src/test/java/com/azure/core/MockServer.java diff --git a/core/azure-core/src/test/java/com/azure/core/MyOtherRestException.java b/sdk/core/azure-core/src/test/java/com/azure/core/MyOtherRestException.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/MyOtherRestException.java rename to sdk/core/azure-core/src/test/java/com/azure/core/MyOtherRestException.java diff --git a/core/azure-core/src/test/java/com/azure/core/MyRestException.java b/sdk/core/azure-core/src/test/java/com/azure/core/MyRestException.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/MyRestException.java rename to sdk/core/azure-core/src/test/java/com/azure/core/MyRestException.java diff --git a/core/azure-core/src/test/java/com/azure/core/UserAgentTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/UserAgentTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/UserAgentTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/UserAgentTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/credentials/CredentialsTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/credentials/CredentialsTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/credentials/CredentialsTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/credentials/CredentialsTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/credentials/TokenCacheTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/credentials/TokenCacheTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/credentials/TokenCacheTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/credentials/TokenCacheTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/entities/AccessPolicy.java b/sdk/core/azure-core/src/test/java/com/azure/core/entities/AccessPolicy.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/entities/AccessPolicy.java rename to sdk/core/azure-core/src/test/java/com/azure/core/entities/AccessPolicy.java diff --git a/core/azure-core/src/test/java/com/azure/core/entities/HttpBinFormDataJSON.java b/sdk/core/azure-core/src/test/java/com/azure/core/entities/HttpBinFormDataJSON.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/entities/HttpBinFormDataJSON.java rename to sdk/core/azure-core/src/test/java/com/azure/core/entities/HttpBinFormDataJSON.java diff --git a/core/azure-core/src/test/java/com/azure/core/entities/HttpBinHeaders.java b/sdk/core/azure-core/src/test/java/com/azure/core/entities/HttpBinHeaders.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/entities/HttpBinHeaders.java rename to sdk/core/azure-core/src/test/java/com/azure/core/entities/HttpBinHeaders.java diff --git a/core/azure-core/src/test/java/com/azure/core/entities/HttpBinJSON.java b/sdk/core/azure-core/src/test/java/com/azure/core/entities/HttpBinJSON.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/entities/HttpBinJSON.java rename to sdk/core/azure-core/src/test/java/com/azure/core/entities/HttpBinJSON.java diff --git a/core/azure-core/src/test/java/com/azure/core/entities/SignedIdentifierInner.java b/sdk/core/azure-core/src/test/java/com/azure/core/entities/SignedIdentifierInner.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/entities/SignedIdentifierInner.java rename to sdk/core/azure-core/src/test/java/com/azure/core/entities/SignedIdentifierInner.java diff --git a/core/azure-core/src/test/java/com/azure/core/entities/SignedIdentifiersWrapper.java b/sdk/core/azure-core/src/test/java/com/azure/core/entities/SignedIdentifiersWrapper.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/entities/SignedIdentifiersWrapper.java rename to sdk/core/azure-core/src/test/java/com/azure/core/entities/SignedIdentifiersWrapper.java diff --git a/core/azure-core/src/test/java/com/azure/core/entities/Slide.java b/sdk/core/azure-core/src/test/java/com/azure/core/entities/Slide.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/entities/Slide.java rename to sdk/core/azure-core/src/test/java/com/azure/core/entities/Slide.java diff --git a/core/azure-core/src/test/java/com/azure/core/entities/Slideshow.java b/sdk/core/azure-core/src/test/java/com/azure/core/entities/Slideshow.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/entities/Slideshow.java rename to sdk/core/azure-core/src/test/java/com/azure/core/entities/Slideshow.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/HttpHeaderTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/HttpHeaderTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/HttpHeaderTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/HttpHeaderTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/HttpHeadersTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/HttpHeadersTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/HttpHeadersTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/HttpHeadersTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/HttpMethodTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/HttpMethodTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/HttpMethodTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/HttpMethodTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/HttpPipelineTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/HttpPipelineTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/HttpPipelineTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/HttpPipelineTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/HttpRequestTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/HttpRequestTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/HttpRequestTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/HttpRequestTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/MockHttpClient.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/MockHttpClient.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/MockHttpClient.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/MockHttpClient.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/MockHttpResponse.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/MockHttpResponse.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/MockHttpResponse.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/MockHttpResponse.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/ReactorNettyClientTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/ReactorNettyClientTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/ReactorNettyClientTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/ReactorNettyClientTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/policy/HostPolicyTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/policy/HostPolicyTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/policy/HostPolicyTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/policy/HostPolicyTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/policy/ProtocolPolicyTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/policy/ProtocolPolicyTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/policy/ProtocolPolicyTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/policy/ProtocolPolicyTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/policy/ProxyAuthenticationPolicyTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/policy/ProxyAuthenticationPolicyTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/policy/ProxyAuthenticationPolicyTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/policy/ProxyAuthenticationPolicyTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/policy/RequestIdPolicyTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/policy/RequestIdPolicyTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/policy/RequestIdPolicyTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/policy/RequestIdPolicyTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/policy/RetryPolicyTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/policy/RetryPolicyTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/policy/RetryPolicyTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/policy/RetryPolicyTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/http/rest/PagedFluxTest.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/rest/PagedFluxTest.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/http/rest/PagedFluxTest.java rename to sdk/core/azure-core/src/test/java/com/azure/core/http/rest/PagedFluxTest.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/Base64UrlTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/Base64UrlTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/Base64UrlTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/Base64UrlTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/EncodedParameterTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/EncodedParameterTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/EncodedParameterTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/EncodedParameterTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyStressTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyStressTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/RestProxyStressTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyStressTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/RestProxyTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithHttpProxyNettyTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithHttpProxyNettyTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithHttpProxyNettyTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithHttpProxyNettyTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithMockTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithMockTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithMockTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithMockTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithNettyTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithNettyTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithNettyTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyWithNettyTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyXMLTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyXMLTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/RestProxyXMLTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/RestProxyXMLTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/SubstitutionTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/SubstitutionTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/SubstitutionTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/SubstitutionTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/SwaggerInterfaceParserTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/SwaggerInterfaceParserTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/SwaggerInterfaceParserTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/SwaggerInterfaceParserTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/SwaggerMethodParserTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/SwaggerMethodParserTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/SwaggerMethodParserTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/SwaggerMethodParserTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/UrlEscaperTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/UrlEscaperTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/UrlEscaperTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/UrlEscaperTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/ValidatorTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/ValidatorTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/ValidatorTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/ValidatorTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/http/UrlBuilderTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/http/UrlBuilderTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/http/UrlBuilderTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/http/UrlBuilderTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/http/UrlTokenizerTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/http/UrlTokenizerTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/http/UrlTokenizerTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/http/UrlTokenizerTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesSerializerTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesSerializerTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesSerializerTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/AdditionalPropertiesSerializerTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/DateTimeSerializerTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/DateTimeSerializerTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/DateTimeSerializerTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/DateTimeSerializerTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/DurationSerializerTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/DurationSerializerTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/DurationSerializerTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/DurationSerializerTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/FlatteningSerializerTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/FlatteningSerializerTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/FlatteningSerializerTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/FlatteningSerializerTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/JacksonAdapterTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/JacksonAdapterTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/JacksonAdapterTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/serializer/jackson/JacksonAdapterTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/util/Foo.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/Foo.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/util/Foo.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/Foo.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/util/FooChild.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/FooChild.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/util/FooChild.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/FooChild.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/util/ImplUtilsTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/ImplUtilsTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/util/ImplUtilsTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/ImplUtilsTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/implementation/util/TypeUtilTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/TypeUtilTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/implementation/util/TypeUtilTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/TypeUtilTests.java diff --git a/core/azure-core/src/test/java/com/azure/core/util/polling/PollerTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/util/polling/PollerTests.java similarity index 100% rename from core/azure-core/src/test/java/com/azure/core/util/polling/PollerTests.java rename to sdk/core/azure-core/src/test/java/com/azure/core/util/polling/PollerTests.java diff --git a/core/azure-core/src/test/resources/GetContainerACLs.xml b/sdk/core/azure-core/src/test/resources/GetContainerACLs.xml similarity index 100% rename from core/azure-core/src/test/resources/GetContainerACLs.xml rename to sdk/core/azure-core/src/test/resources/GetContainerACLs.xml diff --git a/core/azure-core/src/test/resources/GetXMLWithAttributes.xml b/sdk/core/azure-core/src/test/resources/GetXMLWithAttributes.xml similarity index 100% rename from core/azure-core/src/test/resources/GetXMLWithAttributes.xml rename to sdk/core/azure-core/src/test/resources/GetXMLWithAttributes.xml diff --git a/core/azure-core/src/test/resources/upload.txt b/sdk/core/azure-core/src/test/resources/upload.txt similarity index 100% rename from core/azure-core/src/test/resources/upload.txt rename to sdk/core/azure-core/src/test/resources/upload.txt diff --git a/sdk/core/pom.service.xml b/sdk/core/pom.service.xml index 7c475cc3a4808..10c012fa679b8 100644 --- a/sdk/core/pom.service.xml +++ b/sdk/core/pom.service.xml @@ -9,6 +9,9 @@ pom 1.0.0 - + azure-core + azure-core-amqp + azure-core-management + azure-core-test diff --git a/core/pom.xml b/sdk/core/pom.xml similarity index 97% rename from core/pom.xml rename to sdk/core/pom.xml index 8a99642ce90cc..033b535580980 100644 --- a/core/pom.xml +++ b/sdk/core/pom.xml @@ -10,7 +10,7 @@ com.azure azure-client-sdk-parent 1.1.0 - ../pom.client.xml + ../../pom.client.xml com.azure diff --git a/sdk/eventhubs/pom.service.xml b/sdk/eventhubs/pom.service.xml index 2f81bff7b40e9..87821b3eed055 100644 --- a/sdk/eventhubs/pom.service.xml +++ b/sdk/eventhubs/pom.service.xml @@ -9,7 +9,7 @@ pom 1.0.0 - ../../core + ../core azure-eventhubs diff --git a/sdk/keyvault/pom.service.xml b/sdk/keyvault/pom.service.xml index 862a0ba0d96ee..98d1b31a7867c 100644 --- a/sdk/keyvault/pom.service.xml +++ b/sdk/keyvault/pom.service.xml @@ -19,7 +19,7 @@ microsoft-azure-keyvault-complete - ../../core + ../core ../identity/azure-identity azure-keyvault-keys azure-keyvault-secrets From 2fdc3c4b8f7ca5234e084331e550a3ae18303ebc Mon Sep 17 00:00:00 2001 From: Connie Yau Date: Fri, 12 Jul 2019 14:06:20 -0700 Subject: [PATCH 79/85] Fix NullPointerException when annotation is a nested class. (#4417) --- .../azure/tools/checkstyle/checks/JavadocThrowsChecks.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/JavadocThrowsChecks.java b/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/JavadocThrowsChecks.java index 01fd42149ae2b..c12eeb540056c 100644 --- a/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/JavadocThrowsChecks.java +++ b/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/JavadocThrowsChecks.java @@ -140,7 +140,10 @@ private boolean isOverrideAnnotation(DetailAST modifierToken) { return false; } - return "Override".equals(modifierToken.findFirstToken(TokenTypes.IDENT).getText()); + // Possible for an identifier not to exist if it is a nested class (ie. @Parameterized.Parameters(String)). + final DetailAST identifier = modifierToken.findFirstToken(TokenTypes.IDENT); + + return identifier != null && "Override".equals(identifier.getText()); } /* From 09fc4532250e8f1643443ceed92094f2d8ef8037 Mon Sep 17 00:00:00 2001 From: Hemant Tanwar Date: Sat, 13 Jul 2019 21:41:11 -0700 Subject: [PATCH 80/85] Implement PagedFlux in Keyvault (#4406) implementing pagination in in keyvault --- .../ConfigurationAsyncClient.java | 2 + .../keyvault/keys/KeyAsyncClient.java | 128 +++++++++------- .../keyvault/secrets/SecretAsyncClient.java | 137 +++++++++++------- 3 files changed, 163 insertions(+), 104 deletions(-) diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java index 23f233305f699..b3a14cfc735b2 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java @@ -761,7 +761,9 @@ private static void validateSetting(ConfigurationSetting setting) { * Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since * add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return * this status when the configuration doesn't exist. + * * @param throwable Error response from the service. + * * @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException, * otherwise the throwable is returned unmodified. */ diff --git a/sdk/keyvault/azure-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java b/sdk/keyvault/azure-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java index da44d45f04a26..f1e5d5057d5f0 100644 --- a/sdk/keyvault/azure-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java +++ b/sdk/keyvault/azure-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java @@ -7,17 +7,14 @@ import com.azure.core.exception.ResourceModifiedException; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; import com.azure.core.http.rest.VoidResponse; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedFlux; import com.azure.core.implementation.RestProxy; import com.azure.core.implementation.annotation.ServiceClient; -import com.azure.core.implementation.util.ImplUtils; -import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.keys.implementation.DeletedKeyPage; -import com.azure.security.keyvault.keys.implementation.KeyBasePage; import com.azure.security.keyvault.keys.models.DeletedKey; import com.azure.security.keyvault.keys.models.EcKeyCreateOptions; import com.azure.security.keyvault.keys.models.Key; @@ -34,7 +31,6 @@ import java.util.Objects; import java.util.function.Function; -import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -48,6 +44,7 @@ * {@codesnippet com.azure.security.keyvault.keys.async.keyclient.instantiation} * * @see KeyClientBuilder + * @see PagedFlux */ @ServiceClient(builder = KeyClientBuilder.class, isAsync = true, serviceInterfaces = KeyService.class) public final class KeyAsyncClient { @@ -629,14 +626,36 @@ public Mono> restoreKey(byte[] backup) { * .map(Response::value); * * - * @return A {@link Flux} containing {@link KeyBase key} of all the keys in the vault. + * @return A {@link PagedFlux} containing {@link KeyBase key} of all the keys in the vault. + */ + public PagedFlux listKeys() { + return new PagedFlux<>(() -> + listKeysFirstPage(), + continuationToken -> listKeysNextPage(continuationToken)); + } + + /* + * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to + * {@link KeyAsyncClient#listKeys()}. + * + * @param continuationToken The {@link PagedResponse#nextLink()} from a previous, successful call to one of the listKeys operations. + * @return A {@link Mono} of {@link PagedResponse} from the next page of results. */ - public Flux listKeys() { + private Mono> listKeysNextPage(String continuationToken) { + return service.getKeys(endpoint, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + .doOnRequest(ignored -> logger.info("Listing next keys page - Page {} ", continuationToken)) + .doOnSuccess(response -> logger.info("Listed next keys page - Page {} ", continuationToken)) + .doOnError(error -> logger.warning("Failed to list next keys page - Page {} ", continuationToken, error)); + } + + /* + * Calls the service and retrieve first page result. It makes one call and retrieve {@code DEFAULT_MAX_PAGE_RESULTS} values. + */ + private Mono> listKeysFirstPage() { return service.getKeys(endpoint, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) - .doOnRequest(ignored -> logger.info("Listing keys")) - .doOnSuccess(response -> logger.info("Listed keys")) - .doOnError(error -> logger.warning("Failed to list keys", error)) - .flatMapMany(r -> extractAndFetchKeys(r, Context.NONE)); + .doOnRequest(ignored -> logger.info("Listing keys")) + .doOnSuccess(response -> logger.info("Listed keys")) + .doOnError(error -> logger.warning("Failed to list keys", error)); } /** @@ -652,14 +671,36 @@ public Flux listKeys() { * System.out.printf("Deleted key's recovery Id %s \n", deletedKey.recoveryId())); * * - * @return A {@link Flux} containing all of the {@link DeletedKey deleted keys} in the vault. + * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ - public Flux listDeletedKeys() { + public PagedFlux listDeletedKeys() { + return new PagedFlux<>(() -> + listDeletedKeysFirstPage(), + continuationToken -> listDeletedKeysNextPage(continuationToken)); + } + + /* + * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to + * {@link KeyAsyncClient#listDeletedKeys()}. + * + * @param continuationToken The {@link PagedResponse#nextLink()} from a previous, successful call to one of the list operations. + * @return A {@link Mono} of {@link PagedResponse} from the next page of results. + */ + private Mono> listDeletedKeysNextPage(String continuationToken) { + return service.getDeletedKeys(endpoint, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + .doOnRequest(ignored -> logger.info("Listing next deleted keys page - Page {} ", continuationToken)) + .doOnSuccess(response -> logger.info("Listed next deleted keys page - Page {} ", continuationToken)) + .doOnError(error -> logger.warning("Failed to list next deleted keys page - Page {} ", continuationToken, error)); + } + + /* + * Calls the service and retrieve first page result. It makes one call and retrieve {@code DEFAULT_MAX_PAGE_RESULTS} values. + */ + private Mono> listDeletedKeysFirstPage() { return service.getDeletedKeys(endpoint, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) - .doOnRequest(ignored -> logger.info("Listing deleted keys")) - .doOnSuccess(response -> logger.info("Listed deleted keys")) - .doOnError(error -> logger.warning("Failed to list deleted keys", error)) - .flatMapMany(r -> extractAndFetchDeletedKeys(r, Context.NONE)); + .doOnRequest(ignored -> logger.info("Listing deleted keys")) + .doOnSuccess(response -> logger.info("Listed deleted keys")) + .doOnError(error -> logger.warning("Failed to list deleted keys", error)); } /** @@ -679,44 +720,33 @@ public Flux listDeletedKeys() { * @param name The name of the key. * @throws ResourceNotFoundException when a key with {@code name} doesn't exist in the key vault. * @throws HttpRequestException when a key with {@code name} is empty string. - * @return A {@link Flux} containing {@link KeyBase key} of all the versions of the specified key in the vault. Flux is empty if key with {@code name} does not exist in key vault. + * @return A {@link PagedFlux} containing {@link KeyBase key} of all the versions of the specified key in the vault. Flux is empty if key with {@code name} does not exist in key vault. */ - public Flux listKeyVersions(String name) { - return service.getKeyVersions(endpoint, name, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) - .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) - .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) - .doOnError(error -> logger.warning(String.format("Failed to list key versions - {}", name), error)) - .flatMapMany(r -> extractAndFetchKeys(r, Context.NONE)); + public PagedFlux listKeyVersions(String name) { + return new PagedFlux<>(() -> + listKeyVersionsFirstPage(name), + continuationToken -> listKeyVersionsNextPage(continuationToken)); } - /** - * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to - * {@link KeyAsyncClient#listKeys()}. - * - * @param nextPageLink The {@link KeyBasePage#nextLink()} from a previous, successful call to one of the list operations. - * @return A stream of {@link KeyBase key} from the next page of results. - */ - private Flux listKeysNext(String nextPageLink, Context context) { - return service.getKeys(endpoint, nextPageLink, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE).flatMapMany(r -> extractAndFetchKeys(r, context)); - } - - private Publisher extractAndFetchKeys(PagedResponse page, Context context) { - return ImplUtils.extractAndFetch(page, context, this::listKeysNext); + private Mono> listKeyVersionsFirstPage(String name) { + return service.getKeyVersions(endpoint, name, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + .doOnRequest(ignored -> logger.info("Listing key versions - {}", name)) + .doOnSuccess(response -> logger.info("Listed key versions - {}", name)) + .doOnError(error -> logger.warning(String.format("Failed to list key versions - {}", name), error)); } - /** + /* * Gets attributes of all the keys given by the {@code nextPageLink} that was retrieved from a call to - * {@link KeyAsyncClient#listDeletedKeys()}. + * {@link KeyAsyncClient#listKeyVersions()}. * - * @param nextPageLink The {@link DeletedKeyPage#nextLink()} from a previous, successful call to one of the list operations. - * @return A stream of {@link KeyBase key} from the next page of results. + * @param continuationToken The {@link PagedResponse#nextLink()} from a previous, successful call to one of the listKeys operations. + * @return A {@link Mono} of {@link PagedResponse} from the next page of results. */ - private Flux listDeletedKeysNext(String nextPageLink, Context context) { - return service.getDeletedKeys(endpoint, nextPageLink, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE).flatMapMany(r -> extractAndFetchDeletedKeys(r, context)); - } - - private Publisher extractAndFetchDeletedKeys(PagedResponse page, Context context) { - return ImplUtils.extractAndFetch(page, context, this::listDeletedKeysNext); + private Mono> listKeyVersionsNextPage(String continuationToken) { + return service.getKeys(endpoint, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + .doOnRequest(ignored -> logger.info("Listing next key versions page - Page {} ", continuationToken)) + .doOnSuccess(response -> logger.info("Listed next key versions page - Page {} ", continuationToken)) + .doOnError(error -> logger.warning("Failed to list next key versions page - Page {} ", continuationToken, error)); } } diff --git a/sdk/keyvault/azure-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java b/sdk/keyvault/azure-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java index 0ed4b9d76c89c..d7f491e520303 100644 --- a/sdk/keyvault/azure-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java +++ b/sdk/keyvault/azure-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java @@ -4,21 +4,18 @@ package com.azure.security.keyvault.secrets; import com.azure.core.http.HttpPipeline; -import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.SimpleResponse; import com.azure.core.http.rest.VoidResponse; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.SimpleResponse; import com.azure.core.implementation.RestProxy; import com.azure.core.implementation.annotation.ServiceClient; -import com.azure.core.implementation.util.ImplUtils; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; -import com.azure.security.keyvault.secrets.implementation.SecretBasePage; import com.azure.security.keyvault.secrets.models.DeletedSecret; import com.azure.security.keyvault.secrets.models.Secret; import com.azure.security.keyvault.secrets.models.SecretBase; -import com.azure.security.keyvault.secrets.implementation.DeletedSecretPage; -import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -38,6 +35,7 @@ * {@codesnippet com.azure.security.keyvault.secretclient.async.construct} * * @see SecretClientBuilder + * @see PagedFlux */ @ServiceClient(builder = SecretClientBuilder.class, isAsync = true, serviceInterfaces = SecretService.class) public final class SecretAsyncClient { @@ -412,14 +410,36 @@ public Mono> restoreSecret(byte[] backup) { * .map(Response::value); * * - * @return A {@link Flux} containing {@link SecretBase secret} of all the secrets in the vault. + * @return A {@link PagedFlux} containing {@link SecretBase secret} of all the secrets in the vault. + */ + public PagedFlux listSecrets() { + return new PagedFlux<>(() -> + listSecretsFirstPage(), + continuationToken -> listSecretsNextPage(continuationToken)); + } + + /* + * Gets attributes of all the secrets given by the {@code nextPageLink} that was retrieved from a call to + * {@link SecretAsyncClient#listSecrets()}. + * + * @param continuationToken The {@link PagedResponse#nextLink()} from a previous, successful call to one of the list operations. + * @return A {@link Mono} of {@link PagedResponse} from the next page of results. */ - public Flux listSecrets() { + private Mono> listSecretsNextPage(String continuationToken) { + return service.getSecrets(endpoint, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + .doOnRequest(ignoredValue -> logger.info("Retrieving the next secrets page - Page {}", continuationToken)) + .doOnSuccess(response -> logger.info("Retrieved the next secrets page - Page {}", continuationToken)) + .doOnError(error -> logger.warning("Failed to retrieve the next secrets page - Page {}", continuationToken, error)); + } + + /* + * Calls the service and retrieve first page result. It makes one call and retrieve {@code DEFAULT_MAX_PAGE_RESULTS} values. + */ + private Mono> listSecretsFirstPage() { return service.getSecrets(endpoint, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) - .doOnRequest(ignored -> logger.info("Listing secrets")) - .doOnSuccess(response -> logger.info("Listed secrets")) - .doOnError(error -> logger.warning("Failed to list secrets", error)) - .flatMapMany(r -> extractAndFetchSecrets(r, Context.NONE)); + .doOnRequest(ignored -> logger.info("Listing secrets")) + .doOnSuccess(response -> logger.info("Listed secrets")) + .doOnError(error -> logger.warning("Failed to list secrets", error)); } /** @@ -436,12 +456,34 @@ public Flux listSecrets() { * * @return A {@link Flux} containing all of the {@link DeletedSecret deleted secrets} in the vault. */ - public Flux listDeletedSecrets() { + public PagedFlux listDeletedSecrets() { + return new PagedFlux<>(() -> + listDeletedSecretsFirstPage(), + continuationToken -> listDeletedSecretsNextPage(continuationToken, Context.NONE)); + } + + /** + * Gets attributes of all the secrets given by the {@code nextPageLink} that was retrieved from a call to + * {@link SecretAsyncClient#listDeletedSecrets()}. + * + * @param continuationToken The {@link PagedResponse#nextLink()} from a previous, successful call to one of the list operations. + * @return A {@link Mono} of {@link PagedResponse} from the next page of results. + */ + private Mono> listDeletedSecretsNextPage(String continuationToken, Context context) { + return service.getDeletedSecrets(endpoint, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + .doOnRequest(ignoredValue -> logger.info("Retrieving the next deleted secrets page - Page {}", continuationToken)) + .doOnSuccess(response -> logger.info("Retrieved the next deleted secrets page - Page {}", continuationToken)) + .doOnError(error -> logger.warning("Failed to retrieve the next deleted secrets page - Page {}", continuationToken, error)); + } + + /* + * Calls the service and retrieve first page result. It makes one call and retrieve {@code DEFAULT_MAX_PAGE_RESULTS} values. + */ + private Mono> listDeletedSecretsFirstPage() { return service.getDeletedSecrets(endpoint, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) - .doOnRequest(ignored -> logger.info("Listing deleted secrets")) - .doOnSuccess(response -> logger.info("Listed deleted secrets")) - .doOnError(error -> logger.warning("Failed to list deleted secrets", error)) - .flatMapMany(r -> extractAndFetchDeletedSecrets(r, Context.NONE)); + .doOnRequest(ignored -> logger.info("Listing deleted secrets")) + .doOnSuccess(response -> logger.info("Listed deleted secrets")) + .doOnError(error -> logger.warning("Failed to list deleted secrets", error)); } /** @@ -461,51 +503,36 @@ public Flux listDeletedSecrets() { * @param name The name of the secret. * @throws ResourceNotFoundException when a secret with {@code name} doesn't exist in the key vault. * @throws HttpRequestException when a secret with {@code name} is empty string. - * @return A {@link Flux} containing {@link SecretBase secret} of all the versions of the specified secret in the vault. Flux is empty if secret with {@code name} does not exist in key vault + * @return A {@link PagedFlux} containing {@link SecretBase secret} of all the versions of the specified secret in the vault. Flux is empty if secret with {@code name} does not exist in key vault */ - public Flux listSecretVersions(String name) { - return service.getSecretVersions(endpoint, name, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) - .doOnRequest(ignored -> logger.info("Listing secret versions - {}", name)) - .doOnSuccess(response -> logger.info("Listed secret versions - {}", name)) - .doOnError(error -> logger.warning(String.format("Failed to list secret versions - {}", name), error)) - .flatMapMany(r -> extractAndFetchSecrets(r, Context.NONE)); + public PagedFlux listSecretVersions(String name) { + return new PagedFlux<>(() -> + listSecretVersionsFirstPage(name), + continuationToken -> listSecretVersionsNextPage(continuationToken)); } - /** - * Gets attributes of all the secrets given by the {@code nextPageLink} that was retrieved from a call to - * {@link SecretAsyncClient#listSecrets()}. + /* + * Gets attributes of all the secrets versions given by the {@code nextPageLink} that was retrieved from a call to + * {@link SecretAsyncClient#listSecretVersions()}. * - * @param nextPageLink The {@link SecretBasePage#nextLink()} from a previous, successful call to one of the list operations. - * @return A stream of {@link SecretBase secret} from the next page of results. + * @param continuationToken The {@link PagedResponse#nextLink()} from a previous, successful call to one of the list operations. + * + * @return A {@link Mono} of {@link PagedResponse} from the next page of results. */ - private Flux listSecretsNext(String nextPageLink, Context context) { - return service.getSecrets(endpoint, nextPageLink, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) - .doOnRequest(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) - .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) - .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)) - .flatMapMany(r -> extractAndFetchSecrets(r, context)); + private Mono> listSecretVersionsNextPage(String continuationToken) { + return service.getSecrets(endpoint, continuationToken, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + .doOnRequest(ignoredValue -> logger.info("Retrieving the next secrets versions page - Page {}", continuationToken)) + .doOnSuccess(response -> logger.info("Retrieved the next secrets versions page - Page {}", continuationToken)) + .doOnError(error -> logger.warning("Failed to retrieve the next secrets versions page - Page {}", continuationToken, error)); } - private Publisher extractAndFetchSecrets(PagedResponse page, Context context) { - return ImplUtils.extractAndFetch(page, context, this::listSecretsNext); - } - - /** - * Gets attributes of all the secrets given by the {@code nextPageLink} that was retrieved from a call to - * {@link SecretAsyncClient#listDeletedSecrets()}. - * - * @param nextPageLink The {@link DeletedSecretPage#nextLink()} from a previous, successful call to one of the list operations. - * @return A stream of {@link SecretBase secret} from the next page of results. + /* + * Calls the service and retrieve first page result. It makes one call and retrieve {@code DEFAULT_MAX_PAGE_RESULTS} values. */ - private Flux listDeletedSecretsNext(String nextPageLink, Context context) { - return service.getDeletedSecrets(endpoint, nextPageLink, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) - .doOnRequest(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) - .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) - .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)) - .flatMapMany(r -> extractAndFetchDeletedSecrets(r, context)); - } - - private Publisher extractAndFetchDeletedSecrets(PagedResponse page, Context context) { - return ImplUtils.extractAndFetch(page, context, this::listDeletedSecretsNext); + private Mono> listSecretVersionsFirstPage(String name) { + return service.getSecretVersions(endpoint, name, DEFAULT_MAX_PAGE_RESULTS, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + .doOnRequest(ignored -> logger.info("Listing secret versions - {}", name)) + .doOnSuccess(response -> logger.info("Listed secret versions - {}", name)) + .doOnError(error -> logger.warning(String.format("Failed to list secret versions - {}", name), error)); } } From 3474de90d8ccd02e924478eeede371cce8525ca7 Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Mon, 15 Jul 2019 00:12:03 -0700 Subject: [PATCH 81/85] Support context for ConfigurationAsyncClient APIs (#4415) * Support context for ConfigurationAsyncClient APIs * Fix unit test --- .../ConfigurationAsyncClient.java | 24 +++--- .../ConfigurationAsyncClientTest.java | 14 ++-- .../implementation/util/FluxUtilTests.java | 74 +++++++++++++++++++ 3 files changed, 95 insertions(+), 17 deletions(-) diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java index b3a14cfc735b2..470dff124d006 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/main/java/com/azure/data/appconfiguration/ConfigurationAsyncClient.java @@ -115,7 +115,7 @@ public Mono> addSetting(String key, String value) */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> addSetting(ConfigurationSetting setting) { - return addSetting(setting, Context.NONE); + return monoContext(context -> addSetting(setting, context)); } /** @@ -188,7 +188,8 @@ Mono> addSetting(ConfigurationSetting setting, Co */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setSetting(String key, String value) { - return setSetting(new ConfigurationSetting().key(key).value(value), Context.NONE); + return monoContext( + context -> setSetting(new ConfigurationSetting().key(key).value(value), context)); } /** @@ -232,7 +233,7 @@ public Mono> setSetting(String key, String value) */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setSetting(ConfigurationSetting setting) { - return setSetting(setting, Context.NONE); + return monoContext(context -> setSetting(setting, context)); } /** @@ -316,7 +317,8 @@ Mono> setSetting(ConfigurationSetting setting, Co */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> updateSetting(String key, String value) { - return updateSetting(new ConfigurationSetting().key(key).value(value), Context.NONE); + return monoContext( + context -> updateSetting(new ConfigurationSetting().key(key).value(value), context)); } /** @@ -348,7 +350,7 @@ public Mono> updateSetting(String key, String val */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> updateSetting(ConfigurationSetting setting) { - return updateSetting(setting, Context.NONE); + return monoContext(context -> updateSetting(setting, context)); } /** @@ -414,7 +416,7 @@ Mono> updateSetting(ConfigurationSetting setting, */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getSetting(String key) { - return getSetting(new ConfigurationSetting().key(key), Context.NONE); + return monoContext(context -> getSetting(new ConfigurationSetting().key(key), context)); } /** @@ -441,7 +443,7 @@ public Mono> getSetting(String key) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getSetting(ConfigurationSetting setting) { - return getSetting(setting, Context.NONE); + return monoContext(context -> getSetting(setting, context)); } /** @@ -500,7 +502,7 @@ Mono> getSetting(ConfigurationSetting setting, Co */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteSetting(String key) { - return deleteSetting(new ConfigurationSetting().key(key), Context.NONE); + return monoContext(context -> deleteSetting(new ConfigurationSetting().key(key), context)); } /** @@ -534,7 +536,7 @@ public Mono> deleteSetting(String key) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteSetting(ConfigurationSetting setting) { - return deleteSetting(setting, Context.NONE); + return monoContext(context -> deleteSetting(setting, context)); } /** @@ -593,8 +595,10 @@ Mono> deleteSetting(ConfigurationSetting setting, * @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux * contains all of the current settings in the service. */ + @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listSettings(SettingSelector options) { - return listSettings(options, Context.NONE); + return new PagedFlux<>(() -> monoContext(context -> listFirstPageSettings(options, context)), + continuationToken -> monoContext(context -> listNextPageSettings(context, continuationToken))); } /** diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java index 067e149c4f292..8026fb83eecc0 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/test/java/com/azure/data/appconfiguration/ConfigurationAsyncClientTest.java @@ -102,7 +102,7 @@ public void addSettingEmptyValue() { */ public void addSettingNullKey() { assertRunnableThrowsException(() -> client.addSetting(null, "A Value").block(), IllegalArgumentException.class); - assertRunnableThrowsException(() -> client.addSetting(null), NullPointerException.class); + assertRunnableThrowsException(() -> client.addSetting(null).block(), NullPointerException.class); } /** @@ -179,8 +179,8 @@ public void setSettingEmptyValue() { * Verifies that an exception is thrown when null key is passed. */ public void setSettingNullKey() { - assertRunnableThrowsException(() -> client.setSetting(null, "A Value"), IllegalArgumentException.class); - assertRunnableThrowsException(() -> client.setSetting(null), NullPointerException.class); + assertRunnableThrowsException(() -> client.setSetting(null, "A Value").block(), IllegalArgumentException.class); + assertRunnableThrowsException(() -> client.setSetting(null).block(), NullPointerException.class); } /** @@ -224,8 +224,8 @@ public void updateSettingOverload() { * Verifies that an exception is thrown when null key is passed. */ public void updateSettingNullKey() { - assertRunnableThrowsException(() -> client.updateSetting(null, "A Value"), IllegalArgumentException.class); - assertRunnableThrowsException(() -> client.updateSetting(null), NullPointerException.class); + assertRunnableThrowsException(() -> client.updateSetting(null, "A Value").block(), IllegalArgumentException.class); + assertRunnableThrowsException(() -> client.updateSetting(null).block(), NullPointerException.class); } /** @@ -365,8 +365,8 @@ public void deleteSettingWithETag() { * Test the API will not make a delete call without having a key passed, an IllegalArgumentException should be thrown. */ public void deleteSettingNullKey() { - assertRunnableThrowsException(() -> client.deleteSetting((String) null), IllegalArgumentException.class); - assertRunnableThrowsException(() -> client.deleteSetting((ConfigurationSetting) null), NullPointerException.class); + assertRunnableThrowsException(() -> client.deleteSetting((String) null).block(), IllegalArgumentException.class); + assertRunnableThrowsException(() -> client.deleteSetting((ConfigurationSetting) null).block(), NullPointerException.class); } /** diff --git a/sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java index 7cda0889394d6..76cd1feb04a5e 100644 --- a/sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java +++ b/sdk/core/azure-core/src/test/java/com/azure/core/implementation/util/FluxUtilTests.java @@ -7,16 +7,25 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.implementation.http.PagedResponseBase; import com.azure.core.util.Context; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; +import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.util.ReferenceCountUtil; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; import java.nio.channels.AsynchronousFileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.StandardOpenOption; @@ -25,6 +34,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; @@ -286,6 +297,69 @@ public void testCallWithContextGetCollection() { Assert.assertEquals(expectedLines, actualLines); } + @Test + public void testCallWithContextGetPagedCollection() throws Exception { + // Simulates the customer code that includes context + getPagedCollection() + .subscriberContext( + reactor.util.context.Context.of("Key1", "Val1", "Key2", "Val2")) + .doOnNext(System.out::println) + .subscribe(); + } + + private PagedFlux getPagedCollection() + throws Exception { + // Simulates the client library API + List> pagedResponses = getPagedResponses(4); + return new PagedFlux<>( + () -> FluxUtil.monoContext(context -> getFirstPage(pagedResponses, context)), + continuationToken -> FluxUtil + .monoContext(context -> getNextPage(continuationToken, pagedResponses, context))); + } + + private List> getPagedResponses(int noOfPages) + throws MalformedURLException { + HttpHeaders httpHeaders = new HttpHeaders().put("header1", "value1") + .put("header2", "value2"); + HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, new URL("http://localhost")); + String deserializedHeaders = "header1,value1,header2,value2"; + return IntStream.range(0, noOfPages) + .boxed() + .map(i -> createPagedResponse(httpRequest, httpHeaders, deserializedHeaders, i, noOfPages)) + .collect(Collectors.toList()); + } + + private Mono> getFirstPage(List> pagedResponses, + Context context) { + // Simulates the service side code which should get the context provided by customer code + Assert.assertEquals("Val1", context.getData("Key1").get()); + return pagedResponses.isEmpty() ? Mono.empty() : Mono.just(pagedResponses.get(0)); + } + + private Mono> getNextPage(String continuationToken, + List> pagedResponses, Context context) { + // Simulates the service side code which should get the context provided by customer code + Assert.assertEquals("Val2", context.getData("Key2").get()); + if (continuationToken == null || continuationToken.isEmpty()) { + return Mono.empty(); + } + return Mono.just(pagedResponses.get(Integer.valueOf(continuationToken))); + } + + private PagedResponseBase createPagedResponse(HttpRequest httpRequest, + HttpHeaders httpHeaders, String deserializedHeaders, int i, int noOfPages) { + return new PagedResponseBase<>(httpRequest, HttpResponseStatus.OK.code(), + httpHeaders, + getItems(i), + i < noOfPages - 1 ? String.valueOf(i + 1) : null, + deserializedHeaders); + } + + private List getItems(Integer i) { + return IntStream.range(i * 3, i * 3 + 3).boxed().collect(Collectors.toList()); + } + + private Mono getSingle(String prefix) { return FluxUtil.monoContext(context -> serviceCallSingle(prefix, context)); } From d4aa66aae1c99227f83220a6cc2df58dbf0771a5 Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Mon, 15 Jul 2019 09:01:12 -0700 Subject: [PATCH 82/85] Move eventhubs track 1 (#4382) * Base move. * Brought in the legacy parent POM. --- .../eventhubs/microsoft-azure-eventhubs-eph}/.gitignore | 0 .../eventhubs/microsoft-azure-eventhubs-eph}/Overview.md | 0 .../eventhubs/microsoft-azure-eventhubs-eph}/Readme.md | 0 .../eventhubs/microsoft-azure-eventhubs-eph}/pom.xml | 2 +- .../com/microsoft/azure/eventprocessorhost/AzureBlobLease.java | 0 .../eventprocessorhost/AzureStorageCheckpointLeaseManager.java | 0 .../AzureStoragePartitionManagerOptions.java | 0 .../java/com/microsoft/azure/eventprocessorhost/BaseLease.java | 0 .../com/microsoft/azure/eventprocessorhost/Checkpoint.java | 0 .../java/com/microsoft/azure/eventprocessorhost/Closable.java | 0 .../com/microsoft/azure/eventprocessorhost/CloseReason.java | 0 .../com/microsoft/azure/eventprocessorhost/CompleteLease.java | 0 .../azure/eventprocessorhost/DefaultEventProcessorFactory.java | 0 .../microsoft/azure/eventprocessorhost/EventProcessorHost.java | 0 .../eventprocessorhost/EventProcessorHostActionStrings.java | 0 .../azure/eventprocessorhost/EventProcessorOptions.java | 0 .../azure/eventprocessorhost/ExceptionReceivedEventArgs.java | 0 .../azure/eventprocessorhost/ExceptionWithAction.java | 0 .../com/microsoft/azure/eventprocessorhost/HostContext.java | 0 .../microsoft/azure/eventprocessorhost/ICheckpointManager.java | 0 .../microsoft/azure/eventprocessorhost/IEventProcessor.java | 0 .../azure/eventprocessorhost/IEventProcessorFactory.java | 0 .../com/microsoft/azure/eventprocessorhost/ILeaseManager.java | 0 .../azure/eventprocessorhost/InMemoryCheckpointManager.java | 0 .../azure/eventprocessorhost/InMemoryLeaseManager.java | 0 .../microsoft/azure/eventprocessorhost/LeaseLostException.java | 0 .../com/microsoft/azure/eventprocessorhost/LoggingUtils.java | 0 .../microsoft/azure/eventprocessorhost/PartitionContext.java | 0 .../microsoft/azure/eventprocessorhost/PartitionManager.java | 0 .../azure/eventprocessorhost/PartitionManagerOptions.java | 0 .../com/microsoft/azure/eventprocessorhost/PartitionPump.java | 0 .../microsoft/azure/eventprocessorhost/PartitionScanner.java | 0 .../com/microsoft/azure/eventprocessorhost/PumpManager.java | 0 .../azure/eventprocessorhost/CheckpointManagerTest.java | 0 .../java/com/microsoft/azure/eventprocessorhost/DummyPump.java | 0 .../azure/eventprocessorhost/EPHConstructorTests.java | 0 .../microsoft/azure/eventprocessorhost/LeaseManagerTest.java | 0 .../azure/eventprocessorhost/PartitionManagerTest.java | 0 .../microsoft/azure/eventprocessorhost/PerTestSettings.java | 0 .../azure/eventprocessorhost/PrefabEventProcessor.java | 0 .../azure/eventprocessorhost/PrefabGeneralErrorHandler.java | 0 .../azure/eventprocessorhost/PrefabProcessorFactory.java | 0 .../azure/eventprocessorhost/RealEventHubUtilities.java | 0 .../java/com/microsoft/azure/eventprocessorhost/Repros.java | 0 .../com/microsoft/azure/eventprocessorhost/SadPathTests.java | 0 .../java/com/microsoft/azure/eventprocessorhost/SmokeTest.java | 0 .../java/com/microsoft/azure/eventprocessorhost/TestBase.java | 0 .../com/microsoft/azure/eventprocessorhost/TestUtilities.java | 0 .../eventhubs/microsoft-azure-eventhubs-extensions}/pom.xml | 2 +- .../azure/eventhubs/extensions/appender/EventHubsAppender.java | 0 .../azure/eventhubs/extensions/appender/EventHubsManager.java | 0 .../eventhubs/microsoft-azure-eventhubs}/pom.xml | 2 +- .../azure/eventhubs/AuthorizationFailedException.java | 0 .../main/java/com/microsoft/azure/eventhubs/BatchOptions.java | 0 .../com/microsoft/azure/eventhubs/CommunicationException.java | 0 .../com/microsoft/azure/eventhubs/ConnectionStringBuilder.java | 0 .../main/java/com/microsoft/azure/eventhubs/ErrorContext.java | 0 .../src/main/java/com/microsoft/azure/eventhubs/EventData.java | 0 .../java/com/microsoft/azure/eventhubs/EventDataBatch.java | 0 .../java/com/microsoft/azure/eventhubs/EventHubClient.java | 0 .../java/com/microsoft/azure/eventhubs/EventHubException.java | 0 .../microsoft/azure/eventhubs/EventHubRuntimeInformation.java | 0 .../main/java/com/microsoft/azure/eventhubs/EventPosition.java | 0 .../eventhubs/IllegalConnectionStringFormatException.java | 0 .../com/microsoft/azure/eventhubs/IllegalEntityException.java | 0 .../microsoft/azure/eventhubs/OperationCancelledException.java | 0 .../com/microsoft/azure/eventhubs/PartitionReceiveHandler.java | 0 .../java/com/microsoft/azure/eventhubs/PartitionReceiver.java | 0 .../microsoft/azure/eventhubs/PartitionRuntimeInformation.java | 0 .../java/com/microsoft/azure/eventhubs/PartitionSender.java | 0 .../azure/eventhubs/PayloadSizeExceededException.java | 0 .../com/microsoft/azure/eventhubs/QuotaExceededException.java | 0 .../azure/eventhubs/ReceiverDisconnectedException.java | 0 .../java/com/microsoft/azure/eventhubs/ReceiverOptions.java | 0 .../microsoft/azure/eventhubs/ReceiverRuntimeInformation.java | 0 .../main/java/com/microsoft/azure/eventhubs/RetryPolicy.java | 0 .../com/microsoft/azure/eventhubs/ServerBusyException.java | 0 .../java/com/microsoft/azure/eventhubs/TimeoutException.java | 0 .../main/java/com/microsoft/azure/eventhubs/TransportType.java | 0 .../azure/eventhubs/impl/ActiveClientTokenManager.java | 0 .../com/microsoft/azure/eventhubs/impl/AmqpConnection.java | 0 .../java/com/microsoft/azure/eventhubs/impl/AmqpConstants.java | 0 .../java/com/microsoft/azure/eventhubs/impl/AmqpErrorCode.java | 0 .../java/com/microsoft/azure/eventhubs/impl/AmqpException.java | 0 .../main/java/com/microsoft/azure/eventhubs/impl/AmqpLink.java | 0 .../java/com/microsoft/azure/eventhubs/impl/AmqpReceiver.java | 0 .../com/microsoft/azure/eventhubs/impl/AmqpResponseCode.java | 0 .../java/com/microsoft/azure/eventhubs/impl/AmqpSender.java | 0 .../main/java/com/microsoft/azure/eventhubs/impl/AmqpUtil.java | 0 .../com/microsoft/azure/eventhubs/impl/BaseLinkHandler.java | 0 .../java/com/microsoft/azure/eventhubs/impl/CBSChannel.java | 0 .../com/microsoft/azure/eventhubs/impl/ClientConstants.java | 0 .../java/com/microsoft/azure/eventhubs/impl/ClientEntity.java | 0 .../com/microsoft/azure/eventhubs/impl/ConnectionHandler.java | 0 .../com/microsoft/azure/eventhubs/impl/CustomIOHandler.java | 0 .../com/microsoft/azure/eventhubs/impl/DispatchHandler.java | 0 .../microsoft/azure/eventhubs/impl/ErrorContextProvider.java | 0 .../com/microsoft/azure/eventhubs/impl/EventDataBatchImpl.java | 0 .../java/com/microsoft/azure/eventhubs/impl/EventDataImpl.java | 0 .../java/com/microsoft/azure/eventhubs/impl/EventDataUtil.java | 0 .../com/microsoft/azure/eventhubs/impl/EventHubClientImpl.java | 0 .../com/microsoft/azure/eventhubs/impl/EventPositionImpl.java | 0 .../java/com/microsoft/azure/eventhubs/impl/ExceptionUtil.java | 0 .../microsoft/azure/eventhubs/impl/FaultTolerantObject.java | 0 .../main/java/com/microsoft/azure/eventhubs/impl/IOObject.java | 0 .../java/com/microsoft/azure/eventhubs/impl/IteratorUtil.java | 0 .../com/microsoft/azure/eventhubs/impl/ManagementChannel.java | 0 .../microsoft/azure/eventhubs/impl/MessageOperationResult.java | 0 .../com/microsoft/azure/eventhubs/impl/MessageReceiver.java | 0 .../java/com/microsoft/azure/eventhubs/impl/MessageSender.java | 0 .../com/microsoft/azure/eventhubs/impl/MessageWrapper.java | 0 .../com/microsoft/azure/eventhubs/impl/MessagingFactory.java | 0 .../java/com/microsoft/azure/eventhubs/impl/Operation.java | 0 .../com/microsoft/azure/eventhubs/impl/OperationResult.java | 0 .../microsoft/azure/eventhubs/impl/OperationResultBase.java | 0 .../microsoft/azure/eventhubs/impl/PartitionReceiverImpl.java | 0 .../microsoft/azure/eventhubs/impl/PartitionSenderImpl.java | 0 .../java/com/microsoft/azure/eventhubs/impl/PassByRef.java | 0 .../java/com/microsoft/azure/eventhubs/impl/ProtonUtil.java | 0 .../com/microsoft/azure/eventhubs/impl/ReactorDispatcher.java | 0 .../com/microsoft/azure/eventhubs/impl/ReactorHandler.java | 0 .../com/microsoft/azure/eventhubs/impl/ReceiveLinkHandler.java | 0 .../java/com/microsoft/azure/eventhubs/impl/ReceivePump.java | 0 .../com/microsoft/azure/eventhubs/impl/ReceiverContext.java | 0 .../azure/eventhubs/impl/ReceiverSettingsProvider.java | 0 .../com/microsoft/azure/eventhubs/impl/ReplayableWorkItem.java | 0 .../microsoft/azure/eventhubs/impl/RequestResponseChannel.java | 0 .../microsoft/azure/eventhubs/impl/RequestResponseCloser.java | 0 .../microsoft/azure/eventhubs/impl/RequestResponseOpener.java | 0 .../com/microsoft/azure/eventhubs/impl/RetryExponential.java | 0 .../com/microsoft/azure/eventhubs/impl/SchedulerProvider.java | 0 .../com/microsoft/azure/eventhubs/impl/SendLinkHandler.java | 0 .../java/com/microsoft/azure/eventhubs/impl/SenderContext.java | 0 .../com/microsoft/azure/eventhubs/impl/SessionHandler.java | 0 .../com/microsoft/azure/eventhubs/impl/SessionProvider.java | 0 .../eventhubs/impl/SharedAccessSignatureTokenProvider.java | 0 .../java/com/microsoft/azure/eventhubs/impl/StringUtil.java | 0 .../com/microsoft/azure/eventhubs/impl/TimeoutTracker.java | 0 .../main/java/com/microsoft/azure/eventhubs/impl/Timer.java | 0 .../java/com/microsoft/azure/eventhubs/impl/TrackingUtil.java | 0 .../azure/eventhubs/impl/WebSocketConnectionHandler.java | 0 .../azure/eventhubs/impl/WebSocketProxyConnectionHandler.java | 0 .../main/java/com/microsoft/azure/eventhubs/impl/WorkItem.java | 0 .../azure/eventhubs/concurrency/ConcurrentReceiversTest.java | 0 .../azure/eventhubs/concurrency/EventHubClientTest.java | 0 .../azure/eventhubs/connstrbuilder/ConnStrBuilderTest.java | 0 .../azure/eventhubs/connstrbuilder/TransportTypeTest.java | 0 .../microsoft/azure/eventhubs/eventdata/BackCompatTest.java | 0 .../azure/eventhubs/eventdata/EventDataBatchTest.java | 0 .../com/microsoft/azure/eventhubs/eventdata/EventDataTest.java | 0 .../azure/eventhubs/eventdata/InteropAmqpPropertiesTest.java | 0 .../azure/eventhubs/eventdata/InteropEventBodyTest.java | 0 .../eventhubs/exceptioncontracts/ClientEntityCreateTest.java | 0 .../eventhubs/exceptioncontracts/MsgFactoryOpenCloseTest.java | 0 .../azure/eventhubs/exceptioncontracts/ReactorFaultTest.java | 0 .../azure/eventhubs/exceptioncontracts/ReceiverEpochTest.java | 0 .../azure/eventhubs/exceptioncontracts/RetryPolicyTest.java | 0 .../eventhubs/exceptioncontracts/SecurityExceptionsTest.java | 0 .../eventhubs/exceptioncontracts/SendLargeMessageTest.java | 0 .../exceptioncontracts/WebSocketsSendLargeMessageTest.java | 0 .../com/microsoft/azure/eventhubs/impl/EventDataOrderTest.java | 0 .../azure/eventhubs/jproxy/ProxyNegotiationHandler.java | 0 .../java/com/microsoft/azure/eventhubs/jproxy/ProxyServer.java | 0 .../java/com/microsoft/azure/eventhubs/jproxy/SimpleProxy.java | 0 .../java/com/microsoft/azure/eventhubs/lib/ApiTestBase.java | 0 .../azure/eventhubs/lib/FaultInjectingReactorFactory.java | 0 .../com/microsoft/azure/eventhubs/lib/SasTokenTestBase.java | 0 .../test/java/com/microsoft/azure/eventhubs/lib/TestBase.java | 0 .../java/com/microsoft/azure/eventhubs/lib/TestContext.java | 0 .../com/microsoft/azure/eventhubs/lib/mock/MockServer.java | 0 .../azure/eventhubs/lib/mock/Sender1MsgOnLinkFlowHandler.java | 0 .../microsoft/azure/eventhubs/lib/mock/ServerTraceHandler.java | 0 .../com/microsoft/azure/eventhubs/proxy/ProxyReceiveTest.java | 0 .../com/microsoft/azure/eventhubs/proxy/ProxySelectorTest.java | 0 .../azure/eventhubs/proxy/ProxySendLargeMessageTest.java | 0 .../com/microsoft/azure/eventhubs/proxy/ProxySendTest.java | 0 .../azure/eventhubs/sendrecv/EventDataBatchAPITest.java | 0 .../azure/eventhubs/sendrecv/ReceiveParallelManualTest.java | 0 .../azure/eventhubs/sendrecv/ReceivePumpEventHubTest.java | 0 .../microsoft/azure/eventhubs/sendrecv/ReceivePumpTest.java | 0 .../com/microsoft/azure/eventhubs/sendrecv/ReceiveTest.java | 0 .../azure/eventhubs/sendrecv/ReceiverIdentifierTest.java | 0 .../azure/eventhubs/sendrecv/ReceiverRuntimeMetricsTest.java | 0 .../azure/eventhubs/sendrecv/RequestResponseTest.java | 0 .../azure/eventhubs/sendrecv/SasTokenReceiveTest.java | 0 .../microsoft/azure/eventhubs/sendrecv/SasTokenSendTest.java | 0 .../java/com/microsoft/azure/eventhubs/sendrecv/SendTest.java | 0 .../azure/eventhubs/sendrecv/SetPrefetchCountTest.java | 0 .../azure/eventhubs/sendrecv/WebSocketsReceiveTest.java | 0 .../microsoft/azure/eventhubs/sendrecv/WebSocketsSendTest.java | 0 eventhubs/data-plane/pom.xml => sdk/eventhubs/pom.data.xml | 0 sdk/eventhubs/pom.service.xml | 3 +++ 192 files changed, 6 insertions(+), 3 deletions(-) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/.gitignore (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/Overview.md (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/Readme.md (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/pom.xml (97%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/AzureBlobLease.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/AzureStorageCheckpointLeaseManager.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/AzureStoragePartitionManagerOptions.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/BaseLease.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/Checkpoint.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/Closable.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/CloseReason.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/CompleteLease.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/DefaultEventProcessorFactory.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHost.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHostActionStrings.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorOptions.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/ExceptionReceivedEventArgs.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/ExceptionWithAction.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/HostContext.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/ICheckpointManager.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/IEventProcessor.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/IEventProcessorFactory.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/ILeaseManager.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/InMemoryCheckpointManager.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/InMemoryLeaseManager.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/LeaseLostException.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/LoggingUtils.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionContext.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionManager.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionManagerOptions.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionPump.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionScanner.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/main/java/com/microsoft/azure/eventprocessorhost/PumpManager.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/CheckpointManagerTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/DummyPump.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/EPHConstructorTests.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/LeaseManagerTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/PartitionManagerTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/PerTestSettings.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabEventProcessor.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabGeneralErrorHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabProcessorFactory.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/RealEventHubUtilities.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/Repros.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/SadPathTests.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/SmokeTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/TestBase.java (100%) rename {eventhubs/data-plane/azure-eventhubs-eph => sdk/eventhubs/microsoft-azure-eventhubs-eph}/src/test/java/com/microsoft/azure/eventprocessorhost/TestUtilities.java (100%) rename {eventhubs/data-plane/azure-eventhubs-extensions => sdk/eventhubs/microsoft-azure-eventhubs-extensions}/pom.xml (97%) rename {eventhubs/data-plane/azure-eventhubs-extensions => sdk/eventhubs/microsoft-azure-eventhubs-extensions}/src/main/java/com/microsoft/azure/eventhubs/extensions/appender/EventHubsAppender.java (100%) rename {eventhubs/data-plane/azure-eventhubs-extensions => sdk/eventhubs/microsoft-azure-eventhubs-extensions}/src/main/java/com/microsoft/azure/eventhubs/extensions/appender/EventHubsManager.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/pom.xml (95%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/AuthorizationFailedException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/BatchOptions.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/CommunicationException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/ConnectionStringBuilder.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/ErrorContext.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/EventData.java (100%) mode change 100755 => 100644 rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/EventDataBatch.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/EventHubClient.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/EventHubException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/EventHubRuntimeInformation.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/EventPosition.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/IllegalConnectionStringFormatException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/IllegalEntityException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/OperationCancelledException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/PartitionReceiveHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/PartitionReceiver.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/PartitionRuntimeInformation.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/PartitionSender.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/PayloadSizeExceededException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/QuotaExceededException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/ReceiverDisconnectedException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/ReceiverOptions.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/ReceiverRuntimeInformation.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/RetryPolicy.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/ServerBusyException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/TimeoutException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/TransportType.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ActiveClientTokenManager.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpConnection.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpConstants.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpErrorCode.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpException.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpLink.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpReceiver.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpResponseCode.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpSender.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpUtil.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/BaseLinkHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/CBSChannel.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ClientConstants.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ClientEntity.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ConnectionHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/CustomIOHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/DispatchHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ErrorContextProvider.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataBatchImpl.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataImpl.java (100%) mode change 100755 => 100644 rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataUtil.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/EventHubClientImpl.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/EventPositionImpl.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ExceptionUtil.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/FaultTolerantObject.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/IOObject.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/IteratorUtil.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ManagementChannel.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/MessageOperationResult.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/MessageReceiver.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/MessageSender.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/MessageWrapper.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/MessagingFactory.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/Operation.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/OperationResult.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/OperationResultBase.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/PartitionReceiverImpl.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/PartitionSenderImpl.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/PassByRef.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ProtonUtil.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ReactorDispatcher.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ReactorHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiveLinkHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ReceivePump.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiverContext.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiverSettingsProvider.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/ReplayableWorkItem.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseChannel.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseCloser.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseOpener.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/RetryExponential.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/SchedulerProvider.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/SendLinkHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/SenderContext.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/SessionHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/SessionProvider.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/SharedAccessSignatureTokenProvider.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/StringUtil.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/TimeoutTracker.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/Timer.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/TrackingUtil.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/WebSocketConnectionHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/WebSocketProxyConnectionHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/main/java/com/microsoft/azure/eventhubs/impl/WorkItem.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/concurrency/ConcurrentReceiversTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/concurrency/EventHubClientTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/connstrbuilder/ConnStrBuilderTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/connstrbuilder/TransportTypeTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/eventdata/BackCompatTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/eventdata/EventDataBatchTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/eventdata/EventDataTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/eventdata/InteropAmqpPropertiesTest.java (100%) mode change 100755 => 100644 rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/eventdata/InteropEventBodyTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ClientEntityCreateTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/MsgFactoryOpenCloseTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ReactorFaultTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ReceiverEpochTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/RetryPolicyTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/SecurityExceptionsTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/SendLargeMessageTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/WebSocketsSendLargeMessageTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/impl/EventDataOrderTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/jproxy/ProxyNegotiationHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/jproxy/ProxyServer.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/jproxy/SimpleProxy.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/lib/ApiTestBase.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/lib/FaultInjectingReactorFactory.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/lib/SasTokenTestBase.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/lib/TestBase.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/lib/TestContext.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/lib/mock/MockServer.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/lib/mock/Sender1MsgOnLinkFlowHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/lib/mock/ServerTraceHandler.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxyReceiveTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySelectorTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySendLargeMessageTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySendTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/EventDataBatchAPITest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiveParallelManualTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceivePumpEventHubTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceivePumpTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiveTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiverIdentifierTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiverRuntimeMetricsTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/RequestResponseTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SasTokenReceiveTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SasTokenSendTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SendTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SetPrefetchCountTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/WebSocketsReceiveTest.java (100%) rename {eventhubs/data-plane/azure-eventhubs => sdk/eventhubs/microsoft-azure-eventhubs}/src/test/java/com/microsoft/azure/eventhubs/sendrecv/WebSocketsSendTest.java (100%) rename eventhubs/data-plane/pom.xml => sdk/eventhubs/pom.data.xml (100%) diff --git a/eventhubs/data-plane/azure-eventhubs-eph/.gitignore b/sdk/eventhubs/microsoft-azure-eventhubs-eph/.gitignore similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/.gitignore rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/.gitignore diff --git a/eventhubs/data-plane/azure-eventhubs-eph/Overview.md b/sdk/eventhubs/microsoft-azure-eventhubs-eph/Overview.md similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/Overview.md rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/Overview.md diff --git a/eventhubs/data-plane/azure-eventhubs-eph/Readme.md b/sdk/eventhubs/microsoft-azure-eventhubs-eph/Readme.md similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/Readme.md rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/Readme.md diff --git a/eventhubs/data-plane/azure-eventhubs-eph/pom.xml b/sdk/eventhubs/microsoft-azure-eventhubs-eph/pom.xml similarity index 97% rename from eventhubs/data-plane/azure-eventhubs-eph/pom.xml rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/pom.xml index 0a3bd414a75e3..fad46c57eae75 100644 --- a/eventhubs/data-plane/azure-eventhubs-eph/pom.xml +++ b/sdk/eventhubs/microsoft-azure-eventhubs-eph/pom.xml @@ -8,7 +8,7 @@ com.microsoft.azure azure-eventhubs-clients 2.3.1 - ../pom.xml + ../pom.data.xml 4.0.0 diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureBlobLease.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureBlobLease.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureBlobLease.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureBlobLease.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureStorageCheckpointLeaseManager.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureStorageCheckpointLeaseManager.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureStorageCheckpointLeaseManager.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureStorageCheckpointLeaseManager.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureStoragePartitionManagerOptions.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureStoragePartitionManagerOptions.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureStoragePartitionManagerOptions.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/AzureStoragePartitionManagerOptions.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/BaseLease.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/BaseLease.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/BaseLease.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/BaseLease.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/Checkpoint.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/Checkpoint.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/Checkpoint.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/Checkpoint.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/Closable.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/Closable.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/Closable.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/Closable.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/CloseReason.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/CloseReason.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/CloseReason.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/CloseReason.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/CompleteLease.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/CompleteLease.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/CompleteLease.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/CompleteLease.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/DefaultEventProcessorFactory.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/DefaultEventProcessorFactory.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/DefaultEventProcessorFactory.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/DefaultEventProcessorFactory.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHost.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHost.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHost.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHost.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHostActionStrings.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHostActionStrings.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHostActionStrings.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHostActionStrings.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorOptions.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorOptions.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorOptions.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorOptions.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ExceptionReceivedEventArgs.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ExceptionReceivedEventArgs.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ExceptionReceivedEventArgs.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ExceptionReceivedEventArgs.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ExceptionWithAction.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ExceptionWithAction.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ExceptionWithAction.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ExceptionWithAction.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/HostContext.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/HostContext.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/HostContext.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/HostContext.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ICheckpointManager.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ICheckpointManager.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ICheckpointManager.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ICheckpointManager.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/IEventProcessor.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/IEventProcessor.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/IEventProcessor.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/IEventProcessor.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/IEventProcessorFactory.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/IEventProcessorFactory.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/IEventProcessorFactory.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/IEventProcessorFactory.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ILeaseManager.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ILeaseManager.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ILeaseManager.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/ILeaseManager.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/InMemoryCheckpointManager.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/InMemoryCheckpointManager.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/InMemoryCheckpointManager.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/InMemoryCheckpointManager.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/InMemoryLeaseManager.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/InMemoryLeaseManager.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/InMemoryLeaseManager.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/InMemoryLeaseManager.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/LeaseLostException.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/LeaseLostException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/LeaseLostException.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/LeaseLostException.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/LoggingUtils.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/LoggingUtils.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/LoggingUtils.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/LoggingUtils.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionContext.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionContext.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionContext.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionContext.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionManager.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionManager.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionManager.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionManager.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionManagerOptions.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionManagerOptions.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionManagerOptions.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionManagerOptions.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionPump.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionPump.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionPump.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionPump.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionScanner.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionScanner.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionScanner.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PartitionScanner.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PumpManager.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PumpManager.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PumpManager.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/PumpManager.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/CheckpointManagerTest.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/CheckpointManagerTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/CheckpointManagerTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/CheckpointManagerTest.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/DummyPump.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/DummyPump.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/DummyPump.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/DummyPump.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/EPHConstructorTests.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/EPHConstructorTests.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/EPHConstructorTests.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/EPHConstructorTests.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/LeaseManagerTest.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/LeaseManagerTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/LeaseManagerTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/LeaseManagerTest.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PartitionManagerTest.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PartitionManagerTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PartitionManagerTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PartitionManagerTest.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PerTestSettings.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PerTestSettings.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PerTestSettings.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PerTestSettings.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabEventProcessor.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabEventProcessor.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabEventProcessor.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabEventProcessor.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabGeneralErrorHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabGeneralErrorHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabGeneralErrorHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabGeneralErrorHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabProcessorFactory.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabProcessorFactory.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabProcessorFactory.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PrefabProcessorFactory.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/RealEventHubUtilities.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/RealEventHubUtilities.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/RealEventHubUtilities.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/RealEventHubUtilities.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/Repros.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/Repros.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/Repros.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/Repros.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/SadPathTests.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/SadPathTests.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/SadPathTests.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/SadPathTests.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/SmokeTest.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/SmokeTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/SmokeTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/SmokeTest.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/TestBase.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/TestBase.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/TestBase.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/TestBase.java diff --git a/eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/TestUtilities.java b/sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/TestUtilities.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/TestUtilities.java rename to sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/TestUtilities.java diff --git a/eventhubs/data-plane/azure-eventhubs-extensions/pom.xml b/sdk/eventhubs/microsoft-azure-eventhubs-extensions/pom.xml similarity index 97% rename from eventhubs/data-plane/azure-eventhubs-extensions/pom.xml rename to sdk/eventhubs/microsoft-azure-eventhubs-extensions/pom.xml index a2a85d70883b5..5faee62b351f4 100644 --- a/eventhubs/data-plane/azure-eventhubs-extensions/pom.xml +++ b/sdk/eventhubs/microsoft-azure-eventhubs-extensions/pom.xml @@ -8,7 +8,7 @@ com.microsoft.azure azure-eventhubs-clients 2.3.1 - ../pom.xml + ../pom.data.xml 4.0.0 diff --git a/eventhubs/data-plane/azure-eventhubs-extensions/src/main/java/com/microsoft/azure/eventhubs/extensions/appender/EventHubsAppender.java b/sdk/eventhubs/microsoft-azure-eventhubs-extensions/src/main/java/com/microsoft/azure/eventhubs/extensions/appender/EventHubsAppender.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-extensions/src/main/java/com/microsoft/azure/eventhubs/extensions/appender/EventHubsAppender.java rename to sdk/eventhubs/microsoft-azure-eventhubs-extensions/src/main/java/com/microsoft/azure/eventhubs/extensions/appender/EventHubsAppender.java diff --git a/eventhubs/data-plane/azure-eventhubs-extensions/src/main/java/com/microsoft/azure/eventhubs/extensions/appender/EventHubsManager.java b/sdk/eventhubs/microsoft-azure-eventhubs-extensions/src/main/java/com/microsoft/azure/eventhubs/extensions/appender/EventHubsManager.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs-extensions/src/main/java/com/microsoft/azure/eventhubs/extensions/appender/EventHubsManager.java rename to sdk/eventhubs/microsoft-azure-eventhubs-extensions/src/main/java/com/microsoft/azure/eventhubs/extensions/appender/EventHubsManager.java diff --git a/eventhubs/data-plane/azure-eventhubs/pom.xml b/sdk/eventhubs/microsoft-azure-eventhubs/pom.xml similarity index 95% rename from eventhubs/data-plane/azure-eventhubs/pom.xml rename to sdk/eventhubs/microsoft-azure-eventhubs/pom.xml index 6f567e713080e..dc90cc557ca52 100644 --- a/eventhubs/data-plane/azure-eventhubs/pom.xml +++ b/sdk/eventhubs/microsoft-azure-eventhubs/pom.xml @@ -8,7 +8,7 @@ com.microsoft.azure azure-eventhubs-clients 2.3.1 - ../pom.xml + ../pom.data.xml 4.0.0 diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/AuthorizationFailedException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/AuthorizationFailedException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/AuthorizationFailedException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/AuthorizationFailedException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/BatchOptions.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/BatchOptions.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/BatchOptions.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/BatchOptions.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/CommunicationException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/CommunicationException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/CommunicationException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/CommunicationException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ConnectionStringBuilder.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ConnectionStringBuilder.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ConnectionStringBuilder.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ConnectionStringBuilder.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ErrorContext.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ErrorContext.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ErrorContext.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ErrorContext.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventData.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventData.java old mode 100755 new mode 100644 similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventData.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventData.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventDataBatch.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventDataBatch.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventDataBatch.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventDataBatch.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubClient.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubClient.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubClient.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubClient.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubRuntimeInformation.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubRuntimeInformation.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubRuntimeInformation.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventHubRuntimeInformation.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventPosition.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventPosition.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventPosition.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/EventPosition.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/IllegalConnectionStringFormatException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/IllegalConnectionStringFormatException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/IllegalConnectionStringFormatException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/IllegalConnectionStringFormatException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/IllegalEntityException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/IllegalEntityException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/IllegalEntityException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/IllegalEntityException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/OperationCancelledException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/OperationCancelledException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/OperationCancelledException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/OperationCancelledException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionReceiveHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionReceiveHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionReceiveHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionReceiveHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionReceiver.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionReceiver.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionReceiver.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionReceiver.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionRuntimeInformation.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionRuntimeInformation.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionRuntimeInformation.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionRuntimeInformation.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionSender.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionSender.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionSender.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PartitionSender.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PayloadSizeExceededException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PayloadSizeExceededException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PayloadSizeExceededException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/PayloadSizeExceededException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/QuotaExceededException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/QuotaExceededException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/QuotaExceededException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/QuotaExceededException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverDisconnectedException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverDisconnectedException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverDisconnectedException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverDisconnectedException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverOptions.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverOptions.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverOptions.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverOptions.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverRuntimeInformation.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverRuntimeInformation.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverRuntimeInformation.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ReceiverRuntimeInformation.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/RetryPolicy.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/RetryPolicy.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/RetryPolicy.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/RetryPolicy.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ServerBusyException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ServerBusyException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ServerBusyException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/ServerBusyException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/TimeoutException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/TimeoutException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/TimeoutException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/TimeoutException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/TransportType.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/TransportType.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/TransportType.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/TransportType.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ActiveClientTokenManager.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ActiveClientTokenManager.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ActiveClientTokenManager.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ActiveClientTokenManager.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpConnection.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpConnection.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpConnection.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpConnection.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpConstants.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpConstants.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpConstants.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpConstants.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpErrorCode.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpErrorCode.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpErrorCode.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpErrorCode.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpException.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpException.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpException.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpException.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpLink.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpLink.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpLink.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpLink.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpReceiver.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpReceiver.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpReceiver.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpReceiver.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpResponseCode.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpResponseCode.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpResponseCode.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpResponseCode.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpSender.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpSender.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpSender.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpSender.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpUtil.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpUtil.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpUtil.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/AmqpUtil.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/BaseLinkHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/BaseLinkHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/BaseLinkHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/BaseLinkHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/CBSChannel.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/CBSChannel.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/CBSChannel.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/CBSChannel.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ClientConstants.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ClientConstants.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ClientConstants.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ClientConstants.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ClientEntity.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ClientEntity.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ClientEntity.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ClientEntity.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ConnectionHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ConnectionHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ConnectionHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ConnectionHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/CustomIOHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/CustomIOHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/CustomIOHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/CustomIOHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/DispatchHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/DispatchHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/DispatchHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/DispatchHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ErrorContextProvider.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ErrorContextProvider.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ErrorContextProvider.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ErrorContextProvider.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataBatchImpl.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataBatchImpl.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataBatchImpl.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataBatchImpl.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataImpl.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataImpl.java old mode 100755 new mode 100644 similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataImpl.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataImpl.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataUtil.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataUtil.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataUtil.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventDataUtil.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventHubClientImpl.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventHubClientImpl.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventHubClientImpl.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventHubClientImpl.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventPositionImpl.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventPositionImpl.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventPositionImpl.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/EventPositionImpl.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ExceptionUtil.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ExceptionUtil.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ExceptionUtil.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ExceptionUtil.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/FaultTolerantObject.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/FaultTolerantObject.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/FaultTolerantObject.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/FaultTolerantObject.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/IOObject.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/IOObject.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/IOObject.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/IOObject.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/IteratorUtil.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/IteratorUtil.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/IteratorUtil.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/IteratorUtil.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ManagementChannel.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ManagementChannel.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ManagementChannel.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ManagementChannel.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageOperationResult.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageOperationResult.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageOperationResult.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageOperationResult.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageReceiver.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageReceiver.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageReceiver.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageReceiver.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageSender.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageSender.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageSender.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageSender.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageWrapper.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageWrapper.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageWrapper.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessageWrapper.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessagingFactory.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessagingFactory.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessagingFactory.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/MessagingFactory.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/Operation.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/Operation.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/Operation.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/Operation.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/OperationResult.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/OperationResult.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/OperationResult.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/OperationResult.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/OperationResultBase.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/OperationResultBase.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/OperationResultBase.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/OperationResultBase.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PartitionReceiverImpl.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PartitionReceiverImpl.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PartitionReceiverImpl.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PartitionReceiverImpl.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PartitionSenderImpl.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PartitionSenderImpl.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PartitionSenderImpl.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PartitionSenderImpl.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PassByRef.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PassByRef.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PassByRef.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/PassByRef.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ProtonUtil.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ProtonUtil.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ProtonUtil.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ProtonUtil.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReactorDispatcher.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReactorDispatcher.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReactorDispatcher.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReactorDispatcher.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReactorHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReactorHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReactorHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReactorHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiveLinkHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiveLinkHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiveLinkHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiveLinkHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceivePump.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceivePump.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceivePump.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceivePump.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiverContext.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiverContext.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiverContext.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiverContext.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiverSettingsProvider.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiverSettingsProvider.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiverSettingsProvider.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReceiverSettingsProvider.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReplayableWorkItem.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReplayableWorkItem.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReplayableWorkItem.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/ReplayableWorkItem.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseChannel.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseChannel.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseChannel.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseChannel.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseCloser.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseCloser.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseCloser.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseCloser.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseOpener.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseOpener.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseOpener.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RequestResponseOpener.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RetryExponential.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RetryExponential.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RetryExponential.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/RetryExponential.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SchedulerProvider.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SchedulerProvider.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SchedulerProvider.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SchedulerProvider.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SendLinkHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SendLinkHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SendLinkHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SendLinkHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SenderContext.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SenderContext.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SenderContext.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SenderContext.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SessionHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SessionHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SessionHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SessionHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SessionProvider.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SessionProvider.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SessionProvider.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SessionProvider.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SharedAccessSignatureTokenProvider.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SharedAccessSignatureTokenProvider.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SharedAccessSignatureTokenProvider.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/SharedAccessSignatureTokenProvider.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/StringUtil.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/StringUtil.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/StringUtil.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/StringUtil.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/TimeoutTracker.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/TimeoutTracker.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/TimeoutTracker.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/TimeoutTracker.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/Timer.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/Timer.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/Timer.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/Timer.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/TrackingUtil.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/TrackingUtil.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/TrackingUtil.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/TrackingUtil.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WebSocketConnectionHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WebSocketConnectionHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WebSocketConnectionHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WebSocketConnectionHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WebSocketProxyConnectionHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WebSocketProxyConnectionHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WebSocketProxyConnectionHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WebSocketProxyConnectionHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WorkItem.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WorkItem.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WorkItem.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/main/java/com/microsoft/azure/eventhubs/impl/WorkItem.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/concurrency/ConcurrentReceiversTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/concurrency/ConcurrentReceiversTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/concurrency/ConcurrentReceiversTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/concurrency/ConcurrentReceiversTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/concurrency/EventHubClientTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/concurrency/EventHubClientTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/concurrency/EventHubClientTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/concurrency/EventHubClientTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/connstrbuilder/ConnStrBuilderTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/connstrbuilder/ConnStrBuilderTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/connstrbuilder/ConnStrBuilderTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/connstrbuilder/ConnStrBuilderTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/connstrbuilder/TransportTypeTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/connstrbuilder/TransportTypeTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/connstrbuilder/TransportTypeTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/connstrbuilder/TransportTypeTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/BackCompatTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/BackCompatTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/BackCompatTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/BackCompatTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/EventDataBatchTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/EventDataBatchTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/EventDataBatchTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/EventDataBatchTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/EventDataTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/EventDataTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/EventDataTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/EventDataTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/InteropAmqpPropertiesTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/InteropAmqpPropertiesTest.java old mode 100755 new mode 100644 similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/InteropAmqpPropertiesTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/InteropAmqpPropertiesTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/InteropEventBodyTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/InteropEventBodyTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/InteropEventBodyTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/eventdata/InteropEventBodyTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ClientEntityCreateTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ClientEntityCreateTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ClientEntityCreateTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ClientEntityCreateTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/MsgFactoryOpenCloseTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/MsgFactoryOpenCloseTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/MsgFactoryOpenCloseTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/MsgFactoryOpenCloseTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ReactorFaultTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ReactorFaultTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ReactorFaultTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ReactorFaultTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ReceiverEpochTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ReceiverEpochTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ReceiverEpochTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/ReceiverEpochTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/RetryPolicyTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/RetryPolicyTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/RetryPolicyTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/RetryPolicyTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/SecurityExceptionsTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/SecurityExceptionsTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/SecurityExceptionsTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/SecurityExceptionsTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/SendLargeMessageTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/SendLargeMessageTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/SendLargeMessageTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/SendLargeMessageTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/WebSocketsSendLargeMessageTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/WebSocketsSendLargeMessageTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/WebSocketsSendLargeMessageTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/exceptioncontracts/WebSocketsSendLargeMessageTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/impl/EventDataOrderTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/impl/EventDataOrderTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/impl/EventDataOrderTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/impl/EventDataOrderTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/ProxyNegotiationHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/ProxyNegotiationHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/ProxyNegotiationHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/ProxyNegotiationHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/ProxyServer.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/ProxyServer.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/ProxyServer.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/ProxyServer.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/SimpleProxy.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/SimpleProxy.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/SimpleProxy.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/jproxy/SimpleProxy.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/ApiTestBase.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/ApiTestBase.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/ApiTestBase.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/ApiTestBase.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/FaultInjectingReactorFactory.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/FaultInjectingReactorFactory.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/FaultInjectingReactorFactory.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/FaultInjectingReactorFactory.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/SasTokenTestBase.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/SasTokenTestBase.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/SasTokenTestBase.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/SasTokenTestBase.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/TestBase.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/TestBase.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/TestBase.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/TestBase.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/TestContext.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/TestContext.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/TestContext.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/TestContext.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/MockServer.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/MockServer.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/MockServer.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/MockServer.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/Sender1MsgOnLinkFlowHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/Sender1MsgOnLinkFlowHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/Sender1MsgOnLinkFlowHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/Sender1MsgOnLinkFlowHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/ServerTraceHandler.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/ServerTraceHandler.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/ServerTraceHandler.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/lib/mock/ServerTraceHandler.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxyReceiveTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxyReceiveTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxyReceiveTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxyReceiveTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySelectorTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySelectorTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySelectorTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySelectorTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySendLargeMessageTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySendLargeMessageTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySendLargeMessageTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySendLargeMessageTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySendTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySendTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySendTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/proxy/ProxySendTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/EventDataBatchAPITest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/EventDataBatchAPITest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/EventDataBatchAPITest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/EventDataBatchAPITest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiveParallelManualTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiveParallelManualTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiveParallelManualTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiveParallelManualTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceivePumpEventHubTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceivePumpEventHubTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceivePumpEventHubTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceivePumpEventHubTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceivePumpTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceivePumpTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceivePumpTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceivePumpTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiveTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiveTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiveTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiveTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiverIdentifierTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiverIdentifierTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiverIdentifierTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiverIdentifierTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiverRuntimeMetricsTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiverRuntimeMetricsTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiverRuntimeMetricsTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/ReceiverRuntimeMetricsTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/RequestResponseTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/RequestResponseTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/RequestResponseTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/RequestResponseTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SasTokenReceiveTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SasTokenReceiveTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SasTokenReceiveTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SasTokenReceiveTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SasTokenSendTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SasTokenSendTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SasTokenSendTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SasTokenSendTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SendTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SendTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SendTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SendTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SetPrefetchCountTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SetPrefetchCountTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SetPrefetchCountTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/SetPrefetchCountTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/WebSocketsReceiveTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/WebSocketsReceiveTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/WebSocketsReceiveTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/WebSocketsReceiveTest.java diff --git a/eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/WebSocketsSendTest.java b/sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/WebSocketsSendTest.java similarity index 100% rename from eventhubs/data-plane/azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/WebSocketsSendTest.java rename to sdk/eventhubs/microsoft-azure-eventhubs/src/test/java/com/microsoft/azure/eventhubs/sendrecv/WebSocketsSendTest.java diff --git a/eventhubs/data-plane/pom.xml b/sdk/eventhubs/pom.data.xml similarity index 100% rename from eventhubs/data-plane/pom.xml rename to sdk/eventhubs/pom.data.xml diff --git a/sdk/eventhubs/pom.service.xml b/sdk/eventhubs/pom.service.xml index 87821b3eed055..23edea1a17d6e 100644 --- a/sdk/eventhubs/pom.service.xml +++ b/sdk/eventhubs/pom.service.xml @@ -9,6 +9,9 @@ pom 1.0.0 + microsoft-azure-eventhubs + microsoft-azure-eventhubs-eph + microsoft-azure-eventhubs-extensions ../core azure-eventhubs From a0cc90adbf2b5b7fe93f130068c1d9fca5ef78b2 Mon Sep 17 00:00:00 2001 From: Connie Yau Date: Mon, 15 Jul 2019 14:44:44 -0700 Subject: [PATCH 83/85] Enable live tests for Event Hubs client library (#4423) * Add live tests for event hubs. * Do not stop the EventHubConsumer when there are no messages received within a timeframe. Keep the link open indefinitely. * Fix bug where starting consumption at incorrect location. --- .../messaging/eventhubs/EventHubConsumer.java | 5 +- .../EventPositionIntegrationTest.java | 2 +- .../eventhubs/SetPrefetchCountTest.java | 71 ++++++++++++++----- sdk/eventhubs/tests.yml | 10 +++ 4 files changed, 65 insertions(+), 23 deletions(-) create mode 100644 sdk/eventhubs/tests.yml diff --git a/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java index 19bdefe5663c8..a76b11d722a6a 100644 --- a/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java +++ b/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumer.java @@ -3,8 +3,8 @@ package com.azure.messaging.eventhubs; -import com.azure.core.util.logging.ClientLogger; import com.azure.core.implementation.annotation.Immutable; +import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.implementation.AmqpReceiveLink; import com.azure.messaging.eventhubs.models.EventHubConsumerOptions; import com.azure.messaging.eventhubs.models.EventPosition; @@ -84,8 +84,7 @@ public class EventHubConsumer implements Closeable { } return link.receive().map(EventData::new); - }).timeout(operationTimeout) - .subscribeWith(emitterProcessor) + }).subscribeWith(emitterProcessor) .doOnSubscribe(subscription -> { AmqpReceiveLink existingLink = RECEIVE_LINK_FIELD_UPDATER.get(this); if (existingLink == null) { diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java index 04a8f19aab2dd..30921adf1ba5a 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventPositionIntegrationTest.java @@ -28,6 +28,7 @@ import java.util.concurrent.atomic.AtomicReference; import static com.azure.messaging.eventhubs.EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME; +import static com.azure.messaging.eventhubs.TestUtils.MESSAGE_TRACKING_ID; import static com.azure.messaging.eventhubs.TestUtils.isMatchingEvent; import static java.nio.charset.StandardCharsets.UTF_8; @@ -43,7 +44,6 @@ public class EventPositionIntegrationTest extends ApiTestBase { private static final AtomicBoolean HAS_PUSHED_EVENTS = new AtomicBoolean(); private static final AtomicReference EVENTS_PUSHED = new AtomicReference<>(); private static final String MESSAGE_POSITION_ID = "message-position"; - private static final String MESSAGE_TRACKING_ID = "message-tracking-id"; private static final String MESSAGE_TRACKING_VALUE = UUID.randomUUID().toString(); private static final AtomicReference MESSAGES_PUSHED_INSTANT = new AtomicReference<>(); diff --git a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java index 80d1c7548cb26..be7a5dd4dd529 100644 --- a/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java +++ b/sdk/eventhubs/azure-eventhubs/src/test/java/com/azure/messaging/eventhubs/SetPrefetchCountTest.java @@ -8,6 +8,7 @@ import com.azure.messaging.eventhubs.implementation.ApiTestBase; import com.azure.messaging.eventhubs.implementation.ReactorHandlerProvider; import com.azure.messaging.eventhubs.models.EventHubConsumerOptions; +import com.azure.messaging.eventhubs.models.EventHubProducerOptions; import com.azure.messaging.eventhubs.models.EventPosition; import org.junit.Assert; import org.junit.Rule; @@ -16,21 +17,33 @@ import reactor.core.Disposable; import reactor.core.publisher.Flux; +import java.time.Instant; +import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; -import static java.nio.charset.StandardCharsets.UTF_8; +import static com.azure.messaging.eventhubs.TestUtils.isMatchingEvent; /** * Verifies we can use various prefetch options with {@link EventHubConsumer}. */ public class SetPrefetchCountTest extends ApiTestBase { - private static final String PARTITION_ID = "0"; + private static final String PARTITION_ID = "1"; // Default number of events to fetch when creating the consumer. private static final int DEFAULT_PREFETCH_COUNT = 500; + // Set a large number of events to send to the service. + private static final int NUMBER_OF_EVENTS = DEFAULT_PREFETCH_COUNT * 3; + + // We use these values to keep track of the events we've pushed to the service and ensure the events we receive are + // our own. + private static final AtomicBoolean HAS_PUSHED_EVENTS = new AtomicBoolean(); + private static final String MESSAGE_TRACKING_VALUE = UUID.randomUUID().toString(); + private static final AtomicReference MESSAGES_PUSHED_INSTANT = new AtomicReference<>(); + private EventHubAsyncClient client; - private EventHubProducer producer; private EventHubConsumer consumer; @Rule @@ -51,12 +64,13 @@ protected void beforeTest() { final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(getReactorProvider()); client = new EventHubAsyncClient(getConnectionOptions(), getReactorProvider(), handlerProvider); - producer = client.createProducer(); + + setupEventTestData(client); } @Override protected void afterTest() { - dispose(producer, consumer, client); + dispose(consumer, client); } /** @@ -67,24 +81,22 @@ public void setLargePrefetchCount() throws InterruptedException { // Arrange // Since we cannot test receiving very large prefetch like 10000 in a unit test, DefaultPrefetchCount * 3 was // chosen - final int eventCount = DEFAULT_PREFETCH_COUNT * 3; + final int eventCount = NUMBER_OF_EVENTS; final CountDownLatch countDownLatch = new CountDownLatch(eventCount); final EventHubConsumerOptions options = new EventHubConsumerOptions() .retry(Retry.getDefaultRetry()) .prefetchCount(2000); consumer = client.createConsumer(EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME, PARTITION_ID, - EventPosition.latest(), options); + EventPosition.fromEnqueuedTime(MESSAGES_PUSHED_INSTANT.get()), options); final Disposable subscription = consumer.receive() - .take(eventCount + 1).subscribe(event -> countDownLatch.countDown()); + .filter(x -> isMatchingEvent(x, MESSAGE_TRACKING_VALUE)) + .take(eventCount).subscribe(event -> countDownLatch.countDown()); // Act try { - final Flux events = Flux.range(0, eventCount).map(number -> new EventData("c".getBytes(UTF_8))); - producer.send(events).block(); - - countDownLatch.await(45, TimeUnit.SECONDS); + countDownLatch.await(1, TimeUnit.MINUTES); // Assert Assert.assertEquals(0, countDownLatch.getCount()); @@ -104,17 +116,13 @@ public void setSmallPrefetchCount() throws InterruptedException { final EventHubConsumerOptions options = new EventHubConsumerOptions().prefetchCount(11); consumer = client.createConsumer(EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME, PARTITION_ID, - EventPosition.latest(), options); + EventPosition.fromEnqueuedTime(MESSAGES_PUSHED_INSTANT.get()), options); - final Disposable subscription = consumer.receive() - .take(eventCount + 1).subscribe(event -> countDownLatch.countDown()); + final Disposable subscription = consumer.receive().filter(x -> isMatchingEvent(x, MESSAGE_TRACKING_VALUE)) + .take(eventCount).subscribe(event -> countDownLatch.countDown()); try { // Act - final Flux events = Flux.range(0, eventCount) - .map(number -> new EventData("testString".getBytes(UTF_8))); - producer.send(events).block(TIMEOUT); - countDownLatch.await(45, TimeUnit.SECONDS); // Assert @@ -123,4 +131,29 @@ public void setSmallPrefetchCount() throws InterruptedException { subscription.dispose(); } } + + /** + * When we run this test, we check if there have been events already pushed to the partition, if not, we push some + * events there. + */ + private void setupEventTestData(EventHubAsyncClient client) { + if (HAS_PUSHED_EVENTS.getAndSet(true)) { + logger.info("Already pushed events to partition. Skipping."); + return; + } + + logger.info("Pushing events to partition. Message tracking value: {}", MESSAGE_TRACKING_VALUE); + + final EventHubProducerOptions producerOptions = new EventHubProducerOptions() + .partitionId(PARTITION_ID); + final EventHubProducer producer = client.createProducer(producerOptions); + final Flux events = TestUtils.getEvents(NUMBER_OF_EVENTS, MESSAGE_TRACKING_VALUE); + + try { + MESSAGES_PUSHED_INSTANT.set(Instant.now()); + producer.send(events).block(TIMEOUT); + } finally { + dispose(producer); + } + } } diff --git a/sdk/eventhubs/tests.yml b/sdk/eventhubs/tests.yml new file mode 100644 index 0000000000000..e6aa03d5f6a63 --- /dev/null +++ b/sdk/eventhubs/tests.yml @@ -0,0 +1,10 @@ +trigger: none + +jobs: + - template: ../../eng/pipelines/templates/jobs/archetype-sdk-tests.yml + parameters: + ServiceDirectory: eventhubs + EnvVars: + AZURE_EVENTHUBS_CONNECTION_STRING: $(java-event-hubs-test-connection-string) + AZURE_TEST_MODE: RECORD + AZURE_LOG_LEVEL: 4 From 4eca419d21b3bcdd2cef38c1e4dfd40505252337 Mon Sep 17 00:00:00 2001 From: Connie Yau Date: Mon, 15 Jul 2019 15:18:36 -0700 Subject: [PATCH 84/85] Disable flakey test. (#4435) --- .../java/com/azure/core/http/ReactorNettyClientTests.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/sdk/core/azure-core/src/test/java/com/azure/core/http/ReactorNettyClientTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/http/ReactorNettyClientTests.java index 4d486fc00cdf1..d5b182d585927 100644 --- a/sdk/core/azure-core/src/test/java/com/azure/core/http/ReactorNettyClientTests.java +++ b/sdk/core/azure-core/src/test/java/com/azure/core/http/ReactorNettyClientTests.java @@ -72,7 +72,6 @@ public void testFlowableResponseLongBodyAsByteArrayAsync() { checkBodyReceived(LONG_BODY, "/long"); } - @Test public void testMultipleSubscriptionsEmitsError() { HttpResponse response = getResponse("/short"); @@ -94,8 +93,6 @@ public void testDispose() throws InterruptedException { Assert.assertTrue(response.internConnection().isDisposed()); } - - @Test public void testCancel() { HttpResponse response = getResponse("/long"); @@ -217,6 +214,7 @@ public void testServerShutsDownSocketShouldPushErrorToContentFlowable() } } + @Ignore("This flakey test fails often on MacOS. https://github.com/Azure/azure-sdk-for-java/issues/4357.") @Test public void testConcurrentRequests() throws NoSuchAlgorithmException { long t = System.currentTimeMillis(); From fa17e70a210b0b7b9d67a63c7979d6b1d765f6a6 Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Mon, 15 Jul 2019 16:21:24 -0700 Subject: [PATCH 85/85] Keyvault context for async clients (#4430) * Support context for ConfigurationAsyncClient APIs * Enable reactor context for KeyVault Keys and Secrets async client * Fix formatting * Remove unused import * Add missing annotations --- .../keyvault/keys/KeyAsyncClient.java | 122 ++++++++++-------- .../keyvault/secrets/SecretAsyncClient.java | 93 +++++++------ 2 files changed, 125 insertions(+), 90 deletions(-) diff --git a/sdk/keyvault/azure-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java b/sdk/keyvault/azure-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java index f1e5d5057d5f0..b8b4ad5c4816c 100644 --- a/sdk/keyvault/azure-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java +++ b/sdk/keyvault/azure-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/KeyAsyncClient.java @@ -13,7 +13,9 @@ import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedFlux; import com.azure.core.implementation.RestProxy; +import com.azure.core.implementation.annotation.ReturnType; import com.azure.core.implementation.annotation.ServiceClient; +import com.azure.core.implementation.annotation.ServiceMethod; import com.azure.core.util.logging.ClientLogger; import com.azure.security.keyvault.keys.models.DeletedKey; import com.azure.security.keyvault.keys.models.EcKeyCreateOptions; @@ -34,6 +36,8 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import static com.azure.core.implementation.util.FluxUtil.monoContext; + /** * The KeyAsyncClient provides asynchronous methods to manage {@link Key keys} in the Azure Key Vault. The client * supports creating, retrieving, updating, deleting, purging, backing up, restoring and listing the {@link Key keys}. The client @@ -91,12 +95,13 @@ public final class KeyAsyncClient { * @throws HttpRequestException if {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Key created key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createKey(String name, KeyType keyType) { KeyRequestParameters parameters = new KeyRequestParameters().kty(keyType); - return service.createKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.createKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Creating key - {}", name)) .doOnSuccess(response -> logger.info("Created key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to create key - {}", name, error)); + .doOnError(error -> logger.warning("Failed to create key - {}", name, error))); } /** @@ -127,16 +132,17 @@ public Mono> createKey(String name, KeyType keyType) { * @throws HttpRequestException if {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Key created key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createKey(KeyCreateOptions keyCreateOptions) { Objects.requireNonNull(keyCreateOptions, "The key options parameter cannot be null."); KeyRequestParameters parameters = new KeyRequestParameters() .kty(keyCreateOptions.keyType()) .keyOps(keyCreateOptions.keyOperations()) .keyAttributes(new KeyRequestAttributes(keyCreateOptions)); - return service.createKey(endpoint, keyCreateOptions.name(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.createKey(endpoint, keyCreateOptions.name(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Creating key - {}", keyCreateOptions.name())) .doOnSuccess(response -> logger.info("Created key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to create key - {}", keyCreateOptions.name(), error)); + .doOnError(error -> logger.warning("Failed to create key - {}", keyCreateOptions.name(), error))); } /** @@ -169,6 +175,7 @@ public Mono> createKey(KeyCreateOptions keyCreateOptions) { * @throws HttpRequestException if {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Key created key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createRsaKey(RsaKeyCreateOptions rsaKeyCreateOptions) { Objects.requireNonNull(rsaKeyCreateOptions, "The Rsa key options parameter cannot be null."); KeyRequestParameters parameters = new KeyRequestParameters() @@ -176,10 +183,10 @@ public Mono> createRsaKey(RsaKeyCreateOptions rsaKeyCreateOptions) .keySize(rsaKeyCreateOptions.keySize()) .keyOps(rsaKeyCreateOptions.keyOperations()) .keyAttributes(new KeyRequestAttributes(rsaKeyCreateOptions)); - return service.createKey(endpoint, rsaKeyCreateOptions.name(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.createKey(endpoint, rsaKeyCreateOptions.name(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Creating Rsa key - {}", rsaKeyCreateOptions.name())) .doOnSuccess(response -> logger.info("Created Rsa key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to create Rsa key - {}", rsaKeyCreateOptions.name(), error)); + .doOnError(error -> logger.warning("Failed to create Rsa key - {}", rsaKeyCreateOptions.name(), error))); } /** @@ -212,6 +219,7 @@ public Mono> createRsaKey(RsaKeyCreateOptions rsaKeyCreateOptions) * @throws HttpRequestException if {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Key created key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createEcKey(EcKeyCreateOptions ecKeyCreateOptions) { Objects.requireNonNull(ecKeyCreateOptions, "The Ec key options options cannot be null."); KeyRequestParameters parameters = new KeyRequestParameters() @@ -219,10 +227,10 @@ public Mono> createEcKey(EcKeyCreateOptions ecKeyCreateOptions) { .curve(ecKeyCreateOptions.curve()) .keyOps(ecKeyCreateOptions.keyOperations()) .keyAttributes(new KeyRequestAttributes(ecKeyCreateOptions)); - return service.createKey(endpoint, ecKeyCreateOptions.name(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.createKey(endpoint, ecKeyCreateOptions.name(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Creating Ec key - {}", ecKeyCreateOptions.name())) .doOnSuccess(response -> logger.info("Created Ec key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to create Ec key - {}", ecKeyCreateOptions.name(), error)); + .doOnError(error -> logger.warning("Failed to create Ec key - {}", ecKeyCreateOptions.name(), error))); } /** @@ -242,12 +250,13 @@ public Mono> createEcKey(EcKeyCreateOptions ecKeyCreateOptions) { * @throws HttpRequestException if {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Key imported key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> importKey(String name, JsonWebKey keyMaterial) { KeyImportRequestParameters parameters = new KeyImportRequestParameters().key(keyMaterial); - return service.importKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.importKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Importing key - {}", name)) .doOnSuccess(response -> logger.info("Imported key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to import key - {}", name, error)); + .doOnError(error -> logger.warning("Failed to import key - {}", name, error))); } /** @@ -276,16 +285,17 @@ public Mono> importKey(String name, JsonWebKey keyMaterial) { * @throws HttpRequestException if {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Key imported key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> importKey(KeyImportOptions keyImportOptions) { Objects.requireNonNull(keyImportOptions, "The key import configuration parameter cannot be null."); KeyImportRequestParameters parameters = new KeyImportRequestParameters() .key(keyImportOptions.keyMaterial()) .hsm(keyImportOptions.hsm()) .keyAttributes(new KeyRequestAttributes(keyImportOptions)); - return service.importKey(endpoint, keyImportOptions.name(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.importKey(endpoint, keyImportOptions.name(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Importing key - {}", keyImportOptions.name())) .doOnSuccess(response -> logger.info("Imported key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to import key - {}", keyImportOptions.name(), error)); + .doOnError(error -> logger.warning("Failed to import key - {}", keyImportOptions.name(), error))); } /** @@ -307,15 +317,15 @@ public Mono> importKey(KeyImportOptions keyImportOptions) { * @throws HttpRequestException if {@code name} or {@code version} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the requested {@link Key key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getKey(String name, String version) { - String keyVersion = ""; - if (version != null) { - keyVersion = version; + if (version == null) { + return getKey(name); } - return service.getKey(endpoint, name, keyVersion, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.getKey(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); + .doOnError(error -> logger.warning("Failed to get key - {}", name, error))); } /** @@ -336,11 +346,12 @@ public Mono> getKey(String name, String version) { * @throws HttpRequestException if {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the requested {@link Key key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getKey(String name) { - return getKey(name, "") + return monoContext(context -> getKey(name, "") .doOnRequest(ignored -> logger.info("Retrieving key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); + .doOnError(error -> logger.warning("Failed to get key - {}", name, error))); } @@ -362,16 +373,14 @@ public Mono> getKey(String name) { * @throws HttpRequestException if {@link KeyBase#name()} name} or {@link KeyBase#version() version} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the requested {@link Key key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getKey(KeyBase keyBase) { Objects.requireNonNull(keyBase, "The Key Base parameter cannot be null."); - String keyVersion = ""; - if (keyBase.version() != null) { - keyVersion = keyBase.version(); + if (keyBase.version() == null) { + return getKey(keyBase.name()); } - return service.getKey(endpoint, keyBase.name(), keyVersion, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) - .doOnRequest(ignored -> logger.info("Retrieving key - {}", keyBase.name())) - .doOnSuccess(response -> logger.info("Retrieved key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to get key - {}", keyBase.name(), error)); + + return getKey(keyBase.name(), keyBase.version()); } /** @@ -398,16 +407,17 @@ public Mono> getKey(KeyBase keyBase) { * @throws HttpRequestException if {@link KeyBase#name() name} or {@link KeyBase#version() version} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link KeyBase updated key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> updateKey(KeyBase key) { Objects.requireNonNull(key, "The key input parameter cannot be null."); KeyRequestParameters parameters = new KeyRequestParameters() .tags(key.tags()) .keyAttributes(new KeyRequestAttributes(key)); - return service.updateKey(endpoint, key.name(), key.version(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.updateKey(endpoint, key.name(), key.version(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Updating key - {}", key.name())) .doOnSuccess(response -> logger.info("Updated key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to update key - {}", key.name(), error)); + .doOnError(error -> logger.warning("Failed to update key - {}", key.name(), error))); } /** @@ -435,6 +445,7 @@ public Mono> updateKey(KeyBase key) { * @throws HttpRequestException if {@link KeyBase#name() name} or {@link KeyBase#version() version} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link KeyBase updated key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> updateKey(KeyBase key, KeyOperation... keyOperations) { Objects.requireNonNull(key, "The key input parameter cannot be null."); KeyRequestParameters parameters = new KeyRequestParameters() @@ -442,10 +453,10 @@ public Mono> updateKey(KeyBase key, KeyOperation... keyOperations) .keyOps(Arrays.asList(keyOperations)) .keyAttributes(new KeyRequestAttributes(key)); - return service.updateKey(endpoint, key.name(), key.version(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.updateKey(endpoint, key.name(), key.version(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Updating key - {}", key.name())) .doOnSuccess(response -> logger.info("Updated key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to update key - {}", key.name(), error)); + .doOnError(error -> logger.warning("Failed to update key - {}", key.name(), error))); } /** @@ -468,11 +479,12 @@ public Mono> updateKey(KeyBase key, KeyOperation... keyOperations) * @throws HttpRequestException when a key with {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link DeletedKey deleted key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteKey(String name) { - return service.deleteKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.deleteKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Deleting key - {}", name)) .doOnSuccess(response -> logger.info("Deleted key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to delete key - {}", name, error)); + .doOnError(error -> logger.warning("Failed to delete key - {}", name, error))); } /** @@ -493,11 +505,12 @@ public Mono> deleteKey(String name) { * @throws HttpRequestException when a key with {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link DeletedKey deleted key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getDeletedKey(String name) { - return service.getDeletedKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.getDeletedKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Retrieving deleted key - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to get key - {}", name, error)); + .doOnError(error -> logger.warning("Failed to get key - {}", name, error))); } /** @@ -518,11 +531,12 @@ public Mono> getDeletedKey(String name) { * @throws HttpRequestException when a key with {@code name} is empty string. * @return A {@link Mono} containing a {@link VoidResponse}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono purgeDeletedKey(String name) { - return service.purgeDeletedKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.purgeDeletedKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Purging deleted key - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted key - {}", name)) - .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error)); + .doOnError(error -> logger.warning("Failed to purge deleted key - {}", name, error))); } /** @@ -544,11 +558,12 @@ public Mono purgeDeletedKey(String name) { * @throws HttpRequestException when a key with {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Key recovered key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> recoverDeletedKey(String name) { - return service.recoverDeletedKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.recoverDeletedKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Recovering deleted key - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error)); + .doOnError(error -> logger.warning("Failed to recover deleted key - {}", name, error))); } /** @@ -574,13 +589,14 @@ public Mono> recoverDeletedKey(String name) { * @throws HttpRequestException when a key with {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the backed up key blob. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> backupKey(String name) { - return service.backupKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.backupKey(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Backing up key - {}", name)) .doOnSuccess(response -> logger.info("Backed up key - {}", name)) .doOnError(error -> logger.warning("Failed to backup key - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse(base64URLResponse.request(), - base64URLResponse.statusCode(), base64URLResponse.headers(), base64URLResponse.value().value()))); + base64URLResponse.statusCode(), base64URLResponse.headers(), base64URLResponse.value().value())))); } /** @@ -605,12 +621,13 @@ public Mono> backupKey(String name) { * @throws ResourceModifiedException when {@code backup} blob is malformed. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Key restored key}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> restoreKey(byte[] backup) { KeyRestoreRequestParameters parameters = new KeyRestoreRequestParameters().keyBackup(backup); - return service.restoreKey(endpoint, API_VERSION, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.restoreKey(endpoint, API_VERSION, parameters, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Attempting to restore key")) .doOnSuccess(response -> logger.info("Restored Key - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to restore key - {}", error)); + .doOnError(error -> logger.warning("Failed to restore key - {}", error))); } /** @@ -628,10 +645,11 @@ public Mono> restoreKey(byte[] backup) { * * @return A {@link PagedFlux} containing {@link KeyBase key} of all the keys in the vault. */ + @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listKeys() { - return new PagedFlux<>(() -> - listKeysFirstPage(), - continuationToken -> listKeysNextPage(continuationToken)); + return new PagedFlux<>( + () -> monoContext(context -> listKeysFirstPage()), + continuationToken -> monoContext(context -> listKeysNextPage(continuationToken))); } /* @@ -673,10 +691,11 @@ private Mono> listKeysFirstPage() { * * @return A {@link PagedFlux} containing all of the {@link DeletedKey deleted keys} in the vault. */ + @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listDeletedKeys() { - return new PagedFlux<>(() -> - listDeletedKeysFirstPage(), - continuationToken -> listDeletedKeysNextPage(continuationToken)); + return new PagedFlux<>( + () -> monoContext(context -> listDeletedKeysFirstPage()), + continuationToken -> monoContext(context -> listDeletedKeysNextPage(continuationToken))); } /* @@ -722,10 +741,11 @@ private Mono> listDeletedKeysFirstPage() { * @throws HttpRequestException when a key with {@code name} is empty string. * @return A {@link PagedFlux} containing {@link KeyBase key} of all the versions of the specified key in the vault. Flux is empty if key with {@code name} does not exist in key vault. */ + @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listKeyVersions(String name) { - return new PagedFlux<>(() -> - listKeyVersionsFirstPage(name), - continuationToken -> listKeyVersionsNextPage(continuationToken)); + return new PagedFlux<>( + () -> monoContext(context -> listKeyVersionsFirstPage(name)), + continuationToken -> monoContext(context -> listKeyVersionsNextPage(continuationToken))); } private Mono> listKeyVersionsFirstPage(String name) { diff --git a/sdk/keyvault/azure-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java b/sdk/keyvault/azure-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java index d7f491e520303..8adfceac47ffe 100644 --- a/sdk/keyvault/azure-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java +++ b/sdk/keyvault/azure-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/SecretAsyncClient.java @@ -10,7 +10,9 @@ import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.implementation.RestProxy; +import com.azure.core.implementation.annotation.ReturnType; import com.azure.core.implementation.annotation.ServiceClient; +import com.azure.core.implementation.annotation.ServiceMethod; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; import com.azure.security.keyvault.secrets.models.DeletedSecret; @@ -26,6 +28,8 @@ import com.azure.core.exception.ResourceModifiedException; import com.azure.core.exception.HttpRequestException; +import static com.azure.core.implementation.util.FluxUtil.monoContext; + /** * The SecretAsyncClient provides asynchronous methods to manage {@link Secret secrets} in the Azure Key Vault. The client * supports creating, retrieving, updating, deleting, purging, backing up, restoring and listing the {@link Secret secrets}. The client @@ -87,6 +91,7 @@ public final class SecretAsyncClient { * @throws HttpRequestException if {@link Secret#name() name} or {@link Secret#value() value} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Secret created secret}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setSecret(Secret secret) { Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() @@ -95,10 +100,10 @@ public Mono> setSecret(Secret secret) { .contentType(secret.contentType()) .secretAttributes(new SecretRequestAttributes(secret)); - return service.setSecret(endpoint, secret.name(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.setSecret(endpoint, secret.name(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.name())) .doOnSuccess(response -> logger.info("Set secret - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to set secret - {}", secret.name(), error)); + .doOnError(error -> logger.warning("Failed to set secret - {}", secret.name(), error))); } /** @@ -119,12 +124,13 @@ public Mono> setSecret(Secret secret) { * @throws HttpRequestException if {@code name} or {@code value} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Secret created secret}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setSecret(String name, String value) { SecretRequestParameters parameters = new SecretRequestParameters().value(value); - return service.setSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.setSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Setting secret - {}", name)) .doOnSuccess(response -> logger.info("Set secret - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to set secret - {}", name, error)); + .doOnError(error -> logger.warning("Failed to set secret - {}", name, error))); } /** @@ -147,15 +153,16 @@ public Mono> setSecret(String name, String value) { * @throws HttpRequestException if {@code name} name} or {@code version} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the requested {@link Secret secret}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getSecret(String name, String version) { - String secretVersion = ""; - if (version != null) { - secretVersion = version; + if (version == null) { + return getSecret(name); } - return service.getSecret(endpoint, name, secretVersion, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + + return monoContext(context -> service.getSecret(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignoredValue -> logger.info("Retrieving secret - {}", name)) .doOnSuccess(response -> logger.info("Retrieved secret - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to get secret - {}", name, error)); + .doOnError(error -> logger.warning("Failed to get secret - {}", name, error))); } /** @@ -176,16 +183,13 @@ public Mono> getSecret(String name, String version) { * @throws HttpRequestException if {@link SecretBase#name()} name} or {@link SecretBase#version() version} is empty string. * @return A {@link Response} whose {@link Response#value() value} contains the requested {@link Secret secret}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getSecret(SecretBase secretBase) { Objects.requireNonNull(secretBase, "The Secret Base parameter cannot be null."); - String secretVersion = ""; - if (secretBase.version() != null) { - secretVersion = secretBase.version(); + if (secretBase.version() == null) { + return getSecret(secretBase.name()); } - return service.getSecret(endpoint, secretBase.name(), secretVersion, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) - .doOnRequest(ignoredValue -> logger.info("Retrieving secret - {}", secretBase.name())) - .doOnSuccess(response -> logger.info("Retrieved secret - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to get secret - {}", secretBase.name(), error)); + return getSecret(secretBase.name(), secretBase.version()); } /** * Get the latest version of the specified secret from the key vault. The get operation is applicable to any secret stored in Azure Key Vault. @@ -205,6 +209,7 @@ public Mono> getSecret(SecretBase secretBase) { * @throws HttpRequestException if {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the requested {@link Secret secret}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getSecret(String name) { return getSecret(name, ""); } @@ -234,6 +239,7 @@ public Mono> getSecret(String name) { * @throws HttpRequestException if {@link SecretBase#name()} name} or {@link SecretBase#version() version} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link SecretBase updated secret}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> updateSecret(SecretBase secret) { Objects.requireNonNull(secret, "The secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() @@ -241,10 +247,10 @@ public Mono> updateSecret(SecretBase secret) { .contentType(secret.contentType()) .secretAttributes(new SecretRequestAttributes(secret)); - return service.updateSecret(endpoint, secret.name(), secret.version(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.updateSecret(endpoint, secret.name(), secret.version(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Updating secret - {}", secret.name())) .doOnSuccess(response -> logger.info("Updated secret - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to update secret - {}", secret.name(), error)); + .doOnError(error -> logger.warning("Failed to update secret - {}", secret.name(), error))); } /** @@ -265,11 +271,12 @@ public Mono> updateSecret(SecretBase secret) { * @throws HttpRequestException when a secret with {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link DeletedSecret deleted secret}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteSecret(String name) { - return service.deleteSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.deleteSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Deleting secret - {}", name)) .doOnSuccess(response -> logger.info("Deleted secret - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to delete secret - {}", name, error)); + .doOnError(error -> logger.warning("Failed to delete secret - {}", name, error))); } /** @@ -290,11 +297,12 @@ public Mono> deleteSecret(String name) { * @throws HttpRequestException when a secret with {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link DeletedSecret deleted secret}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getDeletedSecret(String name) { - return service.getDeletedSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.getDeletedSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Retrieving deleted secret - {}", name)) .doOnSuccess(response -> logger.info("Retrieved deleted secret - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to retrieve deleted secret - {}", name, error)); + .doOnError(error -> logger.warning("Failed to retrieve deleted secret - {}", name, error))); } /** @@ -315,11 +323,12 @@ public Mono> getDeletedSecret(String name) { * @throws HttpRequestException when a secret with {@code name} is empty string. * @return A {@link Mono} containing a {@link VoidResponse}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono purgeDeletedSecret(String name) { - return service.purgeDeletedSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.purgeDeletedSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Purging deleted secret - {}", name)) .doOnSuccess(response -> logger.info("Purged deleted secret - {}", name)) - .doOnError(error -> logger.warning("Failed to purge deleted secret - {}", name, error)); + .doOnError(error -> logger.warning("Failed to purge deleted secret - {}", name, error))); } /** @@ -340,11 +349,12 @@ public Mono purgeDeletedSecret(String name) { * @throws HttpRequestException when a secret with {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Secret recovered secret}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> recoverDeletedSecret(String name) { - return service.recoverDeletedSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.recoverDeletedSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Recovering deleted secret - {}", name)) .doOnSuccess(response -> logger.info("Recovered deleted secret - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to recover deleted secret - {}", name, error)); + .doOnError(error -> logger.warning("Failed to recover deleted secret - {}", name, error))); } /** @@ -364,13 +374,14 @@ public Mono> recoverDeletedSecret(String name) { * @throws HttpRequestException when a secret with {@code name} is empty string. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the backed up secret blob. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> backupSecret(String name) { - return service.backupSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.backupSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Backing up secret - {}", name)) .doOnSuccess(response -> logger.info("Backed up secret - {}", name)) .doOnError(error -> logger.warning("Failed to back up secret - {}", name, error)) .flatMap(base64URLResponse -> Mono.just(new SimpleResponse(base64URLResponse.request(), - base64URLResponse.statusCode(), base64URLResponse.headers(), base64URLResponse.value().value()))); + base64URLResponse.statusCode(), base64URLResponse.headers(), base64URLResponse.value().value())))); } /** @@ -389,12 +400,13 @@ public Mono> backupSecret(String name) { * @throws ResourceModifiedException when {@code backup} blob is malformed. * @return A {@link Mono} containing a {@link Response} whose {@link Response#value() value} contains the {@link Secret restored secret}. */ + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> restoreSecret(byte[] backup) { SecretRestoreRequestParameters parameters = new SecretRestoreRequestParameters().secretBackup(backup); - return service.restoreSecret(endpoint, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) + return monoContext(context -> service.restoreSecret(endpoint, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE) .doOnRequest(ignored -> logger.info("Attempting to restore secret")) .doOnSuccess(response -> logger.info("Restored secret - {}", response.value().name())) - .doOnError(error -> logger.warning("Failed to restore secret", error)); + .doOnError(error -> logger.warning("Failed to restore secret", error))); } /** @@ -412,10 +424,11 @@ public Mono> restoreSecret(byte[] backup) { * * @return A {@link PagedFlux} containing {@link SecretBase secret} of all the secrets in the vault. */ + @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listSecrets() { - return new PagedFlux<>(() -> - listSecretsFirstPage(), - continuationToken -> listSecretsNextPage(continuationToken)); + return new PagedFlux<>( + () -> monoContext(context -> listSecretsFirstPage()), + continuationToken -> monoContext(context -> listSecretsNextPage(continuationToken))); } /* @@ -456,10 +469,11 @@ private Mono> listSecretsFirstPage() { * * @return A {@link Flux} containing all of the {@link DeletedSecret deleted secrets} in the vault. */ + @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listDeletedSecrets() { - return new PagedFlux<>(() -> - listDeletedSecretsFirstPage(), - continuationToken -> listDeletedSecretsNextPage(continuationToken, Context.NONE)); + return new PagedFlux<>( + () -> monoContext(context -> listDeletedSecretsFirstPage()), + continuationToken -> monoContext(context -> listDeletedSecretsNextPage(continuationToken, Context.NONE))); } /** @@ -505,10 +519,11 @@ private Mono> listDeletedSecretsFirstPage() { * @throws HttpRequestException when a secret with {@code name} is empty string. * @return A {@link PagedFlux} containing {@link SecretBase secret} of all the versions of the specified secret in the vault. Flux is empty if secret with {@code name} does not exist in key vault */ + @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listSecretVersions(String name) { - return new PagedFlux<>(() -> - listSecretVersionsFirstPage(name), - continuationToken -> listSecretVersionsNextPage(continuationToken)); + return new PagedFlux<>( + () -> monoContext(context -> listSecretVersionsFirstPage(name)), + continuationToken -> monoContext(context -> listSecretVersionsNextPage(continuationToken))); } /*